Advertisement
Guest User

Untitled

a guest
May 24th, 2018
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lisp 15.20 KB | None | 0 0
  1. (provide 'my/utils)
  2.  
  3. (require 'f)
  4.  
  5. ;; See how this works and how it is used
  6. (defmacro my/with-advice (adlist &rest body)
  7.   "Execute BODY with temporary advice in ADLIST.
  8.  
  9. TODO You could also do this with something like the noflet package, if you prefer.
  10.  
  11. Each element of ADLIST should be a list of the form
  12.  (SYMBOL WHERE FUNCTION [PROPS])
  13. suitable for passing to `advice-add'.  The BODY is wrapped in an
  14. `unwind-protect' form, so the advice will be removed even in the
  15. event of an error or nonlocal exit."
  16.   (declare (debug ((&rest (&rest form)) body))
  17.            (indent 1))
  18.   `(progn
  19.      ,@(mapcar (lambda (adform)
  20.                  (cons 'advice-add adform))
  21.                adlist)
  22.      (unwind-protect (progn ,@body)
  23.        ,@(mapcar (lambda (adform)
  24.                    `(advice-remove ,(car adform) ,(nth 2 adform)))
  25.                  adlist))))
  26.  
  27. (defun my/call-logging-hooks (command &optional verbose)
  28.   "Call COMMAND, reporting every hook run in the process.
  29. Interactively, prompt for a command to execute.
  30.  
  31. Return a list of the hooks run, in the order they were run.
  32. Interactively, or with optional argument VERBOSE, also print a
  33. message listing the hooks.
  34.  
  35. [[https://emacs.stackexchange.com/questions/19578/list-hooks-that-will-run-after-command][List hooks that will run after command - Emacs Stack Exchange]]
  36.  
  37. There are some caveats.
  38. "
  39.   (interactive "CCommand to log hooks: \np")
  40.   (let* ((log     nil)
  41.          (logger (lambda (&rest hooks)
  42.                    (setq log (append log hooks nil)))))
  43.     (my/with-advice
  44.      ((#'run-hooks :before logger))
  45.      (call-interactively command))
  46.     (when verbose
  47.       (message
  48.        (if log "Hooks run during execution of %s:"
  49.          "No hooks run during execution of %s.")
  50.        command)
  51.       (dolist (hook log)
  52.         (message "> %s" hook)))
  53.     log))
  54.  
  55.  
  56. (defun get-string-from-file (filePath)
  57.   "Return filePath's file content."
  58.   (with-temp-buffer
  59.     (insert-file-contents filePath)
  60.     (buffer-string)))
  61.  
  62.  
  63. (defun exit ()
  64.   "Exit/return early from an elisp file
  65.  How is this not a builtin?"
  66.   (with-current-buffer " *load*"
  67.     (goto-char (point-max))))
  68.  
  69. (defun log-it (message)
  70.   "I want my own function because emacs does not remember messages after init"
  71.   (bash "cat > $NOTES/programs/messages.log"))
  72.  
  73. ;; Use this to print messages when debugging .emacs
  74. ;; I can use tmux, but, hide the window
  75. ;; I need a command that can use stdin.
  76. ;; emacs uses ptys. Therefore, It's hard to separate output. So I should write my own mechanism to collect stdout.
  77. ;; If I always use tmux, then it's ok. Always detach tmux.
  78. ;; TODO use (bash) to *locate* org files rather than searching for them.
  79.  
  80. (defun sh-notty (&optional cmd stdin)
  81.   "Runs command in shell and return the result"
  82.   (interactive)
  83.   (if (not cmd)
  84.       (setq cmd "false"))
  85.  
  86.   (setq tf (make-temp-file "elispbash"))
  87.  
  88.   (setq final_cmd (concat "( cd \"" (get-dir) "\"; " cmd ") > " tf))
  89.  
  90.   (if (not stdin)
  91.       (progn
  92.         (shell-command final_cmd))
  93.     (with-temp-buffer
  94.       (insert stdin)
  95.       (shell-command-on-region (point-min) (point-max) final_cmd)))
  96.   (setq output (get-string-from-file tf))
  97.  
  98.   output)
  99.  
  100. (defun bash (&optional cmd stdin b_output tm_session)
  101.   (interactive)
  102.   (sh cmd stdin b_output tm_session "bash"))
  103.  
  104. (defun zsh (&optional cmd stdin b_output tm_session)
  105.   (interactive)
  106.   (sh cmd stdin b_output tm_session "zsh"))
  107.  
  108. (defun sh (&optional cmd stdin b_output tm_session shell)
  109.   "Runs command in a new tmux window and optionally returns the output of the command as a string.
  110. b_output is (t/nil) tm_session is the session of the new tmux window"
  111.   (interactive)
  112.   ;; (message "starting")
  113.  
  114.   (if (not shell)
  115.       (setq shell "bash"))
  116.  
  117.   (if (not tm_session)
  118.       (setq tm_session "localhost_current"))
  119.  
  120.   (setq session-dir-cmd (concat "nw -sh " shell " -t " tm_session  " -d -c \"" (get-dir) "\" \"" cmd "\""))
  121.  
  122.   (if b_output
  123.       ;; This means bash is recursive. Can't do this.
  124.       ;; (setq tf (bash "nix tf tempfile dat"))
  125.       (setq tf (make-temp-file "elispbash")))
  126.  
  127.   (if (not cmd)
  128.       (setq cmd "zsh"))
  129.  
  130.   (if b_output
  131.       ;; unbuffer breaks stdout
  132.       (if stdin
  133.           (setq final_cmd (concat "tm -f -s -sout " session-dir-cmd " > " tf))
  134.         (setq final_cmd (concat "unbuffer tm -f -fout " session-dir-cmd " > " tf)))
  135.     (if stdin
  136.         (setq final_cmd (concat "tm -f -S -tout " session-dir-cmd))
  137.       (setq final_cmd (concat "unbuffer tm -f -d -tout -d -te " session-dir-cmd))))
  138.  
  139.   ;; (message (concat  "bash: " final_cmd))
  140.  
  141.   (if (not stdin)
  142.       (shell-command final_cmd)
  143.     (with-temp-buffer
  144.       (insert stdin)
  145.       ;; This only returns the exit code. I want stdout
  146.  
  147.       (shell-command-on-region (point-min) (point-max) final_cmd))
  148.  
  149.     ;; This does not fix it
  150.     ;; (with-output-to-string
  151.     ;;   (shell-command-on-region (point-min) (point-max) final_cmd)
  152.     ;;   )
  153.  
  154.     )
  155.   ;; (message (concat  "bash-done: " final_cmd))
  156.  
  157.   (if b_output
  158.       ;; (sleep-for 5)
  159.       ;; Cat tf
  160.       (progn
  161.         (setq output (get-string-from-file tf))
  162.         ;; (message (concat  "output: " output))
  163.         output)
  164.     ))
  165.  
  166.  
  167. (defun my/add-all-commit ()
  168.   (interactive)
  169.   (bash "git add -A .; git commit \"$(k f8)\"")
  170.   (message "Added all changes to git and committed."))
  171.  
  172.  
  173. (defun select-tmux-current ()
  174.   (interactive)
  175.   ;; This doesn't work because it selects itself
  176.   ;; (bash "tm -f -d select-current")
  177.   (shell-command "tm -f -d select-current"))
  178.  
  179.  
  180. (defun tv (stdin)
  181.   "converts the parameter to its string representation and pipes it into tmux"
  182.   (interactive)
  183.   (bash "v" (format "%s" stdin))
  184.   (select-tmux-current))
  185.  
  186.  
  187. ;; (message (sed "s/a/b/g" "aaaa"))
  188. (defun sed (command stdin)
  189.   "wrapper around sed"
  190.   (interactive)
  191.   (setq stdin (format "%s" stdin))
  192.   (setq command (concat "sed '" (format "%s" command) "'"))
  193.   (sh-notty command stdin))
  194.  
  195.  
  196. (defun tmux-bash (&optional cmd)
  197.   "Runs command in a new tmux window"
  198.   (interactive)
  199.   (if (not cmd)
  200.       (setq cmd "zsh"))
  201.   (shell-command (concat "unbuffer tm -f -d -te nw -c \"" (get-dir) "\" \"" cmd "\"")))
  202.  
  203.  
  204. ;; Use this when I get the error. Eshell buffer goes into "text is read only", can't type #3565
  205. (defun eshell/clear ()
  206.   "Clear the eshell buffer."
  207.   (interactive)
  208.   (let ((inhibit-read-only t))
  209.     (erase-buffer)))
  210.  
  211.  
  212. (defun my/slurp (f)
  213.   (with-temp-buffer
  214.     (insert-file-contents f)
  215.     (buffer-substring-no-properties
  216.      (point-min)
  217.      (point-max))))
  218.  
  219.  
  220. (defun my/load-list (f)
  221.   "split-string splits the file into a list of strings. mapcar intern turns the list of strings into a list of symbols"
  222.   (mapcar 'intern
  223.           (split-string
  224.            (my/slurp f) "\n" t)))
  225.  
  226.  
  227. (defun my-load-all-in-directory (dir)
  228.   "`load' all elisp libraries in directory DIR which are not already loaded."
  229.   (interactive "D")
  230.   (let ((libraries-loaded (mapcar #'file-name-sans-extension
  231.                                   (delq nil (mapcar #'car load-history)))))
  232.     (dolist (file (directory-files dir t ".+\\.elc?$"))
  233.       (let ((library (file-name-sans-extension file)))
  234.         (unless (member library libraries-loaded)
  235.           (load library nil t)
  236.           (push library libraries-loaded))))))
  237.  
  238.  
  239. (defun my-find-file (filename)
  240.   (let ((size-in-bytes (nth 7 (file-attributes filename))))
  241.     (if (< size-in-bytes 1e3)
  242.         (find-file filename)
  243.       (vlf filename))))
  244.  
  245.  
  246. ;; Command filter
  247. (defun cfilter (cmd)
  248.   "This pipes the region or entire buffer through a shell command
  249. This is kinda outdated now."
  250.   (let ((cmd (concat cmd " | s chomp")))
  251.     (if (region-active-p)
  252.         (let ((rstart (region-beginning))
  253.               (rend (region-end)))
  254.           (shell-command-on-region rstart rend cmd nil 1))
  255.       (progn
  256.         (mark-whole-buffer)
  257.         (cfilter cmd)))))
  258.  
  259.  
  260. (defun toggle-evil ()
  261.   (interactive)
  262.   "Tries Holy Mode + falls back to evil"
  263.   (if (fboundp 'spacemacs/toggle-holy-mode)
  264.       (spacemacs/toggle-holy-mode)
  265.     (call-interactively #'evil-mode)))
  266.  
  267. (defun region-or-string (&optional object)
  268.   "Return string rep of object if given, otherwise, return the string of the selected region"
  269.   (interactive)
  270.   (cond ((region-active-p) (buffer-substring (region-beginning) (region-end)))
  271.         (object (format "%s" object))
  272.         (t nil)
  273.         ))
  274.  
  275. (defun q (input)
  276.   "Only quotes if it needs to"
  277.   (interactive)
  278.   (sh-notty "q" input))
  279.  
  280. (defun qne (input)
  281.   "Quotes but removes the ends"
  282.   (interactive)
  283.   (sh-notty "qne" input))
  284.  
  285. (defun uq (input)
  286.   "Unquotes"
  287.   (interactive)
  288.   (sh-notty "uq" input))
  289.  
  290. (defun uqftln (input)
  291.   "Unquotes each line"
  292.   (interactive)
  293.   (sh-notty "uq -ftln" input))
  294.  
  295. (defun qftln (input)
  296.   "Quotes each line"
  297.   (interactive)
  298.   (sh-notty "q -ftln" input))
  299.  
  300.  
  301. (defun fzf (&optional string)
  302.   "Pipes argument or region through fzf"
  303.   (interactive)
  304.   (bash "fzf" (region-or-string string))
  305.   (select-tmux-current)
  306.   )
  307.  
  308. (defun sph (&optional cmd)
  309.   "Runs command in a horizontal split"
  310.   (interactive)
  311.   (if (not cmd)
  312.       (setq cmd "zsh"))
  313.   (shell-command (concat "unbuffer tm -f -d -te sph -c \"" (get-dir) "\" \"" cmd "\"")))
  314.  
  315. (defun spv (&optional cmd)
  316.   "Runs command in a vertical split"
  317.   (interactive)
  318.   (if (not cmd)
  319.       (setq cmd "zsh"))
  320.   (shell-command (concat "unbuffer tm -f -d -te spv -c \"" (get-dir) "\" \"" cmd "\"")))
  321.  
  322. (defun compile-run ()
  323.   (interactive)
  324.   ( shell-command (concat "unbuffer tm -f -te -d spv -args cr \"" (buffer-file-name) "\"") )
  325.   )
  326.  
  327.  
  328. (defmacro make-wrapper (wrappee wrapper)
  329.   "Create a WRAPPER (a symbol) for WRAPPEE (also a symbol)."
  330.   (let ((arglist (make-symbol "arglist")))
  331.     `(defun ,wrapper (&rest ,arglist)
  332.        ,(concat (documentation wrappee) "\n But I do something more.")
  333.        ,(interactive-form wrappee)
  334.        (prog1 (apply (quote ,wrappee) ,arglist)
  335.          (message "Wrapper %S does something more." (quote ,wrapper))))))
  336.  
  337.  
  338. (defun wrappee-interactive (num str)
  339.   "That is the doc string of wrappee-interactive."
  340.   (interactive "nNumber:\nsString:")
  341.   (message "The number is %d.\nThe string is \"%s\"." num str))
  342.  
  343. (defun wrappee-non-interactive (format &rest arglist)
  344.   "That is the doc string of wrappee-non-interactive."
  345.   (apply 'message format arglist))
  346.  
  347. (make-wrapper wrappee-interactive wrapper-interactive)
  348. (make-wrapper wrappee-non-interactive wrapper-non-interactive)
  349. ;; test of the non-interactive part:
  350.  
  351. (wrapper-non-interactive "Number: %d, String: %s" 1 "test")
  352.  
  353.  
  354. ;; This doesnt even work because it uses simpleclip
  355. (defun copy-current-line-position-to-clipboard ()
  356.   "Copy current line in file to clipboard as '</path/to/file>:<line-number>'"
  357.   (interactive)
  358.   (let ((path-with-line-number
  359.          (concat (buffer-file-name) ":" (number-to-string (line-number-at-pos)))))
  360.     ;;(x-select-text path-with-line-number)
  361.     (simpleclip-set-contents path-with-line-number)
  362.     (message (concat path-with-line-number " copied to clipboard"))))
  363.  
  364.  
  365.  
  366.  
  367.  
  368. (defvar my-terminal-run-history nil)
  369.  
  370. ;; But how to get this to show ansi-colors?
  371. (defun my-terminal-run (command &optional name)
  372.   "Runs COMMAND in a `term' buffer."
  373.   (interactive
  374.    (list (read-from-minibuffer "$ " nil nil nil 'my-terminal-run-history)))
  375.   (let* ((name (or name command))
  376.          (switches (split-string-and-unquote command))
  377.          (command (pop switches))
  378.          (termbuf (apply 'make-term name command nil switches)))
  379.     (set-buffer termbuf)
  380.     (term-mode)
  381.     (term-char-mode)
  382.     (switch-to-buffer termbuf)))
  383.  
  384. (global-set-key (kbd "C-c s c") 'my-terminal-run)
  385.  
  386.  
  387. (defun my/beep ()
  388.   (let ((inhibit-message t)) (shell-command "tmux run -b 'a beep'")))
  389.  
  390. ;; This is how to start and stop a timer
  391. ;; (run-with-timer 0 1 #'my-beep)
  392. ;; (cancel-function-timers #'my/beep)
  393.  
  394.  
  395. (defun do-lines (fun &optional start end)
  396.   "Invoke function FUN on the text of each line from START to END."
  397.   (interactive
  398.    (let ((fn   (intern (completing-read "Function: " obarray 'functionp t))))
  399.      (if (use-region-p)
  400.          (list fn (region-beginning) (region-end))
  401.        (list fn (point-min) (point-max)))))
  402.   (save-excursion
  403.     (goto-char start)
  404.     (while (< (point) end)
  405.       (funcall fun (buffer-substring (line-beginning-position) (line-end-position)))
  406.       (forward-line 1))))
  407.  
  408.  
  409. (defun crc32 (string)
  410.   (interactive)
  411.   ;; The extra bash is only necessary for the tmux version
  412.   ;; (bash "bash -c 'crc32 <(cat)' | s chomp" string t)
  413.   (sh-notty "crc32 <(cat) | s chomp" string))
  414.  
  415.  
  416. ;; Pure elisp sha512
  417. (defun sha512 (object &optional start end binary)
  418.   "Return the SHA512 of an OBJECT.
  419. OBJECT is either a string or a buffer. Optional arguments START and
  420. END are character positions specifying which portion of OBJECT for
  421. computing the hash.  If BINARY is non-nil, return a string in binary
  422. form."
  423.   ;; md5
  424.   ;; sha1
  425.   ;; sha224
  426.   ;; sha256
  427.   ;; sha384
  428.   ;; sha512
  429.   ;; Emacs has some builtin hash functions, but I should make everything myself to learn it.
  430.   ;; (secure-hash 'sha1 object start end binary)
  431.   (secure-hash 'sha512 object start end binary))
  432.  
  433.  
  434. (defun my/sha1 (string)
  435.   "Can't replace existing sha1 builtin function."
  436.   (interactive)
  437.   ;; The extra bash is only necessary for the tmux version
  438.   ;; (bash "bash -c 'crc32 <(cat)' | s chomp" string t)
  439.  
  440.   ;; (sh-notty "zsh -c 'sha1sum =(cat) | cut -d \\  -f 1' | s chomp" string)
  441.   (sh-notty "openssl dgst -sha1 -binary" string))
  442.  
  443. (defun test-virtmic (mp3_path)
  444.   (interactive))
  445.  
  446. (defun mp42mkv (path_input)
  447.   "Converts an mp4 into an mkv. Use this when streaming to another computer and I need to watch it as it's streaming."
  448.   (interactive)
  449.   ;; I thought about using sed here, but this is probably better because for performance
  450.   (defvar path_output (concat path_input ".mkv"))
  451.   (bash (concat "ffmpeg -i " path_input " -vcodec copy " path_output)))
  452.  
  453.  
  454. ;; [[https://stackoverflow.com/questions/24565068/emacs-text-is-read-only?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa][lisp - (Emacs) Text is read only? - Stack Overflow]]
  455. ;; Useful as temporary hack to fix slime repl.
  456. (defun set-region-writeable (begin end)
  457.   "Removes the read-only text property from the marked region."
  458.   ;; See http://stackoverflow.com/questions/7410125
  459.   (interactive "r")
  460.   (let ((modified (buffer-modified-p))
  461.         (inhibit-read-only t))
  462.     (remove-text-properties begin end '(read-only t))
  463.     (set-buffer-modified-p modified)))
  464.  
  465.  
  466. (defun cider-connect-tmux ()
  467.   "Scrapes the port from the tmux window and connects to cider"
  468.   (interactive)
  469.   (let ((port
  470.          (sh-notty "tm cat-pane localhost_current:lein-repl.0 | sed -n '/on port \\([0-9]\\+\\)/ s/.*on port \\([0-9]\\+\\).*/\\1/p' | s chomp")))
  471.  
  472.     (cider-connect "localhost" port "$HOME/notes2018/ws/clojure/scratch/")))
  473.  
  474.  
  475. ;; ;; (ignore-errors (kill-buffer "*cider-repl tstprjclj*"))
  476.  
  477. ;; Not using this anymore. Instead, I'm waiting for this to be ready
  478. ;; localhost_ws_clojure_scratch:cider-jack-in-default.0
  479. (defun clojure-cheatsheet-boot ()
  480.   "Not using this anymore"
  481.   (interactive)
  482.   (ignore-errors (kill-buffer "*cider-repl localhost*"))
  483.   (cider-connect-tmux)
  484.   (ignore-errors (clojure-cheatsheet)))
  485.  
  486. (defun py/install-file ()
  487.   "Install a single python file as a module"
  488.  
  489.   )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement