Last active
January 16, 2020 01:03
-
-
Save alanmimms/640b4fee983fc251f18ddc3abb039b42 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;; I needed this for Verilog. I wanted a way to put something in the Emacs kill buffer | |
;;; and "yank" it over and over while incrementing the first found binary value in the kill buffer. | |
;;; It's patterned after another solution I found elsewhere, but this is mostly my code at this point. | |
;;; Bog-standard dumb code I wrote because I thought I could hack it out quickly while learning Elisp. it's nothing | |
;;; wonderful, but maybe it will save someone some time someday. | |
;;; | |
;;; Example: | |
;;; Start with the text | |
;;; case ({ADbool, ADsel}) | |
;;; 5'b1010101: | |
;;; | |
;;; and select and copy to yank buffer (alt-W) the last line of the above. | |
;;; | |
;;; Then yank-binary-and-increment (C-c C-y) will paste a copy of that line each time it's invoked but | |
;;; with the next higher binary number in place of 5'b1010101. Doing this twice yields: | |
;;; case ({ADbool, ADsel}) | |
;;; 5'b1010101: | |
;;; 5'b1010110: | |
;;; 5'b1010111: | |
;;; | |
(defun number-to-binary-string (number n-digits) | |
(setq new-string "") | |
(dotimes (digit-count n-digits) | |
(setq new-string (concat (if (zerop (logand number 1)) "0" "1") new-string)) | |
(setq number (lsh number -1))) | |
new-string) | |
(defun increment-first-binary-string (string) | |
(setq start (string-match "'b[01]+" string)) | |
(setq end (match-end 0)) | |
(unless start (throw 'no-number)) ;Bail safely if no number found | |
(setq first-string (substring string (+ start 2) end)) | |
(setq number (string-to-number first-string 2)) | |
(setq new-num-string (number-to-binary-string (1+ number) (length first-string))) | |
(concat | |
(substring string 0 start) | |
"'b" | |
new-num-string | |
(substring string end))) | |
(defun yank-binary-and-increment () | |
"Yank text, incrementing the first integer found in it." | |
(interactive "*") | |
(catch 'no-number | |
(setq new-text (increment-first-binary-string (current-kill 0))) | |
(insert-for-yank new-text) | |
(kill-new new-text t))) | |
(global-set-key (kbd "C-c C-y") 'yank-binary-and-increment) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment