;; -*- lexical-binding: t; -*-

;;; Portability macros
(defmacro jao-syscase (clauses)
  (let ((cls (assoc system-type clauses)))
    (when cls `(progn ,@(cdr cls)))))

(defmacro jao-d-l (darw linux)
  `(jao-syscase ((darwin ,darw) (gnu/linux ,linux))))

(defmacro jao-when-darwin (&rest body)
  `(jao-syscase ((darwin ,@body))))

(defmacro jao-when-linux (&rest body)
  `(jao-syscase ((gnu/linux ,@body))))

(defun jao-is-linux () (jao-when-linux t))
(defun jao-is-darwin () (jao-when-darwin t))

;;; Initialisation
;;;; Bootstrap and use package
(defvar jao-emacs-dir
  (expand-file-name (jao-d-l "~/.emacs.d/config" "~/etc/emacs")))

(setq package-user-dir
      (expand-file-name (format "~/.emacs.d/elpa.%s" emacs-major-version))
      package-check-signature 'allow-unsigned)

(require 'package)
(setq package-archives
      '(("gnu-devel" . "https://elpa.gnu.org/devel/")
        ("nongnu-devel" . "https://elpa.nongnu.org/nongnu-devel/")
        ("melpa" . "https://melpa.org/packages/"))
      package-archive-priorities '(("gnu-devel" . 2)
                                   ("nongnu-devel" . 1)
                                   ("melpa" . 0)))

(package-initialize)

(unless (package-installed-p 'use-package)
  (package-refresh-contents)
  (package-install 'use-package))
(require 'use-package)

(use-package gnu-elpa-keyring-update :ensure t)

;;;; .elc vs .el loading

(setq load-prefer-newer t)
(setq comp-async-report-warnings-errors nil
      warning-suppress-types '((comp)))

;;; Paths
(defvar jao-local-lisp-dir (jao-d-l "~/.emacs.d/lib" "~/lib/elisp")
  "Directory for external elisp libraries and repos")

(defvar jao-data-dir (expand-file-name "data" jao-emacs-dir)
  "Directory containing static data, such as images.")

(defun jao-data-file (file) (expand-file-name file jao-data-dir))

(defvar jao-doc-dir (expand-file-name (jao-d-l "~/Documents" "~/doc")))

(setq jao-org-dir (expand-file-name "org" jao-doc-dir))

(defvar jao-sink-dir
  (file-name-as-directory (expand-file-name "sink" jao-doc-dir))
  "Directory used for downloads and such.")

(defvar jao-site-dir (expand-file-name "site" jao-emacs-dir))
(defun jao-site-el (basename &optional gpg)
  (expand-file-name (concat basename ".el" (when gpg ".gpg")) jao-site-dir))

(defun jao-load-site-el (basename &optional gpg)
  (let ((lf (jao-site-el basename gpg)))
    (if (file-exists-p lf)
        (load lf)
      (message "Attempted to load non existing %s" lf))))

(defun jao-exec-path (dir)
  (let ((fn (expand-file-name dir)))
    (setq exec-path (remove fn exec-path))
    (add-to-list 'exec-path fn)
    (setenv "PATH" (concat fn ":" (getenv "PATH")))))

(defun jao-load-path (subdir)
  "Add to load path a subdir of `jao-local-lisp-dir'"
  (let ((path (expand-file-name subdir jao-local-lisp-dir)))
    (when (file-directory-p path) (add-to-list 'load-path path))))

;;;; load and info path initialisation
(add-to-list 'load-path jao-site-dir)
(add-to-list 'load-path jao-local-lisp-dir)
(add-to-list 'load-path (expand-file-name "custom" jao-emacs-dir))
(add-to-list 'load-path "/usr/local/share/emacs/site-lisp/")

(let ((libd (expand-file-name "lib" jao-emacs-dir)))
  (add-to-list 'load-path libd)
  (dolist (f (directory-files libd t "^[^.]+$"))
    (when (file-directory-p f) (add-to-list 'load-path f))))

(defvar jao-info-dir (expand-file-name "info" jao-doc-dir))
(require 'info)
(add-to-list 'Info-directory-list jao-info-dir)

(jao-when-darwin (require 'jao-custom-mac))

(jao-exec-path (expand-file-name "bin" jao-emacs-dir))

;;;; custom location of custom.el and co.
(setq custom-file (jao-site-el "custom"))
(when (file-exists-p custom-file) (load custom-file))
(setq custom-unlispify-tag-names nil)
(setq custom-buffer-done-kill t)
(setq custom-raised-buttons nil)

;;;; compatibility
(when (< emacs-major-version 30)
  (use-package compat :ensure t :demand t)
  (require 'jao-multisession))

;;; Preamble
(jao-load-site-el "pre")

;;; System Utilities
;;;; (no) backups
(setq vc-make-backup-files nil
      make-backup-files nil)

;;;; history (saveplace, recentf, savehist)
(require 'saveplace)
(setq save-place-file (expand-file-name "~/.emacs.d/cache/places"))
(save-place-mode 1)

(setq recentf-save-file (expand-file-name "~/.emacs.d/cache/recentf")
      recentf-max-saved-items 2000
      recentf-exclude '("/home/jao/\\.emacs\\.d/elpa.*/.*"
                        ".*/.git/COMMIT_EDITMSG"))

(require 'recentf)
(recentf-mode 1)


(setq savehist-file (expand-file-name "~/.emacs.d/cache/history"))
(require 'savehist)

(savehist-mode t)

(defun jao-unpropertize-kill-ring ()
  (setq kill-ring (mapcar #'substring-no-properties kill-ring)))

(add-hook 'kill-emacs-hook #'jao-unpropertize-kill-ring)

(setq savehist-additional-variables '(kill-ring search-ring regexp-search-ring)
      savehist-ignored-variables '(ido-file-history))

;;;; yes/no, bell, startup message

(setq use-short-answers t)
(setq inhibit-startup-message t)
(setq visible-bell (jao-is-linux))

;;;; server
(setenv "EDITOR" "emacsclient")
(require 'server)
(unless (or (daemonp) (server-running-p)) (server-start))

;;;; timers
(put 'list-timers 'disabled nil)

;;;; tramp
(defvar jao-tramp-inhibit t)
(when (and jao-tramp-inhibit (> emacs-major-version 29))
  (inhibit-remote-files))

;;;; docker
(use-package dockerfile-mode :ensure t)
(use-package docker :ensure t)

;;;; sleep/awake
(use-package jao-sleep
  :if (jao-is-linux)
  :demand t
  :config (jao-sleep-dbus-register))

;;;; buffering for processes
(setq read-process-output-max (* 4 1024 1024))

;;;; process runners
(use-package jao-shell
  :demand t
  :bind (("s-r" . jao-shell-exec)))

;;;; app launcher
(jao-when-linux
 (jao-load-path "app-launcher")
 (use-package app-launcher
   :bind (("s-R" . app-launcher-run-app))))

;;;; brightness control
(jao-when-linux
 (jao-shell-def-exec jao-bright-set-up "brightnessctl" "-q" "s" "5%+")
 (jao-shell-def-exec jao-bright-set-down "brightnessctl" "-q" "s" "5%-")

 (defun jao-brightness ()
   (string-trim (or (cadr (jao-shell-cmd-lines "brightnessctl")) "(Unknown)")))

 (defun jao-bright-show ()
   (interactive)
   (message "%s" (jao-brightness)))

 (defun jao-bright-up ()
   (interactive)
   (jao-shell-exec "brightnessctl -q s 5%%+" t)
   (jao-bright-show))

 (defun jao-bright-down ()
   (interactive)
   (jao-shell-exec "brightnessctl -q s 5%%-" t)
   (jao-bright-show)))

;;;; keyboard
(jao-when-darwin
 (setq mac-command-modifier 'meta)
 (setq mac-option-modifier 'super)
 (global-set-key (kbd "£") [?#]))

(use-package repeat
  :demand t
  :config
  (setq repeat-echo-function 'repeat-echo-mode-line
                repeat-exit-key "SHIFT"
                repeat-exit-timeout 2)
  (repeat-mode))

(jao-when-linux
 (defun jao-kb-toggle (&optional lyt)
   (interactive)
   (shell-command-to-string (or lyt
                                (if (jao-kb-toggled-p)
                                    "setxkbmap us"
                                  "setxkbmap us -variant intl"))))

 (defun jao-set-uk-kb (&optional lyt)
   (interactive)
   (jao-kb-toggle "setxkbmap gb"))

 (defun jao-kb-disable-laptop ()
   (interactive)
   (jao-shell-exec "xinput float 13"))

 (defun jao-kb-toggled-p ()
   (not (string-empty-p
         (shell-command-to-string "setxkbmap -query|grep variant")))))

(customize-set-variable 'default-input-method "catalan-prefix")
;; http://mbork.pl/2022-03-07_Transient_input_method
(customize-set-variable 'default-transient-input-method "TeX")

(setq echo-keystrokes 1
      suggest-key-bindings nil)

;;;; transient
(use-package transient
  :init (setq transient-show-popup t)
  :demand t
  :config
  (transient-bind-q-to-quit))

(defmacro jao-transient-major-mode (mode &rest suffix)
  (declare (indent defun))
  (let ((mode (intern (format "%s-mode" mode)))
        (mmap (intern (format "%s-mode-map" mode)))
        (name (intern (format "jao-transient-%s" mode))))
    `(progn
       (transient-define-prefix ,name ()
         ,(format "Transient ops for %s" mode)
         [,(format "Operations for %s" mode) :if-derived ',mode ,@suffix])
       (define-key ,mmap (kbd "s-SPC") #',name)
       (define-key ,mmap (kbd "C-c SPC") #',name))))

(defmacro jao-transient-major-mode+1 (mode suffix)
  (declare (indent defun))
  (let ((name (intern (format "jao-transient-%s" mode))))
    (if (fboundp name)
        `(transient-append-suffix ',name '(0 -1) ,suffix)
      `(jao-transient-major-mode ,mode ,suffix))))

(defmacro jao-transient-major-mode+ (mode &rest suffixes)
  (declare (indent defun))
  `(progn ,@(mapcar (lambda (s) `(jao-transient-major-mode+1 ,mode ,s))
                    suffixes)))

;;;; disk monitoring
(use-package jao-dirmon
  :if (jao-is-linux)
  :commands jao-dirmon-report)

;;;; mailcap
(use-package mailcap
  :if (jao-is-linux)
  :config
  (add-to-list 'mailcap-mime-extensions '(".JPEG" . "image/jpeg"))
  (add-to-list 'mailcap-mime-extensions '(".JPG" . "image/jpeg"))

  (defun jao-icalendar-import-buffer (&optional no-kill)
    (let ((icalendar-import-format "%s%u%l%d"))
      (icalendar-import-buffer diary-file t nil))
    (unless no-kill (kill-buffer))
    (message "Event imported into diary"))

  (defun jao-icalendar-import-invite (file)
    (with-temp-buffer
      (insert-file-contents file)
      (jao-icalendar-import-buffer t)))

  :custom
  ((mailcap-user-mime-data
    `((jao-icalendar-import-buffer "application/ics")
      ("emacsclient -e '(jao-icalendar-import-invite \"%s\")'" "application/ics")
      (doc-view-mode "application/.*pdf" (display-graphic-p))
      ("zathura \"%s\"" "application/.*pdf")
      (image-mode "image/.*" (display-graphic-p))
      ("firefox %s && riverctl set-focused-tags 2" "text/html" jao-river-enabled)
      ("swayimg \"%s\"" "image/.*" jao-sway-enabled)
      ("imv-wayland \"%s\"" "image/.*" jao-wayland-enabled)
      ("imv-x11 \"%s\"" "image/.*")))))

;;;; tmr
(jao-when-linux
 (use-package tmr
   :ensure t
   :init
   (setq tmr-sound-file
         (jao-when-linux "/usr/share/sounds/freedesktop/stereo/message.oga"))
   :config (tmr-mode-line-mode 1)))

;;; Crypto
;;;; PGP, EPG, passwords
(use-package auth-source
  :init
  (setq auth-source-debug nil
        auth-sources '("~/.emacs.d/authinfo.gpg" "~/.netrc"))
  :config
  (add-to-list 'auth-source-protocols '(local "local"))
  (jao-when-darwin (add-to-list 'auth-sources 'macos-keychain-generic t)))

(use-package epa-file
  :demand t
  :init (setq epa-file-cache-passphrase-for-symmetric-encryption t
              epa-file-encrypt-to "A247C4780736A6156BC8DA748C081D34D321D881"
              plstore-encrypt-to epa-file-encrypt-to)
  :config (epa-file-enable))

(defun jao--get-user/password (h)
  (let ((item (car (auth-source-search :type 'netrc :host h :max 1))))
    (when item
      (let ((user (plist-get item :user))
            (pwd (plist-get item :secret)))
        (list user (when pwd (funcall pwd)))))))

(defun jao-call-with-auth (host fun)
  (let ((up (jao--get-user/password host)))
    (funcall fun (car up) (cadr up))))

(defmacro jao-with-auth (host usr pwd &rest body)
  (declare (indent defun))
  `(jao-call-with-auth ,host (lambda (,usr ,pwd) ,@body)))

;;;; pass
(when (> emacs-major-version 28)
  (use-package password-store-menu
   :ensure t
   :config (password-store-menu-enable)
   :custom (password-store-menu-key "C-c p")))

;;; Fonts and color themes
;;;; widgets
(setq widget-image-enable nil
      widget-link-prefix ""
      widget-link-suffix ""
      widget-button-prefix " "
      widget-button-suffix " "
      widget-push-button-prefix ""
      widget-push-button-suffix "")

;;;; nobreak char display
(setq nobreak-char-display nil)

;;;; vertical separator
(unless (display-graphic-p)
  (set-display-table-slot standard-display-table
                          'vertical-border
                          (make-glyph-code ?│)))

;;;; transparency
(defvar jao-transparent-only-bg (jao-is-linux))

(defvar jao-frames-default-alpha
  (cond ((eq window-system 'pgtk) 85)
        (jao-transparent-only-bg 88)
        (t 85)))

(defvar jao-transparent-frame (< jao-frames-default-alpha 100))

(defun jao-alpha-parameters (&optional level)
  (let ((level (or level jao-frames-default-alpha)))
    (if jao-transparent-only-bg
        `((alpha-background . ,level) (alpha))
      `((alpha . ,(cons level level)) (alpha-background)))))

(defun jao-set-transparency (&optional level all)
  (interactive "nOpacity (0-100): ")
  (let ((level (or level jao-frames-default-alpha)))
    (setq jao-transparent-frame (< level 100))
    (if all
        (modify-all-frames-parameters (jao-alpha-parameters level))
      (modify-frame-parameters nil (jao-alpha-parameters level)))))

(defun jao-toggle-transparency (&optional all)
  (interactive "P")
  (let ((level (if jao-transparent-frame 100 jao-frames-default-alpha)))
    (jao-set-transparency level all)))

(jao-set-transparency)

;;;; themes
(defun jao-colors-scheme-dark-p ()
  (and (jao-is-linux) (equal "dark" (getenv "JAO_COLOR_SCHEME"))))

(defun jao-colors-scheme ()
  (if (jao-colors-scheme-dark-p) 'dark 'light))

(customize-set-variable 'frame-background-mode (jao-colors-scheme))

(setq custom-theme-directory
      (expand-file-name "lib/themes" jao-emacs-dir))

(defvar jao-theme-dark 'jao-dark)
(defvar jao-theme-light 'jao-light)
(defvar jao-theme-term-dark 'modus-vivendi)
(defvar jao-theme-term-light 'jao-light-term)

(use-package jao-themes
  :demand t
  :init
  (setq jao-themes-default-family (jao-d-l "Menlo" "Hack") ;; "RobotoMono Nerd Font"
        jao-themes-default-size (jao-d-l 10 9)
        jao-themes-default-variable-pitch-family
        (jao-d-l "Helvetica" "Iosevka Etoile")
        jao-themes-default-variable-pitch-size (jao-d-l 12 9)))

(defun jao-themes-setup ()
  (let* ((dark (jao-colors-scheme-dark-p))
         (theme (cond ((and dark window-system) jao-theme-dark)
                      (dark jao-theme-term-dark)
                      (window-system jao-theme-light)
                      (t jao-theme-term-light))))
    (load-theme theme t)
    (modify-all-frames-parameters `((font . ,jao-themes-default-face)))))

(jao-themes-setup)

;;; Help system
;;;; which-key
(use-package which-key
  :custom
  (which-key-add-column-padding 2)
  (which-key-lighter "")
  (which-key-idle-delay 10000)
  (which-key-idle-secondary-delay 0.05)
  (which-key-show-early-on-C-h  t)
  :hook (after-init . which-key-mode))

;;;; help buffers
(setq help-window-select t
      help-window-keep-selected nil
      help-link-key-to-documentation t)

;;;; find-func/var/lib
(use-package find-func
  :bind (("C-h C-v" . find-variable)
         ("C-h C-f" . find-function)
         ("C-h C-k" . find-function-on-key)
         ("C-h C-l" . find-library)))

;;;; bookmarks
(setq bookmark-default-file "~/.emacs.d/emacs.bmk"
      bookmark-fringe-mark nil)

;;;; man pages
(use-package man
  :config (setq Man-notify-method 'pushy)) ;; pushy - same window

;;; Minibuffer
(use-package jao-minibuffer
  :init
  (if (jao-colors-scheme-dark-p)
      (setq jao-minibuffer-active-buffer-line-color "azure4"
            jao-minibuffer-inactive-buffer-line-color "grey25")
    (setq jao-minibuffer-active-buffer-line-color
          (jao-d-l "#dfdfdf" "burlywood3")
          jao-minibuffer-inactive-buffer-line-color
          (jao-d-l "#dfdfdf" "grey65")))
  (setq jao-minibuffer-adaptive-alignment nil
        jao-minibuffer-info-face-alt 'jao-themes-dimm)
  :commands (jao-minibuffer-add-variable
             jao-minibuffer-refresh
             jao-minibuffer-mode
             jao-minibuffer-mode-line-mode))

(setq enable-recursive-minibuffers t)
(require 'mb-depth)
(minibuffer-depth-indicate-mode 1)

(setq minibuffer-default-prompt-format " (default %s)")
(minibuffer-electric-default-mode 1)

(jao-minibuffer-mode)

;;; Mode line
;;;; config
(setq line-number-display-limit-width 250
      mode-line-position-column-format '(" %c")
      mode-line-position-line-format '(" %c %l")
      mode-line-end-spaces nil
      mode-line-percent-position
      '("%2l" (:eval (format " %d " (line-number-at-pos (point-max)))) "%2c"))

(line-number-mode -1)
(column-number-mode -1)

;;;; time display
(setq world-clock-list
      '(("Europe/London" "Edinburgh")
        ("Europe/Paris" "Barcelona")
        ("Asia/Tokyo" "Tokyo")
        ("America/Los_Angeles" "Corvallis")
        ("America/New_York" "New York")))

(setq display-time-day-and-date nil
      display-time-24hr-format nil
      display-time-default-load-average nil
      display-time-format " %a %e %H:%M")

(defun jao-time-to-epoch (&optional s)
  "Transform a time string to an epoch integer in milliseconds."
  (interactive)
  (let ((s (or s (read-string "Time string: " (thing-at-point 'string)))))
    (message "%s = %s"
             s
             (round (* 1000 (time-to-seconds (parse-time-string s)))))))

(defun jao-epoch-to-time (&optional v)
  "Transform an epoch, given in milliseconds, to a time string."
  (interactive)
  (let ((v (or v (read-number "Milliseconds: " (thing-at-point 'number)))))
    (message "%s = %s" v
             (format-time-string "%Y-%m-%d %H:%M:%S"
                                 (seconds-to-time (/ v 1000.0))))))

;;;; mode line toggle
(defvar jao-mode-line-in-minibuffer (display-graphic-p))

(use-package jao-mode-line
  :commands (jao-mode-line-add-to-minibuffer-left
             jao-mode-line-add-to-minibuffer-right
             jao-mode-line-remove-from-minibuffer)
  :init
  (when (and window-system (not jao-mode-line-in-minibuffer))
    (add-to-list 'after-make-frame-functions #'jao-mode-line-hide-inactive)
    (add-hook 'after-init-hook #'jao-mode-line-toggle-inactive))
  :demand t
  :bind (("<home>" . jao-mode-line-toggle-inactive)
         ("<end>" . jao-mode-line-toggle)
         ("<insert>" . jao-mode-line-echo)))

;;;; diminish
(use-package diminish
  :ensure t
  :demand t
  :diminish ((auto-fill-function . " §")
             (auto-revert-mode . "")))

(use-package outline
  :diminish ((outline-minor-mode . "")))

;;;; battery
(use-package battery
  :init
  (setq battery-load-low 15
        battery-load-critical 8
        battery-mode-line-limit 40
        battery-echo-area-format
        "%L %r %B (%p%% load, remaining time %t)"
        battery-mode-line-format " 🔋%b%p% ")

  (with-eval-after-load "jao-minibuffer"
    (jao-when-linux
     (display-battery-mode 1)
     (jao-minibuffer-add-variable 'battery-mode-line-string 80))))

;;; Notifications
;;;; jao-notify
(use-package jao-notify
  :demand t
  :init (setq jao-notify-use-messages (jao-d-l 'mac t)))

;;;; tracking
(use-package tracking
  :ensure t
  :demand t
  :init (setq tracking-position 'before-modes
              tracking-frame-behavior nil
              tracking-most-recent-first nil
              tracking-max-mode-line-entries 10
              tracking-sort-faces-first t
              tracking-shorten-modes '())
  :config  (setq erc-track-enable-keybindings nil))

(use-package jao-tracking
  :demand t
  :init
  (setq jao-tracking-bkg (if (jao-colors-scheme-dark-p) "grey20" "grey93"))
  :config (jao-tracking-setup t))

;;;; ednc

(jao-when-linux
 (use-package ednc
   :ensure t
   :diminish nil))

(use-package jao-ednc
  :if (jao-is-linux)
  :demand t
  :init (setq jao-ednc-use-tracking nil)
  :commands (jao-ednc-setup)
  :after ednc
  :config
  (jao-ednc-ignore-app "Firefox")
  (transient-define-prefix jao-transient-ednc ()
    ["Notifications"
     ("s" "show last" jao-ednc-show)
     ("S" "show all" jao-ednc-pop)
     ("n" "dismiss and show" jao-ednc-dismiss-and-show :transient t)
     ("d" "dismiss last" jao-ednc-dismiss)
     ("D" "dismiss all" jao-ednc-dismiss-all)
     ("i" "invoke last action" jao-ednc-invoke-last-action)])
  (global-set-key (kbd "s-n") #'jao-transient-ednc))

;;; Calendar, diary
;;;; diary
(setq ;; diary-file (expand-file-name "diary" jao-org-dir)
      diary-display-function 'diary-fancy-display
      diary-mail-addr "jao@localhost"
      diary-comment-start ";;"
      diary-comment-end "")

(add-hook 'diary-list-entries-hook 'diary-sort-entries t)

;;;; calendar

(use-package calendar
  :init
  (setq appt-display-format nil
        calendar-latitude 55.9533
        calendar-longitude -3.1883
        calendar-left-margin 4
        calendar-location-name "Edinburgh, Scotland"
        calendar-mark-diary-entries-flag t
        calendar-week-start-day 1 ;; 0 sunday
        calendar-date-echo-text '(format "ISO date: %s"
                                         (calendar-iso-date-string
                                          (list month day year))))
  (setq calendar-holidays
        '((holiday-fixed 1 1 "New Year's Day")
          (holiday-fixed 4 1 "April Fools' Day")
          (holiday-float 5 0 2 "Mother's Day")
          (holiday-fixed 3 19 "Father's Day")
          (holiday-float 11 4 4 "Thanksgiving")
          (holiday-fixed 12 25 "Christmas")
          (holiday-chinese-new-year)
          (solar-equinoxes-solstices)
          (holiday-sexp calendar-daylight-savings-starts
                        (format "Daylight Saving Time Begins %s"
                                (solar-time-string
                                 (/ calendar-daylight-savings-starts-time
                                    (float 60))
                                 calendar-standard-time-zone-name)))
          (holiday-sexp calendar-daylight-savings-ends
                        (format "Daylight Saving Time Ends %s"
                                (solar-time-string
                                 (/ calendar-daylight-savings-ends-time
                                    (float 60))
                                 calendar-daylight-time-zone-name)))))

  (setq org-calendar-insert-diary-entry-key nil
        org-agenda-diary-file 'diary-file)

  :config
  (appt-activate 1)
  (calendar-set-date-style 'european)

  (add-to-list 'display-buffer-alist
               `(,(regexp-quote diary-fancy-buffer)
                 (display-buffer-at-bottom)
                 (window-parameters (mode-line-format . none))
                 (window-height . fit-window-to-buffer)))

  (defun jao-diary--select ()
    (switch-to-buffer diary-fancy-buffer))

  (add-hook 'diary-fancy-display-mode-hook #'jao-diary--select))

;;;; persistent scratch
(use-package persistent-scratch
  :ensure t
  :config (persistent-scratch-setup-default))

;;;; dired
(use-package ls-lisp
  :if (jao-is-darwin)
  :demand t
  :init (setq ls-lisp-use-insert-directory-program nil
              ls-lisp-dirs-first t))

(use-package dired
  :init
  (setq dired-recursive-deletes 'top
        dired-recursive-copies 'top
        dired-listing-switches "-alhF --group-directories-first"
        dired-dwim-target t
        dired-kill-when-opening-new-dired-buffer t
        dired-mouse-drag-files t
        wdired-create-parent-directories t)

  (jao-when-linux
   (setq dired-guess-shell-alist-user
        '(;; ("\\.\\(png\\|jpe?g\\|tiff\\)" "feh" "xdg-open")
          ("\\.\\(mp[34]\\|m4a\\|ogg\\|flac\\|webm\\|mkv\\)" "mpv" "xdg-open")
          (".*" "xdg-open"))))

  (put 'dired-find-alternate-file 'disabled nil)

  :bind (:map dired-mode-map
              ("C-c C-r" . wdired-change-to-wdired-mode)
              ("C-M-m" . gnus-dired-attach)))

(use-package dired-x :demand t)

(use-package find-dired
  :init (setq find-ls-option '("-print0 | xargs -0 ls -ld" . "-ld"))
  :bind ("C-c D" . find-name-dired))

(use-package dired-duplicates :ensure t)

;;; General editing
;;;; automatically uncompress
(require 'jka-compr)
(auto-compression-mode 1)

;;;; wgrep
(use-package wgrep :ensure t)

;;;; executable scripts
;; (add-hook 'after-save-hook
;;           'executable-make-buffer-file-executable-if-script-p)

;;;; spaces, tabs, kill
(setq kill-whole-line t)
(setq-default indent-tabs-mode nil)
(setq indent-tabs-width 4)
(setq-default default-tab-width 8)
(setq kill-read-only-ok t)
(setq view-read-only nil)

;;;; whitespace and filling column
(add-hook 'write-file-functions 'delete-trailing-whitespace)
(setq-default indicate-empty-lines nil)
(setq-default fill-column 78)
(setq comment-auto-fill-only-comments nil)

(use-package whitespace
  :init
  (setq whitespace-style '(face tabs trailing ;; lines-tail
                           empty  missing-newline-at-eof)
        whitespace-line-column 80)
  :hook (prog-mode . whitespace-mode)
  :diminish nil)

(use-package display-fill-column-indicator
  :init (setq-default display-fill-column-indicator-column 80)
  :hook (prog-mode . display-fill-column-indicator-mode))

;;;; visible mode
(use-package visible-mode
  :bind (("s-v" . visible-mode)))

;;;; changes
(use-package goto-chg
  :ensure t
  :bind (("C-." . goto-last-change)
         ("C-c ." . goto-last-change)
         ("C-c ," . goto-last-change-reverse)))

;;;; eval-and-replace
(defun fc-eval-and-replace ()
  "Replace the preceding sexp with its value."
  (interactive)
  (backward-kill-sexp)
  (condition-case nil
      (prin1 (eval (read (current-kill 0)))
             (current-buffer))
    (error (message "Invalid expression")
           (insert (current-kill 0)))))

 (global-set-key "\C-ce" 'fc-eval-and-replace)

;;;; skeletons and autoinsert
(use-package autoinsert
  :config
  (setq auto-insert-directory "~/.emacs.d/autoinsert/"
        auto-insert t
        auto-insert-query t)
  (setf (alist-get 'html-mode auto-insert-alist nil t) nil))
(add-hook 'find-file-hook #'auto-insert)

(use-package jao-skel
  :demand t
  :config
  (defvar flymake-allowed-file-name-masks nil)
  (require 'jao-skel-geiser)
  (require 'jao-skel-lisp)
  (require 'jao-skel-haskell)
  (require 'jao-skel-latex))

;;; Completion and search
;;;; completion
(require 'jao-custom-completion)

;;;; recoll
(jao-when-linux (jao-load-path "consult-recoll"))

(use-package consult-recoll
  :if (jao-is-linux)
  :commands (consult-recoll consult-recoll-embark-setup)
  :init
  (defun jao-recoll-format (title url _mtype)
    (let* ((u (replace-regexp-in-string "file://" "" url))
           (u (replace-regexp-in-string "/home/jao/" "" u))
           (u (replace-regexp-in-string
               "\\(doc\\|org/doc\\|.emacs.d/gnus/Mail\\|var/mail\\)/" "" u)))
      (format "%s (%s)" ;; "%s (%s, %s)"
              title
              (propertize u 'face 'jao-themes-f01)
              ;; (propertize mtype 'face 'jao-themes-f01)
              )))

  (defun jao-recoll-open-html (file &optional _page)
    (if (string-match-p "\.epub\\'" file)
        (find-file file)
      (jao-afio-goto-www)
      (if jao-afio-use-w3m (w3m-find-file file) (eww-open-file file))))

  (defun jao-recoll-open-pdf (file &optional page)
    (if (string-match-p "/gnus/Mail/" file)
        (funcall
         (or (cdr (assoc-string "message/rfc822" consult-recoll-open-fns))
             'find-file)
         file
         page)
      (jao-open-doc file page)))

  (defun jao-recoll-consult-messages ()
    (interactive)
    (consult-recoll "mime:message "))

  (defun jao-recoll-consult-docs ()
    (interactive)
    (consult-recoll (format "dir:%s/doc " jao-org-dir)))

  (defun jao-recoll-consult-notes ()
    "Use consult-recoll to search notes."
    (interactive)
    (consult-recoll (format "dir:%s " jao-org-notes-dir)))

  (setq consult-recoll-open-fns
        '(("application/pdf" . jao-recoll-open-pdf)
          ("text/html" . jao-recoll-open-html))
        consult-recoll-search-flags 'query
        consult-recoll-inline-snippets t
        consult-recoll-format-candidate #'jao-recoll-format)

  :config

  (consult-customize consult-recoll :preview-key 'any)
  (with-eval-after-load "embark" (consult-recoll-embark-setup))

  (transient-define-prefix jao-transient-recoll ()
    ["Consult recoll queries"
     ("r" "everywhere" consult-recoll)
     ("n" "on notes" jao-recoll-consult-notes)
     ("d" "on docs" jao-recoll-consult-docs)
     ("m" "on messages" jao-recoll-consult-messages)])

  :bind (("s-r" . #'jao-transient-recoll)))

;;;; alternative (mac): consult-spotlight

(jao-when-darwin
 (use-package consult-spotlight
   :ensure t
   :config
   (defun jao-consult-spotlight-docs ()
     (interactive)
     (consult-spotlight "~/Documents"))

   (defun jao-consult-spotlight-mail ()
     (interactive)
     (consult-spotlight "~/Mail"))

   (defun jao-consult-spotlight-notes ()
     (interactive)
     (consult-spotlight jao-org-notes-dir))

   (transient-define-prefix jao-transient-spotlight ()
     ["Spotlight queries"
      ("s" "everywhere" consult-spotlight)
      ("n" "on notes" jao-consult-spotlight-notes)
      ("d" "on docs" jao-consult-spotlight-docs)
      ("m" "on messages" jao-consult-spotlight-mail)])

   :bind (("s-s" . jao-transient-spotlight))))

;;; Buffers
;;;; cursor and mark
(transient-mark-mode -1)
(blink-cursor-mode -1)
(setq cursor-in-non-selected-windows nil
      visible-cursor nil) ;; stop blinking in xterm

;;;; uniquifiy
(require 'uniquify)
(setq uniquify-buffer-name-style 'forward
      uniquify-trailing-separator-p t)

;;;; autosave
(setq auto-save-list-file-prefix "~/.emacs.d/auto-save-list/.saves-"
      auto-save-no-message t
      kill-buffer-delete-auto-save-files t)

(setq lock-file-name-transforms
      '(("\\`/.*/\\([^/]+\\)\\'" "/tmp/emacs-lock/\\1" t)))

;;;; autorevert
(setq auto-revert-check-vc-info nil)
(setq auto-revert-verbose nil)
(setq auto-revert-avoid-polling t)
(setq auto-revert-mode-text "")
(require 'autorevert)
(global-auto-revert-mode 1)

;;;; attached buffers
(defun jao-display-buffer-below-selected (buffer alist)
  (delete-other-windows-vertically)
  (display-buffer-below-selected buffer alist))

(defun jao-display-below-eldoc (buffer alist)
  (let ((w (selected-window)))
    (pop-to-buffer "*eldoc*" nil t)
    (jao-display-buffer-below-selected buffer alist)
    (select-window w t)))

(defun jao-attached-buffer-entry (name-rx height)
  `(,name-rx (display-buffer-reuse-window
              jao-display-buffer-below-selected)
             (window-height . ,(or height 25))))

(defmacro jao-with-attached-buffer (name-rx height &rest body)
  (declare (indent defun))
  `(let ((display-buffer-alist '(,(jao-attached-buffer-entry name-rx height))))
     ,@body))

(defun jao-define-attached-buffer (name-rx &optional height)
  (add-to-list 'display-buffer-alist
               (jao-attached-buffer-entry name-rx height)))

(use-package xref
  :config
  (jao-define-attached-buffer "^\\*xref\\*"))

;;;; same mode
(defun jao-buffer-same-mode (&optional mode pre-fn switch-fn)
  (interactive)
  (let* ((mode (or mode major-mode))
         (modes (if (symbolp mode) (list mode) mode))
         (pred `(lambda (b)
                  (let ((b (get-buffer (if (consp b) (car b) b))))
                    (member (buffer-local-value 'major-mode b)
                            ',modes))))
         (buff (read-buffer "Buffer: " nil t pred)))
    (when pre-fn (funcall pre-fn))
    (if switch-fn (funcall switch-fn buff) (switch-to-buffer buff))))

(defun jao-buffer-same-mode-cmd (&optional pop)
  (interactive "P")
  (jao-buffer-same-mode nil nil (and pop #'pop-to-buffer)))

(global-set-key (kbd "C-c C-b") #'jao-buffer-same-mode-cmd)

;;;; projects
;; (use-package project :demand t)
;; (use-package list-projects :ensure t)

;;;; buffer quit function (the triple ESC)
(setq buffer-quit-function (lambda () t))

;;;; redisplay escape hatch
;; (setq max-redisplay-ticks 2250000)
;;;; scrolling
(if window-system
    (setq scroll-preserve-screen-position 'always
          scroll-conservatively most-positive-fixnum
          scroll-margin 5
          scroll-step 2
          redisplay-skip-fontification-on-input t)
  (setq scroll-preserve-screen-position nil
        scroll-conservatively 0
        scroll-margin 5
        scroll-step 1
        redisplay-skip-fontification-on-input nil))

(jao-when-linux
 (use-package ultra-scroll
   :ensure t
   :init
   (setq scroll-conservatively 101    ; or whatever value you prefer, since v0.4
         scroll-margin 0)       ; important: scroll-margin>0 not yet supported
   :config
   (ultra-scroll-mode 1)))

;;;; show diffs when running C-x s
(add-to-list 'save-some-buffers-action-alist
             `("d"
               ,(lambda (buffer)
                  (diff-buffer-with-file (buffer-file-name buffer)))
               "show diff between the buffer and its file"))

;;;; copy buffer file name
;; https://stackoverflow.com/questions/18812938/copy-full-file-path-into-copy-paste-clipboard
(defun copy-buffer-file-name-as-kill (choice)
  "Copy the buffer-file-name to the kill-ring"
  (interactive "cCopy Buffer Name (F) Full, (D) Directory, (N) Name")
  (let ((new-kill-string)
        (name (if (eq major-mode 'dired-mode)
                  (dired-get-filename)
                (or (buffer-file-name) ""))))
    (cond ((eq choice ?f)
           (setq new-kill-string name))
          ((eq choice ?d)
           (setq new-kill-string (file-name-directory name)))
          ((eq choice ?n)
           (setq new-kill-string (file-name-nondirectory name)))
          (t (message "Quit")))
    (when new-kill-string
      (message "%s copied" new-kill-string)
      (kill-new new-kill-string))))

;;;; warnings display
(setq warning-display-at-bottom nil)

;;; Windows
;;;; splitting and switch
(setq split-height-threshold 200
      split-width-threshold 144
      display-buffer-avoid-small-windows 40)

(setq switch-to-buffer-preserve-window-point nil
      switch-to-buffer-obey-display-actions t
      switch-to-buffer-in-dedicated-window 'pop
      switch-to-prev-buffer-skip 'this) ;; don't switch to a
                                        ;; buffer already visible in
                                        ;; this frame


(global-set-key (kbd "C-x _") #'delete-other-windows-vertically)

;;;; first window
(defvar jao-first-window--from nil)

(defun jao-first-window ()
  "Go to previous windows in frame, remembering where we were."
  (interactive)
  (let ((cb (current-buffer)))
    (if (eq (get-buffer-window cb) (select-window (frame-first-window)))
        (when jao-first-window--from (pop-to-buffer jao-first-window--from))
      (setq jao-first-window--from cb))))

(global-set-key (kbd "s-a") #'jao-first-window)
(global-set-key (kbd "M-a") #'jao-first-window)

;;;; window navigation (custom)
(defun jao-nth-window (n)
  (if (zerop n)
      'jao-first-window
    `(lambda ()
       (interactive)
       (select-window (frame-first-window))
       (dotimes (x ,n) (other-window 1)))))

(defun jao-prev-window ()
  "Go to previous window."
  (interactive)
  (other-window -1))

(defvar jao-prev-window-repeat-map
  (let ((map (make-sparse-keymap)))
    (define-key map "p" 'jao-prev-window)
    (define-key map "P" (lambda ()
                          (interactive)
                          (setq repeat-map 'jao-prev-window-repeat-map)
                          (other-window 1)))
    map)
  "Keymap to repeat `prev-window' key sequences.  Used in `repeat-mode'.")

(put 'jao-prev-window 'repeat-map jao-prev-window-repeat-map)

(mapc (lambda (n)
        (global-set-key (format "\C-c%s" (1+ n)) (jao-nth-window n)))
      '(0 1 2 3 4 5 6 7 8))

(global-set-key "\C-xp" 'jao-prev-window)

;;;; window navigation (spatial-window)

(use-package spatial-window
  :ensure t
  :config
  (defun jao-spatial-window-select ()
    (interactive)
    (let ((n (length (window-list))))
      (cond ((< n 2))
            ((< n 3) (other-window 1))
            (t (spatial-window-select)))))

  :bind
  ("M-o" . jao-spatial-window-select)
  ;; ("C-x o" . jao-spatial-window-select)
  ;; ("C-x p" . jao-spatial-window-select)
  )

;;;; transposing windows
(defun transpose-windows (arg)
  "Transpose the buffers shown in two windows."
  (interactive "p")
  (let ((selector (if (>= arg 0) 'next-window 'previous-window)))
    (while (/= arg 0)
      (let ((this-win (window-buffer))
            (next-win (window-buffer (funcall selector))))
        (set-window-buffer (selected-window) next-win)
        (set-window-buffer (funcall selector) this-win)
        (select-window (funcall selector)))
      (setq arg (if (> arg 0) (1- arg) (1+ arg))))))

(define-key ctl-x-4-map (kbd "t") 'transpose-windows)

;;;; winner mode
(winner-mode 1)

;;; Frames
;;;; frame geometry
(setq frame-resize-pixelwise t)
(modify-all-frames-parameters
 `((horizontal-scroll-bars . nil)
   (vertical-scroll-bars . nil)
   (scroll-bar-width . 0)
   ,@(jao-when-linux '((menu-bar . nil)))
   ,@(jao-when-darwin '((internal-border-width . 5)
                        ;; (width . 163)
                        ;; (height . 70)
                        (menu-bar . nil)
                        ;; (right-divider-width . 6)
                        ;; (bottom-divider-width . 6)
                        ))))

;;;; frame layout, title, etc
(setq frame-title-format '("%b - emacs"))
(use-package fringe)
(fringe-mode)

(menu-bar-mode -1)

(setq ns-pop-up-frames nil)

;; (setting it to nil avoids mouse wrapping after other-frame)
(setq focus-follows-mouse (and (jao-is-linux) window-system t))

(use-package scroll-bar)
(set-scroll-bar-mode nil)
(use-package tool-bar)
(tool-bar-mode -1)

(defalias 'jao-trisect 'jao-afio-trisect)

(defun jao-bisect ()
  (interactive)
  (jao-trisect t)
  (other-window 1)
  (delete-window))

;;;; afio
(defvar jao-afio-skip-default-set nil)

(use-package jao-afio
  :demand t
  :config
  (jao-afio-setup (not window-system))
  (add-hook 'jao-afio-switch-hook 'jao-minibuffer-refresh t)

  (defun jao-current--frame-id ()
    (propertize (cond ((and (fboundp 'jao-exwm-enabled)
                            (jao-exwm-enabled-p)
                            (not (bound-and-true-p jao-exwm--use-afio))
                            (boundp 'exwm-workspace-current-index))
                       (format "F%s" exwm-workspace-current-index))
                      (t (format "%s" (or (jao-afio-frame-name) ""))))
                'face 'font-lock-warning-face))

  (unless nil ;; jao-afio-use-frames
    (jao-minibuffer-add-variable '(jao-current--frame-id) 100))

  (setq frame-title-format '("emacs - " (:eval (jao-afio-frame-name))))

  (jao-when-darwin
   (jao-afio-add-frame-parameters "docs" (width . 210) (height . 78))
   (unless jao-afio-skip-default-set
     (jao-afio-add-frame-parameters nil (width . 170) (height . 70))
     (add-to-list 'default-frame-alist '(height . 70))
     (add-to-list 'default-frame-alist '(width . 170))))

  :bind (("C-c f" . 'jao-afio-goto-main)
         ("C-c g" . 'jao-afio-goto-mail)
         ("C-c w" . 'jao-afio-goto-www)
         ("C-c z" . 'jao-afio-goto-docs)
         ("C-c t" . 'jao-afio-goto-chats)
         ("C-c 0" . 'jao-afio-goto-scratch)
         ("s-o" . 'jao-afio-toggle)))

;;; Writing and writing modes
;;;; copyright notices
(setq copyright-year-ranges t)
(add-hook 'write-file-functions 'copyright-update)

;;;; indent on yank
(defvar jao-auto-indent-modes
  '(emacs-lisp-mode ;; clojure-mode
    scheme-mode objc-mode
    tuareg-mode c-mode c++-mode
    tcl-mode sql-mode
    perl-mode cperl-mode
    java-mode jde-mode
    LaTeX-mode TeX-mode))

(defadvice yank (after indent-region activate)
  (when (member major-mode jao-auto-indent-modes)
    (indent-region (region-beginning) (region-end) nil)))

;;;; org mode
(require 'jao-custom-org)

;;;; blog
(when (file-directory-p (expand-file-name "www" jao-doc-dir))
  (require 'jao-custom-blog))

;;;; text-ish mode settings
;; SENTENCES separated by just one space
(setq sentence-end "[.?!][]\"')]*\\($\\|\t\\| \\)[ \t\n]*")
(setq sentence-end-double-space t)
;; copy rectangle
(defun kill-rectangle-save (start end)
  "Save the region-rectangle as the last killed one."
  (interactive "r")
  (require 'rect)           ; Make sure killed-rectangle is defvar'ed.
  (setq killed-rectangle (extract-rectangle start end))
  (message "Rectangle saved"))

;; text mode, autoinserts and write hooks
(setq default-major-mode 'text-mode)
(add-hook 'text-mode-hook 'turn-on-auto-fill)

;;;; dictionaries
(use-package dictionary
  :init (setq dictionary-use-single-buffer t
              dictionary-server "localhost")
  :commands (dictionary-search
             dictionary-match-words
             dictionary-lookup-definition
             dictionary
             dictionary-mouse-popup-matching-words
             dictionary-popup-matching-words
             dictionary-tooltip-mode
             global-dictionary-tooltip-mode)
  :bind (("C-c d" . dictionary-search)))

(use-package ispell
  :custom ((ispell-personal-dictionary
            (expand-file-name "~/.emacs.d/ispell.dict"))))

;; (use-package reverso
;;   :ensure t
;;   :init (setq reverso-languages '(english spanish french german)))

;; (use-package wordreference
;;   :ensure t
;;   :init (setq wordreference-target-lang "es"
;;               wordreference-source-lang "en")
;;   :bind (("C-c D" . wordreference-search)))

;;;; markdown
(use-package markdown-mode
  :ensure t
  :init (setq markdown-command '("pandoc" "--from=markdown" "--to=html5")
              markdown-asymmetric-header t
              markdown-enable-wiki-links t
              markdown-wiki-link-fontify-missing t
              markdown-enable-math  nil ;; toggle with M-x markdown-toggle-math
              markdown-link-space-sub-char "-"
              markdown-gfm-additional-languages '("whizzml" "flatline")
              markdown-hide-urls t
              markdown-hide-markup nil
              markdown-fontify-code-blocks-natively t
              markdown-fontify-whole-heading-line t
              markdown-unordered-list-item-prefix t)
  :hook (markdown-mode . outline-minor-mode)
  :config
  (dolist (u '("doc" "message" "notmuch"))
    (add-to-list 'markdown-uri-types u))
  (use-package markdown-toc :ensure t))

;; used by markdown mode to edit code blocks
(use-package edit-indirect :ensure t)

(dolist (ext '("\\.md$" "\\.markdown$"))
  (add-to-list 'auto-mode-alist (cons ext 'markdown-mode)))

;; (use-package md-ts-mode
;;   :ensure t)

;; (md-ts-mode-enable-global)

;;;; TeX and LaTex
(use-package tex-site
  :ensure auctex
  :init
  (setq TeX-auto-save t)
  (setq TeX-parse-self t)
  (setq TeX-a4-paper t)
  (setq TeX-auto-local ".tex-auto-local")
  ;; Preferred view format: dvi, ps, pdf, pdfs
  (setq TeX-view-format "pdf")
  (setq-default TeX-master "../main") ; nil to ask
  (setq TeX-view-program-selection
        (jao-d-l
         '((output-dvi "open")
           (output-pdf "open")
           (output-html "open"))
         '(((output-dvi has-no-display-manager) "dvi2tty")
           ((output-dvi style-pstricks) "dvips and gv")
           (output-dvi "xdvi")
           (output-pdf "xdg-open")
           (output-html "xdg-open"))))
  ;; to make RefTeX faster for large documents, try these:
  (setq reftex-enable-partial-scans t)
  (setq reftex-save-parse-info t)
  (setq reftex-use-multiple-selection-buffers t)
  ;; to integrate with AUCTeX
  (setq reftex-plug-into-AUCTeX t)
  (setq reftex-ref-style-default-list
        '("Hyperref" "Varioref" "Fancyref"))
  (setq LaTeX-command "latex -shell-escape")
  (setq LaTeX-biblatex-use-Biber t)
  (setq bibtex-dialect 'biblatex)
  :config
  (add-hook 'TeX-after-compilation-finished-functions
            'TeX-revert-document-buffer)
  (add-hook 'LaTeX-mode-hook 'turn-on-reftex))

;;; Browsing

(require 'jao-custom-browse)
(require 'jao-custom-eww)

;;; PDFs and other docs

;;;; doc view &co.

(require 'jao-custom-pdf)

;;;; epub
(use-package nov
  :ensure t
  :after doc-view
  :init (setq nov-variable-pitch t
              nov-text-width nil)
  :config
  (add-to-list 'auto-mode-alist '("\\.epub\\'" . nov-mode))
  (defun jao-nov-register-session ()
    (jao-doc-session-mark nov-file-name))
  (add-hook 'nov-mode-hook #'jao-nov-register-session))

;;; Email

(require 'jao-custom-email)

;;; Shells and terms
;;;; shell modes
(setq sh-basic-offset 2)
;; translates ANSI colors into text-properties, for eshell
(autoload 'ansi-color-for-comint-mode-on "ansi-color" nil t)
(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)
(defvar jao-use-vterm nil)
(defvar jao-use-eat nil)

(add-to-list 'display-buffer-alist
             '("\\*Async Shell Command\\*" (display-buffer-no-window)))

(use-package nushell-ts-mode
  :ensure t
  :config (setq nushell-ts-mode-indent-offset 4))

;;;; eat
(use-package eat
  :ensure t
  :commands jao-exec-in-term
  :init (setq jao-use-eat t
              eat-kill-buffer-on-exit t
              eat-enable-yank-to-terminal t)
  ;; :hook ((eshell-mode . eat-eshell-mode)
  ;;        (eshell-mode . eat-eshell-visual-command-mode))
  :diminish ((eat-eshell-mode . "")))

;;;; term
(defvar-local jao-term--cmd nil)

(defun jao-term--find (cmd)
  (seq-find (lambda (b)
              (with-current-buffer b
                (and (derived-mode-p 'eat-mode 'term-mode 'vterm-mode)
                     (string= (or jao-term--cmd "") cmd))))
            (buffer-list)))

(defun jao-exec-in-term (cmd &optional name)
  (interactive "SCommand")
  (require 'eat nil t)
  (cond ((and jao-use-vterm (fboundp 'jao-exec-in-vterm))
         (jao-exec-in-vterm cmd name))
        (jao-use-eat (let ((eat-term-name "xterm-256color"))
                       (with-current-buffer (eat cmd t)
                         (setq-local jao-term--cmd cmd))))
        (t (ansi-term "bash" name)
           (set-process-sentinel (get-buffer-process (current-buffer))
                                 (lambda (process event)
                                   (when (string= event "finished\n")
                                     (kill-buffer (process-buffer process)))))
           (setq-local jao-term--cmd cmd)
           (term-send-string nil (concat cmd " ; exit\n")))))

(defmacro jao-def-exec-in-term (name cmd &rest prelude)
  `(defun ,(intern (format "jao-term-%s" name)) (&optional term)
     (interactive "P")
     ,@prelude
     (let ((jao-use-vterm (if term (not jao-use-vterm) jao-use-vterm)))
       (if-let ((b (jao-term--find ,cmd)))
           (pop-to-buffer b)
         (jao-exec-in-term ,cmd ,(format "*%s*" name))))))

;;;; eshell
;;;;; basic custom
(use-package eshell
  :init
  (setq eshell-directory-name "~/.emacs.d/eshell"
        eshell-hist-ignoredups 'erase
        eshell-history-size 1000000
        eshell-error-if-no-glob nil)

  (defun jao-eshell--outline ()
    (setq-local outline-regexp eshell-prompt-regexp))

  :config (setq eshell-prompt-repeat-map nil)

  :hook (eshell-mode . jao-eshell--outline))

;;;;; colors
(autoload 'ansi-color-apply "ansi-color")
;; (add-hook 'eshell-preoutput-filter-functions 'ansi-color-filter-apply)
(add-hook 'eshell-preoutput-filter-functions 'ansi-color-apply)

(use-package eshell-syntax-highlighting
  :after esh-mode
  :ensure t
  :config
  ;; Enable in all Eshell buffers.
  (eshell-syntax-highlighting-global-mode +1))

;;;;; visual commands
(require 'em-term)

(dolist (c '("editor" "more" "wget" "dict" "vim" "links" "w3m" "guile"
             "zmore" "pager" "aptitude" "su" "htop" "top"
             "screen" "whizzml" "iex" "spt"))
  (add-to-list 'eshell-visual-commands c))

(setq eshell-visual-subcommands '(("git" "log" "diff" "show")
                                  ("sudo" "vim")
                                  ("rebar3" "shell"))
      eshell-destroy-buffer-when-process-dies nil
      eshell-escape-control-x t)

;;;;; bol
(defun jao-eshell-maybe-bol ()
  (interactive)
  (let ((p (point)))
    (eshell-bol)
    (if (= p (point))
        (beginning-of-line))))

;;;;; prompt
;; tracking git repos
(defun jao-eshell--git-dirty ()
  (shell-command-to-string "git diff-index --quiet HEAD -- || echo -n '*'"))

(use-package git-ps1-mode
  :ensure t
  :init (setq git-ps1-mode-showupstream "1"
              git-ps1-mode-showdirtystate "1"))

(defun jao-eshell--git-info ()
  (if (fboundp 'git-ps1-mode-get-current)
      (git-ps1-mode-get-current)
    (let ((desc (shell-command-to-string "git branch --no-color")))
      (when (string-match "^* \\(\\<.+\\>\\)" desc)
        (format "%s%s" (match-string 1 desc) (jao-eshell--git-dirty))))))

(defun jao-eshell--git-current-branch (suffix)
  (let* ((descs (string-split (or (jao-eshell--git-info) "") "/"))
         (desc (if (cdr descs)
                   (concat (mapconcat (lambda (s) (substring s 0 1))
                                      (butlast descs)
                                      "/")
                           "/" (car (last descs)))
                 (car descs))))
    (cond ((and (string-empty-p desc) suffix) (format " (%s)" suffix))
          ((string-empty-p (or suffix "")) (format " (%s)" desc))
          (t (format " (%s %s)" desc suffix)))))

(defun jao-eshell--virtualenv ()
  (let ((venv (getenv "VIRTUAL_ENV")))
    (when (and venv (string-match ".*/\\([^/]+\\)/$" venv))
      (match-string-no-properties 1 venv))))

(defun jao-eshell-prompt-function ()
  (let* ((venv (jao-eshell--virtualenv))
         (venv (if venv (format "%s" venv) "")))
    (concat (abbreviate-file-name (eshell/pwd))
            (jao-eshell--git-current-branch venv)
            (if (= (user-uid) 0) " # " " $ "))))

(setq eshell-prompt-function 'jao-eshell-prompt-function)

;;;;; in-term
(defun eshell/in-term (prog &rest args)
  (switch-to-buffer
   (apply #'make-term (format "in-term %s %s" prog args) prog nil args))
  (term-mode)
  (term-char-mode))

;;;;; dir navigation
(use-package eshell-up
  :ensure t
  :config (setq eshell-up-print-parent-dir t))

(use-package eshell-autojump :ensure t)

;;;;; completion

(defun jao-eshell--set-up-completion ()
  (setq-local completion-styles '(basic partial-completion))
  (add-hook 'completion-at-point-functions
            'bash-completion-capf-nonexclusive nil t))

(use-package bash-completion
  :ensure t
  :hook (eshell-mode . jao-eshell--set-up-completion))

;;;;; toggle
(use-package jao-eshell-here
  :demand t
  :config (jao-define-attached-buffer "^\\*eshell" 0.5)
  :bind (("<f1>" . jao-eshell-here-toggle)
         ("C-<f1>" . jao-eshell-here-toggle-new)))

;;;;; workarounds
;; at some point, bash completion started insertig the TAB
;; after the commands ends
;; (defun jao-eshell--clean-prompt ()
;;   (eshell-bol)
;;   (ignore-errors (kill-line)))

;; (add-hook 'eshell-after-prompt-hook 'jao-eshell--clean-prompt)

;;;;; keybindings
(defun jao-eshell--kbds ()
  (define-key eshell-mode-map "\C-a" 'jao-eshell-maybe-bol)
  (define-key eshell-mode-map "\C-ci" 'consult-outline))

(jao-eshell--kbds)

;;; Version control and CI
;;;; vc options
(setq vc-follow-symlinks t)
(setq auto-revert-check-vc-info nil)

;;;; diff fringe indicators (diff-hl)
(use-package diff-hl
  :ensure t
  :custom ((diff-hl-draw-borders nil)
           (diff-hl-side 'right)
           (diff-hl-margin-symbols-alist
            '((insert . "█")
              (delete . "█")
              (change . "█")
              (unknown . "█")
              (ignored . "█"))))
  :config
  (map-keymap (lambda (_k cmd)
                (put cmd 'repeat-map 'diff-hl-command-map))
              diff-hl-command-map)
  (add-hook 'magit-post-refresh-hook 'diff-hl-magit-post-refresh))

(global-diff-hl-mode 1)
;; (unless (display-graphic-p) (diff-hl-margin-mode 1))

;;;; magit/forge
(use-package magit
  :ensure t
  :commands magit-status
  :init
  (setq magit-repository-directories
        (jao-d-l
         '(("/Users/jao/Projects" . 3))
         '(("/home/jao/usr/bigml" . 2)
           ("/home/jao/usr/jao" . 3)
           ("/usr/local/src" . 1))))

  (setq magit-status-initial-section nil
        magit-define-global-key-bindings nil
        magit-completing-read-function 'magit-builtin-completing-read
        magit-display-buffer-function
        'magit-display-buffer-fullcolumn-most-v1
        magit-delete-by-moving-to-trash nil
        magit-last-seen-setup-instructions "1.4.0"
        magit-log-edit-confirm-cancellation t
        magit-omit-untracked-dir-contents t
        magit-process-connection-type nil
        magit-push-always-verify nil
        magit-save-repository-buffers 'dontask
        magit-section-visibility-indicators '(("…" . t))
        magit-show-long-lines-warning nil
        magit-status-buffer-switch-function 'switch-to-buffer
        magit-status-show-hashes-in-headers t))

;;;; forge
(use-package forge
  :ensure t
  :after magit
  :init
  (setq forge-topic-list-limit (cons 100 -1)
        forge-pull-notifications nil)
  (use-package embark-vc :ensure t)
  :config
  :bind ((:map forge-topic-mode-map ("M-w" . copy-region-as-kill))))

(defun jao-forge-create-branch-from-issue ()
  "Create and checkout a git branch named after the Forge issue at point."
  (interactive)
  (let* ((topic (or (forge-current-topic) (user-error "No issue at point")))
         (id (oref topic number))
         (title (oref topic title))
         ;; Clean up the title to make it a valid git branch name
         (clean-title (downcase (replace-regexp-in-string "[^a-zA-Z0-9]+" "-" title)))
         (branch-name (format "jao-%d-%s" id (string-trim clean-title "-")))
         (branch-name (read-string "Create branch: " branch-name)))
    (magit-branch-and-checkout branch-name (magit-get-current-branch))))

;; Optional: Bind it to 'b i' inside Magit status/issue buffers
(with-eval-after-load 'magit
  (transient-insert-suffix 'magit-branch "s"
    '("i" "branch from issue" jao-forge-create-branch-from-issue)))

;;;; forgejo
(use-package forgejo
  :ensure t
  :custom
  (forgejo-hosts '(("https://codeberg.org"))))

;;;; other git packages
(use-package git-timemachine :ensure t)

;; (use-package consult-git-log-grep
;;   :ensure t
;;   :custom (consult-git-log-grep-open-function #'magit-show-commit)
;;   :bind (("C-c K" . consult-git-grep)))

;; git config --local git-link.remote / git-link.branch
(use-package git-link :ensure t)
(use-package git-modes :ensure t)

;;; Programming

(require 'jao-custom-programming)

;;; Text/data formats
;;;; (no) bidi
(setq-default bidi-display-reordering 'left-to-right
              bidi-paragraph-direction 'left-to-right)
(setq bidi-inhibit-bpa t)

;;;; json
(use-package json-mode :ensure t)
;;;; yaml
(use-package yaml-mode :ensure t)
;;;; toml
(use-package eldoc-toml :ensure t)
(use-package toml-ts-mode
  :config
  (add-to-list 'auto-mode-alist '("`.*\\.toml" . toml-ts-mode))
  (add-hook 'toml-ts-mode-hook 'turn-off-auto-fill))

;;;; protobuf
(use-package protobuf-mode :ensure t)

;;; Graphics / images
(setq image-use-external-converter t
      image-cache-eviction-delay 120)
(setq widget-image-enable nil)

;; stolen from
;; https://emacs.dyerdwelling.family/emacs/20260430074958-emacs--a-tiny-header-line-tweak:-image-dimensions-in-image-mode/

(defun jao-image-mode-show-dimensions ()
  "Display the open image's pixel dimensions and file size in the header line."
  (when (and (derived-mode-p 'image-mode)
             buffer-file-name
             (file-exists-p buffer-file-name))
    (condition-case err
        (let* ((image (or (image-get-display-property)
                          (create-image buffer-file-name)))
               (size (image-size image t))
               (width (car size))
               (height (cdr size))
               (bytes (file-attribute-size
                       (file-attributes buffer-file-name))))
          (setq header-line-format
                (format " %d x %d px   %s"
                        width height
                        (file-size-human-readable bytes))))
      (error
       (setq header-line-format
             (format " image dimensions unavailable: %S" err))))))

(add-hook 'image-mode-hook #'jao-image-mode-show-dimensions)
(add-hook 'image-mode-new-window-functions
          (lambda (&rest _) (jao-image-mode-show-dimensions)))


;;; Network
;;;; r2e

(use-package jao-r2e
  :init (setq jao-r2e-confirm-toggle nil))

;;;; nm applet
(jao-when-linux
 (jao-shell-def-exec jao-nm-applet "nm-applet")

 (defun jao-toggle-nm-applet ()
   (interactive)
   (or (jao-shell-kill-p "nm-applet") (jao-nm-applet))))

;;;; bluetooth
(jao-when-linux (use-package bluetooth :ensure t))

;;;; ssh
(defun jao-tramp-hosts ()
  (seq-uniq
   (mapcan (lambda (x)
             (remove nil (mapcar 'cadr (apply (car x) (cdr x)))))
           (tramp-get-completion-function "ssh"))
   #'string=))

(defun jao-ssh (&optional scratch)
  (interactive "P")
  (let ((h (completing-read "Host: " (jao-tramp-hosts))))
    (when scratch (jao-afio-goto-scratch))
    (jao-exec-in-term (format "ssh %s" h) (format "*ssh %s*" h))))

;;; Chats
;;;; telegram
(use-package telega
  :ensure t
  :custom
  (telega-use-tracking-for '(unmuted) ;; '(or unmuted mention)
                           telega-rainbow-color-custom-for nil
                           telega-msg-rainbow-title nil
                           telega-sticker-set-download t
                           telega-symbol-checkmark "·"
                           telega-symbol-heavy-checkmark "×"
                           telega-symbol-verified "*")
  :config
  (define-key global-map (kbd "C-c C-t") telega-prefix-map)
  (setq telega-chat-show-avatars nil
        telega-chat-prompt-insexp '(telega-ins "> ")
        telega-completing-read-function #'completing-read
        telega-root-show-avatars nil
        telega-emoji-use-images nil
        telega-temp-dir "/tmp/telega"
        telega-symbol-horizontal-bar
        (propertize "-" 'face 'jao-themes-f00)
        telega-symbol-vertical-bar
        (propertize "| " 'face 'jao-themes-dimm)
        telega-mode-line-string-format
        '(:eval (telega-mode-line-unread-unmuted))
        telega-use-images (display-graphic-p)
        telega-open-file-function #'jao--see
        telega-open-message-as-file
        (unless (display-graphic-p) '(photo video animation)))
  (with-eval-after-load "tracking"
    (jao-shorten-modes 'telega-chat-mode)
    (jao-tracking-faces 'telega-tracking))
  (telega-mode-line-mode 1))

(defun jao-telega ()
  (interactive)
  (jao-tracking-go-to-chats)
  (if (get-buffer telega-root-buffer-name)
      (pop-to-buffer telega-root-buffer-name)
    (telega)))

;;;; mastodon
(use-package mastodon
  :ensure t
  :init
  (setq mastodon-instance-url "https://mastodon.social"
        mastodon-active-user "jao@gnu.org"
        mastodon-group-notifications t
        mastodon-images-in-notifs t
        mastodon-tl-position-after-update nil
        mastodon-toot-display-orig-in-reply-buffer t
        mastodon-media--hide-sensitive-media nil)
  :config
  ;; (defun jao-mastodon--setup ()
  ;;   (setq-local scroll-margin 12))

  ;; (add-hook 'mastodon-mode-hook #'jao-mastodon--setup)

  (with-eval-after-load "ewww"
    (define-key eww-mode-map (kbd "T") #'jao-mastodon-toot-url))

  (defun jao-mastodon-toot-url ()
    (interactive)
    (when-let* ((url (jao-url-around-point t)))
      (jao-tracking-go-to-chats)
      (mastodon-toot--compose-buffer nil nil nil url)))

  (defun jao-mastodon ()
    (interactive)
    (jao-d-l (jao-afio-goto-scratch) (jao-afio-goto-chats))
    (mastodon))

  ;; https://0x0.st/XJ14.txt
  (jao-transient-major-mode mastodon
    ["Timelines"
     ("H" "home"            mastodon-tl-get-home-timeline)
     ("L" "local"           mastodon-tl-get-local-timeline)
     ("F" "federated"       mastodon-tl-get-federated-timeline)
     ("K" "bookmarks"       mastodon-profile-view-bookmarks)
     ("V" "favorites"       mastodon-profile-view-favourites)
     ("'" "followed tags"   mastodon-tl-followed-tags-timeline)
     ("@" "mentions"        mastodon-notifications-get-mentions)
     ("N" "notifications"   mastodon-notifications-get)
     ("\\" "of remote host" mastodon-tl-get-remote-local-timeline)]

    ["Search"
     ("s" "search"          mastodon-search-query)
     ("#" "tagged"          mastodon-tl-get-tag-timeline)
     ("\"" "followed tags"  mastodon-tl-list-followed-tags)
     ("I" "filter"          mastodon-views-view-filters)
     ("X" "lists"           mastodon-views-view-lists)]

    ["Toots"
     ("n" "next"            mastodon-tl-goto-next-item :transient t)
     ("p" "prev"            mastodon-tl-goto-prev-item :transient t)
     ("c" "spoiler"         mastodon-tl-toggle-spoiler-text-in-toot :transient t)
     ("T" "thread"          mastodon-tl-thread)
     ("b" "(un)boost"       mastodon-toot-toggle-boost :transient t)
     ("f" "(un)fav"         mastodon-toot-toggle-favourite :transient t)
     ("i" "(un)pin"         mastodon-toot-pin-toot-toggle :transient t)
     ("k" "(un)bookmark"    mastodon-toot-toggle-bookmark :transient t)
     ("v" "vote"            mastodon-tl-poll-vote)]

    ["Own Toots"
     ("r" "replay"          mastodon-toot-reply)
     ("t" "write"           mastodon-toot)
     ("e" "edit"            mastodon-toot-edit-toot-at-point)
     ("d" "delete"          mastodon-toot-delete-toot)
     ("D" "del & redraft"   mastodon-toot-delete-and-redraft-toot)
     ("E" "show edits"      mastodon-toot-view-toot-edits)]

    ["Users"
     ("W" "follow"          mastodon-tl-follow-user)
     ("R" "follow req"      mastodon-views-view-follow-requests)
     ("G" "suggestions"     mastodon-views-view-follow-suggestions)
     ("M" "mute user"       mastodon-tl-mute-user)
     ("B" "block user"      mastodon-tl-block-user)
     ("m" "message user"    mastodon-tl-dm-user)
     ("," "favouriters"     mastodon-toot-list-favouriters)
     ("." "boosters"        mastodon-toot-list-boosters)]

    ["Profiles"
     ("A" "author"          mastodon-profile-get-toot-author)
     ("P" "any user"        mastodon-profile-show-user)
     ("O" "own"             mastodon-profile-my-profile)
     ("U" "update own"      mastodon-profile-update-user-profile-note)]

    ["Misc"
     ("C" "copy URL"        mastodon-toot-copy-toot-url)
     ("?" "help"            describe-mode)
     ("q" "quit"            transient-quit-one)]))

;;;; and more
(jao-when-linux (require 'jao-custom-chats))


;;; Multimedia

(jao-when-linux (require 'jao-custom-multimedia))

;;;; mpc
(use-package jao-mpc
  :demand t)

(defmacro jao-defun-play (name &optional mpc-name)
  (let ((arg (gensym)))
    `(defun ,(intern (format "jao-player-%s" name)) (&optional ,arg)
       (interactive "P")
       (,(intern (format "jao-mpc-%s" (or mpc-name name)))))))

(jao-defun-play toggle)
(jao-defun-play next)
(jao-defun-play previous)
(jao-defun-play stop)
(jao-defun-play echo echo-current)
(jao-defun-play list show-playlist)
(jao-defun-play info lyrics-track-data)
(jao-defun-play browse show-albums)
(jao-defun-play select-album)

(defun jao-player-seek (delta) (jao-mpc-seek delta))

(defalias 'jao-player-connect 'jao-mpc-connect)
(defalias 'jao-player-play 'jao-mpc-play)

(use-package jao-lyrics
  :init
  (setq jao-lyrics-info-function #'jao-player-info
        jao-lyrics-cache-dir (jao-d-l "~/Documents/lyrics" "~/.lyrics")))

(defun jao-player-seek-10 () (interactive) (jao-player-seek 10))
(defun jao-player-seek--10 () (interactive) (jao-player-seek -10))

(defun jao-streaming-clear () (interactive) (jao-mpc-clear))

(defun jao-streaming-echo-current ()
  (interactive)
  (jao-d-l (let ((inhibit-message t)) (jao-mpc-notify))
           (jao-mpc-echo-current)))

(defun jao-streaming-show-playlist ()
  (interactive)
  (jao-mpc-show-playlist))

(use-package jao-random-album
  :demand t
  :config
  (defun jao--notify-album (album)
    (if jao-minibuffer-mode
        (jao-minibuffer-refresh)
      (jao-notify album "Next album" jao-notify-audio-icon "")))
  (setq jao-random-album-notify #'jao--notify-album))

(transient-define-prefix jao-transient-media ()
  [["Play"
    ("m" "toggle" jao-player-toggle)
    ("n" "next" jao-player-next)
    ("p" "previous" jao-player-previous)
    ("S" "play stream" jao-mpc-play-stream)]
   ["Seek and search"
    ("f" "seek fwd" jao-player-seek-10 :transient t)
    ("F" "seek bwd" jao-player-seek--10 :transient t)
    ("a" "search album" jao-mpc-select-album)]
   ["Browse"
    ("b" "browse albums" jao-player-browse)
    ("l" "show play list" jao-player-list)]
   ["Now playing"
    ("w" "now playing" jao-streaming-echo-current)
    ("e" "echo now play" jao-player-echo)
    ("L" "show lyrics" jao-show-lyrics)]
   [:description
    (lambda ()
      (message "mpd %s" (if (jao-mpc-playing-p)
                            (jao-mpc--current-timestr t)
                          (jao-mpc--current-str)))
      (format "Master %s%%" (jao-mixer-get-level nil t)))
    :if jao-is-linux
    ("d" "down" jao-mixer-master-down :transient t)
    ("u" "up" jao-mixer-master-up :transient t)
    ("M" "toggle" jao-mixer-master-toggle)]
   [:description
    (lambda () (format "Capture %s%%" (jao-mixer-get-level "Capture" t)))
    :if jao-is-linux
    ("D" "down" jao-mixer-capture-down :transient t)
    ("U" "up" jao-mixer-capture-up :transient t)]
   ["Utilities"
    ("c" "reconnect to mpd" jao-player-connect)
    ("N" "next random album" jao-random-album-next)
    ("r" (lambda ()
           (concat (if jao-random-album-active "dis" "en") "able random album"))
     jao-random-album-toggle)
    ("P" "pasystray" jao-toggle-pasystray-applet :if jao-is-linux)]])

(global-set-key (kbd "s-m") #'jao-transient-media)

(jao-mpc-setup nil (jao-when-linux 70))

;;; Graphical window system

(defvar jao-exwm-enabled nil)
(defun jao-exwm-enabled-p () jao-exwm-enabled)

(defvar jao-xmonad-enabled
  (jao-when-linux (string= "xmonad" (or (getenv "wm") ""))))
(defun jao-xmonad-enabled-p () jao-xmonad-enabled)

(defvar jao-wayland-enabled
  (jao-when-linux (string= "wayland" (or (getenv "XDG_SESSION_TYPE") ""))))

(defvar jao-river-enabled
  (jao-when-linux (jao-shell-running-p "river")))

(jao-when-darwin
 (defvar jao-sway-enabled nil)
 (defun jao-wayland-enabled-p () nil)
 (defun jao-river-enabled-p () nil))

(jao-d-l
 (when (display-graphic-p)
   (setq jao-minibuffer-info-face 'jao-themes-dimm)
   (jao-mode-line-add-to-minibuffer-left 90))
 (require 'jao-custom-x11))

;;; Global transients
(defun jao-list-packages ()
  (interactive)
  (jao-afio-goto-scratch t)
  (package-list-packages))

(defun jao-window-system-p ()
  (or (not (jao-is-linux))
      jao-exwm-enabled jao-xmonad-enabled jao-wayland-enabled))

(defun jao-x11-p ()
  (jao-when-linux (or jao-exwm-enabled jao-xmonad-enabled)))

(defun jao-reveal ()
  (interactive)
  (cond ((or outline-minor-mode (derived-mode-p 'outline-mode ))
         (outline-show-entry))
        ((derived-mode-p 'org-mode) (org-reveal))))

(jao-def-exec-in-term "aptitude" "aptitude" (jao-afio-goto-scratch))
(jao-def-exec-in-term "htop" "htop" (jao-afio-goto-scratch))
(jao-def-exec-in-term "sudo-htop" "sudo htop" (jao-afio-goto-scratch))

(defun jao-sieve-manage ()
  (interactive)
  (sieve-manage "imap.mailbox.org"))

(jao-d-l
 (progn
   (defun jao-open-firefox () (interactive) (jao-mac-open "-a Firefox"))
   (defun jao-open-nnw () (interactive) (jao-mac-open "-a NetNewsWire"))
   (defun jao-open-safari () (interactive) (jao-mac-open "-a Safari"))
   (defun jao-open-telegram () (interactive) (jao-mac-open "-a Telegram"))

   (defun jao-open-skim-doc-in-emacs ()
     (interactive)
     (let ((jao-pdf-open-in-emacs t))
       (jao-skim-open-current-doc)))

   (global-set-key (kbd "s-f") #'jao-open-safari)
   ;; (global-set-key (kbd "s-n") #'jao-open-nnw)
   ;; (global-set-key (kbd "s-t") #'jao-open-telegram)
   (global-set-key (kbd "s-t") #'eat)

   (defun jao-safari-internal-browse ()
     (interactive)
     (when-let* ((url (jao-safari-current-url)))
       (jao-browse-url-browse url)))

   (transient-define-prefix jao-transient-utils ()
     "Global operations."
     [["Notes"
       ("n" "create new note" jao-org-notes-create)
       ("/" "open note" jao-org-notes-open)
       ("\\" "open note by tags" jao-org-notes-consult-tags)
       ("N" "ripgrep all notes" jao-org-notes-consult-ripgrep)
       ("C" "ripgrep category" jao-org-notes-consult-ripgrep-category)]
      ["Documents"
       ("d" "go to doc" jao-select-pdf)
       ("o" "open doc" jao-open-doc)
       ("c" "view cache" doc-view-dired-cache)]
      ;; ["External"
      ;;  ("xn" "browse NNW article" jao-nnw-browse-current-article)
      ;;  ("xs" "browse safary article" jao-safari-internal-browse)
      ;;  ("xk" "open skim doc" jao-open-skim-doc-in-emacs)
      ;;  ("xe" "choose an emoji" ns-do-show-character-palette
      ;;   :if display-graphic-p)]
      ["Blog"
       ("bn" "create post" jao-org-static-blog-create-new-post)
       ("bd" "create draft" jao-org-static-blog-create-new-draft)
       ("be" "edit draft" jao-org-static-blog-edit-draft)]
      ["Afio"
       ("g" "mail" jao-afio-goto-mail)
       ("z" "docs" jao-afio-goto-docs)
       ("w" "wwww" jao-afio-goto-www)
       ("f" "main" jao-afio-goto-main)
       ;; ("a" "save configuration" jao-afio-save-configuration)
       ]
      ["Network"
       ("S" "sieve" jao-sieve-manage)
       ("s" "ssh" jao-ssh)
       ("r" "r2e" jao-r2e)
       ("T" "telegram rooster" jao-telega)
       ("M" "mastodon" mastodon)
       ;; ("j" "notmuch jump" jao-notmuch-jump)
       ]
      ["Utilities"
       ("l" "packages" jao-list-packages)
       ("F" "copy buffer file name" copy-buffer-file-name-as-kill)
       ("p" "passwords" password-store-menu)
       ("m" "music" jao-transient-media)
       ("t" "htop" jao-term-sudo-htop)]]))

 (transient-define-prefix jao-transient-utils ()
   "Global operations."
   [["Notes"
     ("n" "create new note" jao-org-notes-create)
     ("/" "open note" jao-org-notes-open)
     ("\\" "open note by tags" jao-org-notes-consult-tags)
     ("g" "ripgrep notes" jao-org-notes-consult-ripgrep)]
    ["Documents"
     ("dd" "go to doc" jao-select-pdf :if display-graphic-p)
     ("do" "open doc" jao-open-doc)
     ("dr" "search docs with recoll" jao-recoll-consult-docs)]
    ["Monitors"
     ("p" "list projects" list-projects)
     ;; ("p" "htop" jao-term-htop)
     ("P" "pasytray" jao-toggle-pasystray-applet)
     ("x" "restart i3bar" jao-river-restart-i3bar :if jao-river-enabled-p)
     ("x" "restart xmobar" jao-xmobar-restart :if jao-exwm-enabled-p)
     ("x" "kill xmobar" jao-xmobar-kill :if jao-xmonad-enabled-p)]
    ["Network"
     ("s" "ssh" jao-ssh)
     ("b" "bluetooth" bluetooth-list-devices)
     ("c" "connect chats" jao-all-chats)
     ("S" "sieve" jao-sieve-manage)]
    ["Chats"
     ("i"  "irc" jao-chats-irc)
     ;; ("M" "mastodon" jao-mastodon)
     ("T" "telegram rooster" jao-telega)]
    ["Window system" :if jao-window-system-p
     ("w" "set wallpaper" jao-set-wallpaper)
     ("W" "set radom wallpaper" jao-set-random-wallpaper)
     ("B u" (lambda ()
              (let ((b (jao-brightness)))
                (format "bright up %s" (and (string-match ".*\\((.+)\\).*" b)
                                            (match-string 1 b)))))
      jao-bright-up :transient t)
     ("B d" "bright down" jao-bright-down :transient t)]
    ["Utilities"
     ("a" "aptitude" jao-term-aptitude)
     ("l" "packages" jao-list-packages)
     ("v" "view video" jao-view-video)]
    ["Timers"
     ("t t" "set new" tmr)
     ("t c" "cancel" tmr-cancel)
     ("t l" "list" tmr-list-timers)]
    ["Helpers"
     ;; ("r" "reveal" jao-reveal)
     ("r" "translate" reverso)
     ("f" "copy buffer file name" copy-buffer-file-name-as-kill)
     ("k" (lambda () (concat "keyboard" (when (jao-kb-toggled-p) "*")))
      jao-kb-toggle :if jao-x11-p)]]))

(global-set-key (kbd "s-w") #'jao-transient-utils)

(global-set-key (kbd "<f4>")
                (if (display-graphic-p) #'delete-frame #'jao-transient-utils))

;;; Global key bindings
(defun jao-global-keybindings ()
  (interactive)
  (global-set-key (kbd "<f2>") #'magit-status)
  (global-set-key (kbd "C-x p") #'jao-prev-window)
  (global-set-key (kbd "C-x o") 'other-window)
  (global-set-key "\C-cj" #'join-line)
  (global-set-key "\C-cn" #'next-error)
  (global-set-key "\C-cq" #'auto-fill-mode)
  (global-set-key "\C-xr\M-w" #'kill-rectangle-save)
  (global-set-key "\C-c\C-z" #'comment-or-uncomment-region)
  (global-set-key "\C-z" #'comment-or-uncomment-region)
  (jao-when-darwin (global-set-key (kbd "M-`") 'other-frame)
                   (global-set-key (kbd "s-e") nil)))

(jao-global-keybindings)

;;; Last minute (post.el)
(jao-load-site-el "post")
