;;; eshell-conf.el --- My configurations for Eshell -*- lexical-binding: t; -*- ;; Copyright (C) 2021 李俊緯 ;; Author: 李俊緯 ;; Keywords: terminals, tools, convenience ;; This program is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see . ;;; Commentary: ;; This is my configuration file for Eshell, the shell emulation ;; written in Emacs Lisp. ;;; Code: (eval-when-compile (require 'cl-lib) (require 'esh-mode) (require 'eshell)) (require 'esh-util) (require 'em-term) (require 'ring) (require 'type-break) ;;; Measure time of commands and display automatically. ;;;###autoload (defvar-local eshell-current-command-start-time nil "The time of the start of the current command.") ;;;###autoload (defvar-local eshell-prompt-time-string "" "The string displaying the time of the last command, if any.") ;;;###autoload (defun eshell-current-command-start () "Record the start time of the command." (setq-local eshell-current-command-start-time (current-time))) ;;;###autoload (defun eshell-current-command-stop () "Record the stop time of the last command." (cond ((timep eshell-current-command-start-time) (let* ((elapsed-time (time-since eshell-current-command-start-time)) (elapsed-time-list (time-convert elapsed-time 'list)) (elapsed-time-int (time-convert elapsed-time 'integer)) (format-seconds-string (format-seconds "%yy %dd %hh %mm %ss%z" elapsed-time-int)) (microseconds (caddr elapsed-time-list)) (micro-str (cond ((or (>= elapsed-time-int 1) (> microseconds 10000)) (format "%dμs" microseconds))))) (setq eshell-prompt-time-string (mapconcat #'identity (delq nil (list format-seconds-string micro-str)) " "))) (setq eshell-current-command-start-time nil)))) ;;;###autoload (defun eshell-current-command-time-track () "Add hooks to track command times." (add-hook 'eshell-pre-command-hook #'eshell-current-command-start nil t) (add-hook 'eshell-post-command-hook #'eshell-current-command-stop nil t)) ;;;###autoload (defun eshell-start-track-command-time () "Start tracking the time of commands." (cond ((derived-mode-p 'eshell-mode) (eshell-current-command-time-track))) (add-hook 'eshell-mode-hook #'eshell-current-command-time-track)) ;;;###autoload (defun eshell-stop-track-command-time () "Stop tracking the execution times of commands." (remove-hook 'eshell-pre-command-hook #'eshell-current-command-start t) (remove-hook 'eshell-post-command-hook #'eshell-current-command-stop t) (remove-hook 'eshell-mode-hook #'eshell-current-command-time-track)) ;;;###autoload (defun durand-eshell-emit-prompt () "Emit a prompt if eshell is being used interactively. Add a time information at the beginning. -- Modified by Durand." (when (boundp 'ansi-color-context-region) (setq ansi-color-context-region nil)) (run-hooks 'eshell-before-prompt-hook) (if (not eshell-prompt-function) (set-marker eshell-last-output-end (point)) (let ((prompt (funcall eshell-prompt-function))) (and eshell-highlight-prompt (add-text-properties 0 (length prompt) '(read-only t font-lock-face eshell-prompt front-sticky (font-lock-face read-only) rear-nonsticky (font-lock-face read-only)) prompt)) (eshell-interactive-print (mapconcat #'identity (delq nil (list (cond ((> (length eshell-prompt-time-string) 0) (propertize eshell-prompt-time-string 'font-lock-face 'modus-themes-heading-1 'read-only t 'front-sticky '(font-lock-face read-only) 'rear-nonsticky '(font-lock-face read-only))) ) prompt)) " ")) (setq eshell-prompt-time-string ""))) (run-hooks 'eshell-after-prompt-hook)) (advice-add #'eshell-emit-prompt :override #'durand-eshell-emit-prompt) ;;; Eshell sets the keymap in the major mode function ;;;###autoload (add-hook 'eshell-mode-hook #'durand-set-eshell-keys) ;;;###autoload (defun durand-set-eshell-keys () "Set my key-bindings." (define-key eshell-mode-map (vector #xf) ; C-o #'eshell-clear)) ;;; YouTube URL ;;;###autoload (defun eshell/yt-url (&rest args) "Run `durand-convert-youtube-video-to-url' on the first of ARGS." (eshell-eval-using-options "yt-url" args '((?o "open" nil open-p "Open in the default external browser.") (?h "help" nil nil "Print this help message.") :parse-leading-options-only :usage "[-ho] video-name" :show-usage) (eshell-yt-url args open-p))) ;;;###autoload (defun eshell-yt-url (&optional video-name open-p) "Save the URL of a video downloaded from YouTube to the `kill-ring'. The video is given by VIDEO-NAME. If OPEN-P is non-nil, then open the video in the default external browser instead." (let ((url (durand-convert-youtube-video-to-url (eshell-flatten-and-stringify video-name)))) (cond ((string= url "") (user-error "Please specify VIDEO-NAME")) (open-p (browse-url-default-browser url)) ((kill-new url))))) ;;; Clear screen ;;;###autoload (defun eshell-clear (num) "Deletes the buffer. Do NUM times `eshell-previous-prompt' before deleting." (interactive (list (cond ((null current-prefix-arg) 0) ((prefix-numeric-value current-prefix-arg))))) (let ((inhibit-read-only t)) (delete-region (point-min) (save-excursion (eshell-previous-prompt num) (line-beginning-position))))) ;;; Jump ;; NOTE: This should be replaced by the bookmarks of Emacs. ;;;###autoload (defun eshell/j (&rest args) "Implementation of `j'. See `eshell-j' for the actual functionality and for the format of ARGS." (eshell-eval-using-options "j" args '((?r "recent" 'exclusive use-recent-p "Find in recent directories instead of symbolic links.") (?a "all" nil use-recent-p "Find both in recent directories and in symbolic links.") (?h "help" nil nil "Print this help message.") :usage "[-hra] [short-cut]") (eshell-j args use-recent-p))) ;;;###autoload (defun eshell/mark (&rest args) "Add symbolic links to `eshell-mark-directory'. The argument ARGS should be list of one string which names the link name. If no argument is given, the base name of the current directory is used." ;; (setq args (cons default-directory args)) ;; (setq args (durand-eshell-delete-dups args :test #'string=)) (setq args (cond ((consp args) (car (flatten-tree args))) ((file-name-nondirectory (directory-file-name (file-name-directory default-directory)))))) (eshell-command-result (format "ln -sf \"%s\" \"%s\"" default-directory (expand-file-name args eshell-mark-directory)))) ;;;###autoload (defun eshell/marks () "List all symbolic links. Just for the completeness." (let* ((dirs (directory-files eshell-mark-directory nil (rx-to-string '(seq bos (or (not ".") (seq "." (not "."))))))) (max-length (apply #'max (mapcar #'length dirs)))) (mapconcat (function (lambda (mark) (concat (propertize mark 'font-lock-face 'modus-themes-mark-sel) (make-string (- max-length (length mark)) #x20) " -> " (file-truename (expand-file-name mark eshell-mark-directory))))) dirs "\n"))) ;;;###autoload (defun durand-eshell-delete-dups (sequence &rest args) "Return a copy of SEQUENCE with duplicate elements removed. ARGS should be a property list specifying tests and keys. If the keyword argument TEST is non-nil, it should be a function with two arguments which tests for equality of elements in the sequence. The default is the function `equal'. If the keyword argument KEY is non-nil, it should be a function with one argument which returns the key of the element in the sequence to be compared by the test function. The default is the function `identity'. Note that this function is not supposed to change global state, including match data, so the functions in TEST and KEY are supposed to leave the global state alone as well. \(fn SEQUENCE &key TEST KEY)" (declare (pure t) (side-effect-free t)) (let* ((len (length sequence)) (temp-obarray (obarray-make len)) (valid-key-num (+ (cond ((plist-member args :key) 1) (0)) (cond ((plist-member args :test) 1) (0)))) (key (cond ((cadr (plist-member args :key))) (#'identity))) (test-fn (cond ((cadr (plist-member args :test))) (#'equal))) found-table result) (cond ((or (= (mod (length args) 2) 1) (> (length args) (* 2 valid-key-num))) (user-error "Invalid keyword arguments. Only :key and :test are allowed, but got %S" args))) ;; Note: This just puts a property to the symbol. (define-hash-table-test 'durand-delete-dups-test test-fn (function (lambda (obj) (intern (format "%S" obj) temp-obarray)))) (setq found-table (make-hash-table :test 'durand-delete-dups-test :size len)) (mapc (function (lambda (element) (cond ((gethash (funcall key element) found-table)) ;; Abuse the fact that `puthash' always returns VALUE. ((puthash (funcall key element) t found-table) (setq result (cons element result)))))) sequence) (nreverse result))) ;;;###autoload (defvar eshell-mark-directory (expand-file-name "~/.marks") "The directory that stores links to other directories.") ;;;###autoload (defun eshell-j (&optional short-cut use-recent-p) "Jump to SHORT-CUT. Where this jumps to is determined by the symbolic links in the directory `eshell-mark-directory'. If USE-RECENT-P is non-nil, then also include recent directories in the list of candidates. Moreover, if USE-RECENT-P is 'exclusive, then only list the recent directories as candidates, unless there are no recent directories, in which case it falls back to use the marks as the candidates." (let* ((mark-directory eshell-mark-directory) (short-cut (eshell-flatten-and-stringify short-cut)) (links (delq nil (mapcar (function (lambda (name) (cond ((or (string= "." (file-name-nondirectory name)) (string= ".." (file-name-nondirectory name))) nil) (name)))) (directory-files mark-directory t short-cut t)))) (candidates (cond ((and use-recent-p (not (eq use-recent-p 'exclusive)) (ring-p eshell-last-dir-ring) (not (ring-empty-p eshell-last-dir-ring))) (append (mapcar (function (lambda (file) (cons (file-name-nondirectory file) file))) links) (cond ((string-match-p short-cut mark-directory) (list (cons mark-directory mark-directory)))) (mapcar (function (lambda (file) (cons file file))) (ring-elements eshell-last-dir-ring)))) ((and use-recent-p (eq use-recent-p 'exclusive) (ring-p eshell-last-dir-ring) (not (ring-empty-p eshell-last-dir-ring))) (mapcar (function (lambda (file) (cons file file))) (ring-elements eshell-last-dir-ring))) ((append (mapcar (function (lambda (file) (cons (file-name-nondirectory file) file))) links) (cond ((string-match-p short-cut mark-directory) (list (cons mark-directory mark-directory)))))))) ;; Delete duplicate items (candidates (durand-eshell-delete-dups candidates :test #'string= ;; In Haskell this woule be a simple function composition. :key (function (lambda (ls) (file-truename (cdr ls)))))) ;; Delete non-matching ones (candidates (delq nil (mapcar (lambda (cand) (cond ((string-match-p short-cut (cdr cand)) cand))) candidates)))) (cond ((null candidates) (user-error "No candidates matching %s found" short-cut)) ((null (cdr candidates)) ;; Only one candidate (eshell/cd (file-truename (cdar candidates)))) ((eshell/cd (file-truename (cdr (assoc (let ((completion-regexp-list (cons short-cut completion-regexp-list))) (completing-read "Choose a link: " candidates nil t)) candidates #'string=)))))))) ;;; convenient ls ;;;###autoload (defun eshell/l (&rest args) "Equivalent with ls -ahl ARGS. If called without ARGS, then use ./ instead." (eshell/ls "-hal" (or args "./"))) ;;; Integration with Tramp (add-to-list 'eshell-modules-list 'eshell-tramp) ;;; Substitute commands ;;;###autoload (defun eshell/r (&rest args) "Replace the last command by the specifications in ARGS." (eshell-eval-using-options "r" args '((?h "help" nil nil "Print this help message") (?n "number" t last-number "Which last command to replace") :usage "[-n number] [replacement specifications...] REPLACEMENT SPECIFICATIONS are pairs of the form MATCH=REPLACE. This command will find the last command, or the last N-th command if given the option -n, and replace any match of MATCH by REPLACE." :preserve-args :parse-leading-options-only :show-usage) (eshell-r args last-number))) ;;;###autoload (defun eshell-r (args &optional last-number) "Replace the LAST-NUMBER th command by ARGS. ARGS are pairs of the form MATCH=REPLACE. This command will find the last command, or the LAST-NUMBER-th command if LAST-NUMBER is non-nil, and replace the first match of MATCH by REPLACE. LAST-NUMBER is passed to `prefix-numeric-value': If it is nil, then it means 1; if it is a minus sign, then it means -1; if it is a cons cell, and its `car' is an integer, then it means its `car'; if it is an integer, then it means that integer; and any other value means 1." (let* ((last-number (prefix-numeric-value last-number)) (args (mapcar (lambda (pair) (split-string pair "=")) args)) (nth-last-command (ring-ref eshell-history-ring last-number)) temp) ;; Transform ARGS to the required format. ;; NOTE; Using `mapc' is recommended by the manual. (mapc (function (lambda (arg) (cond ((and (consp arg) (= (length arg) 2) (stringp (car arg)) (stringp (cadr arg))) (setq temp (cons arg temp))) ((and (consp arg) (= (length arg) 1) (stringp (car arg))) (setq temp (cons (list (caar temp) (concat (cadar temp) (cons 32 nil) (car arg))) (cdr temp)))) ((user-error "Wrong specification: MATCH=REPLACE required, but got %S" arg))))) args) (setq args (nreverse temp)) ;; Replace the command (save-match-data (while (consp args) (setq temp (car args)) (cond ;; Cannot use `string-match-p' here. ((string-match (car temp) nth-last-command) (setq nth-last-command (replace-match (or (cadr temp) "") t nil nth-last-command)))) (setq args (cdr args)))) ;; Let the user know what the result of substitution is. (eshell-printn nth-last-command) ;; Check we don't do another r command. (cond ((and (/= (length nth-last-command) 0) (= (aref nth-last-command 0) ?r) (or (= (length nth-last-command) 1) (= (aref nth-last-command 1) 32))) (user-error "Repeating a repeating command. This is probably not what you want"))) (eshell-command-result nth-last-command))) ;;; Expand history (add-to-list 'eshell-expand-input-functions #'eshell-expand-history-references) ;;; Expand multiple dots (defun durand-eshell-expand-dots (beg end) "Expand multiple dots in BEG and END. For example, \"...\" expands into \"../..\"." (save-excursion (save-match-data (let ((str (buffer-substring beg end)) (start 0)) (while (string-match (rx ".." (1+ ".")) str start) (let* ((matched (match-string 0 str)) (len (length matched))) (setq str (replace-match (let ((result "..") (index 2)) (while (< index len) (setq index (1+ index)) (setq result (concat result "/.."))) result) nil nil str)) (setq start (+ (match-end 0) (lsh (- len 2) 1))))) (goto-char beg) (delete-region beg end) (insert str))))) (add-to-list 'eshell-expand-input-functions #'durand-eshell-expand-dots) ;;; Visual commands (add-to-list 'eshell-visual-commands "mpv" nil #'string=) (add-to-list 'eshell-visual-subcommands (list "git" "log" "diff" "show" "help")) ;;; List files after changing directories (setq eshell-list-files-after-cd t) ;;; Eshell bookmark handler (defun durand-eshell-bookmark-jump (bookmark) "Handle Eshell BOOKMARK in my preferred way." (let ((handler (bookmark-get-handler bookmark)) (location (bookmark-prop-get bookmark 'location)) (eshell-buffers (delq nil (mapcar (lambda (buffer) (cond ((provided-mode-derived-p (buffer-local-value 'major-mode buffer) 'eshell-mode) buffer))) (buffer-list))))) (cond ((and (stringp location) (not (string= location "")) (memq handler (list #'eshell-bookmark-jump #'durand-eshell-bookmark-jump))) (let (reuse-p) (mapc (lambda (buffer) (cond ((string= (buffer-local-value 'default-directory buffer) location) (setq reuse-p buffer)))) eshell-buffers) ;; Don't switch to that buffer, otherwise it will cause ;; problems if we want to open the bookmark in another window. (cond (reuse-p (set-buffer reuse-p)) ;; eshell will pop the buffer ((let ((buffer (generate-new-buffer eshell-buffer-name))) (with-current-buffer buffer (setq-local default-directory location) (eshell-mode)) (set-buffer buffer)))))) ((user-error "Cannot jump to this bookmark"))))) (advice-add #'eshell-bookmark-jump :override #'durand-eshell-bookmark-jump) (provide 'eshell-conf) ;;; eshell-conf.el ends here