Display the binary version of hex value in status bar - emacs

I am doing a lot of embedded C programming right now, which means that I am writing things like this all the time:
(ioe_extra_A & 0xE7)
It would be super useful, if when put my cursor on the 0xE7, emacs would display "0b1110 0111" in the status bar or mini-buffer, so I could check that my mask is what I meant it to be.
Typically, no matter what it is I want emacs to do, 10 minutes of Googling will turn up the answer, but for this one, I have exhausted my searching skills and still not turned up an answer.
Thanks ahead of time.

This seems to work:
(defvar my-hex-idle-timer nil)
(defun my-hex-idle-status-on ()
(interactive)
(when (timerp my-hex-idle-timer)
(cancel-timer my-hex-idle-timer))
(setq my-hex-idle-timer (run-with-idle-timer 1 t 'my-hex-idle-status)))
(defun my-hex-idle-status-off ()
(interactive)
(when (timerp my-hex-idle-timer)
(cancel-timer my-hex-idle-timer)
(setq my-hex-idle-timer nil)))
(defun int-to-binary-string (i)
"convert an integer into it's binary representation in string format
By Trey Jackson, from https://stackoverflow.com/a/20577329/."
(let ((res ""))
(while (not (= i 0))
(setq res (concat (if (= 1 (logand i 1)) "1" "0") res))
(setq i (lsh i -1)))
(if (string= res "")
(setq res "0"))
res))
(defun my-hex-idle-status ()
(let ((word (thing-at-point 'word)))
(when (string-prefix-p "0x" word)
(let ((num (ignore-errors (string-to-number (substring word 2) 16))))
(message "In binary: %s" (int-to-binary-string num))))))
Type M-x my-hex-idle-status-on to turn it on.
As noted, thanks to Trey Jackson for int-to-binary-string.

Related

Emacs jump to next annotated words or phrases

When using Emacs, I notice that words or phrases in a buffer can be annotated or highlighted by many minor modes like hi-lock-mode, flyspell-mode, flycheck-mode...
Is there any uniform way to jump to the highlighted words or phrases created by all these minor modes? Specifically, is there any package or function support jumping to the next and previous highlighted phrases?
When using Eclipse, I can do it by pressing Ctrl-. and Ctrl-,. However, when switching to Emacs, so far, I haven't found an equivalent feature.
Developing a mode which aims to tackle that kind of tasks
https://github.com/andreas-roehler/werkstatt/tree/master/general-key
Facilitates the setting of a general command.
Than this command gets different bindings according to modes - which needs to be edited by hand once. Afterwards it allows to set/change a key at one place for all related/bound commands.
See for example inside
https://github.com/andreas-roehler/werkstatt/blob/master/general-key/general-key-python-mode.el
It's alpha still notably for the install process. Bug reports resp. feature requests welcome.
Not surprisingly, #Drew has answered something related to this.
You can programmatically use isearch with something like:
(defun foo (regexp)
(interactive (list (read-regexp "Regexp: ")))
(isearch-mode t t)
(let ((isearch-regexp nil))
(isearch-yank-string regexp)))
This will pull your previous regexp history, including those from hi-lock. I imagine it would be a fun exercise to modify this to use hi-lock-regexp-history.
If you use swiper, you can restrict the search candidates to lines with highlighted patterns by hi-lock-mode.
Here is a simple wrapper of swiper:
(require 'cl-lib)
(defun swiper-over-highlights-simple ()
(interactive)
(let ((original-swiper--candidates (symbol-function 'swiper--candidates)))
(cl-letf (((symbol-function 'swiper--candidates)
(lambda ()
(let ((pattern (mapconcat #'car hi-lock-interactive-patterns "\\|")))
(cl-remove-if-not (lambda (x) (string-match-p pattern x))
(funcall original-swiper--candidates))))))
(swiper))))
In addition, you can change ivy-read's preselect argument, which initializes the first matched line inside swiper.
The following fuction, modified from swiper, finds the closest next line with a highlighted pattern:
(defun swiper-over-highlights (&optional initial-input)
(interactive)
(let ((original-swiper--candidates (symbol-function 'swiper--candidates))
(pattern (mapconcat #'car hi-lock-interactive-patterns "\\|")))
(cl-letf (((symbol-function 'swiper--candidates)
(lambda ()
(cl-remove-if-not (lambda (x) (string-match-p pattern x))
(funcall original-swiper--candidates)))))
(let ((candidates (swiper--candidates)))
(swiper--init)
(setq swiper-invocation-face
(plist-get (text-properties-at (point)) 'face))
(let ((preselect
(save-excursion
(search-forward-regexp pattern nil t)
(let* ((current-line-value (current-line))
(candidate-line-numbers (mapcar (lambda (x) (cadr (text-properties-at 0 x)))
candidates))
(preselect-line-num (cl-find-if (lambda (x) (<= current-line-value x))
candidate-line-numbers)))
(- (length candidate-line-numbers)
(length (member preselect-line-num candidate-line-numbers))))))
(minibuffer-allow-text-properties t)
res)
(unwind-protect
(and
(setq res
(ivy-read
"Swiper: "
candidates
:initial-input initial-input
:keymap swiper-map
:preselect preselect
:require-match t
:action #'swiper--action
:re-builder #'swiper--re-builder
:history 'swiper-history
:extra-props (list :fname (buffer-file-name))
:caller 'swiper))
(point))
(unless (or res swiper-stay-on-quit)
(goto-char swiper--opoint))
(isearch-clean-overlays)
(unless (or res (string= ivy-text ""))
(cl-pushnew ivy-text swiper-history))
(setq swiper--current-window-start nil)
(when swiper--reveal-mode
(reveal-mode 1))))))))

How to search for a complete org headline that was saved as a variable

The function (org-heading-components) and (org-element-property) produce integers for the number of stars and also for the priority. I'd like to store the entire headline as a variable and then use re-search-forward (or a similar function) to go back to that heading, but I foresee the problem that will occur when it cannot find an integer. I need to store the whole heading as a variable, because I often have todo entries with duplicate titles but the other components are diferent.
For example, the following todo:
** Active [#A] Ask the geniuses on stackoverflow how to do this. :lawlist:
when evaluated with (org-heading-components) looks like this:
(2 2 "Active" 65 "Ask the geniuses on stackoverflow how to do this." ":lawlist:")
So, when storing that as a variable and later using re-search-forward there will be problems because 2 2 is not the same as **, and 65 is not the same as [#A].
(defun lawlist ()
(interactive)
(let* (
(beg (point))
(complete-heading (org-heading-components) ))
* * *
(goto-char (point-min))
(re-search-forward complete-heading nil t) ))
You should be able to convert the output as follows:
The first # is the current level (# of stars)
The second number is the reduced headline level, applicable if org-odd-levels-only is set, but this is not regarding output.
Todo keyword
Priority character (65 is ASCII code for A)
Headline text
Tags or nil
The following will return the headline string as shown in the buffer. It will not work with re-search-forward but will work with search-forward (It does not escape any characters).
(defun zin/search-test ()
(interactive)
(let ((head (org-element-interpret-data (org-element-at-point))))
(message "%s" (format "%s" (car (split-string head "\n"))))))
This does not set it to any variable, you'll have to wrap it in an appropriate function that will set your desired variable. Then use (search-forward <var> nil t) to match it, without it erroring out if it cannot find it.
There's a brilliant part of org that might suit you: org-id-copy and
org-id-goto. It works with precision across buffers and sessions:
org-id-copy produces a string. You can feed that string to
org-id-goto which will take you to that heading. Even if you've
closed the original buffer. Even if you've restarted Emacs.
EDIT (December 15, 2013):  Updated solution based upon the variable org-heading-regexp (defined within org.el) and a modification thereof to include (if it exists) a second line containing a deadline - i.e., lawlist-org-heading-regexp. The revision also includes a nifty function regexp-quote that was just taught to me by #Drew over on superuser: https://superuser.com/questions/688781/how-to-highlight-string-and-unhighlight-string-in-buffer-make-overlay?noredirect=1#comment874515_688781  (buffer-substring-no-properties beg end) is used to set the string as a variable.
EDIT (December 17, 2013):   Added isearch-highlight and isearch-dehighlight, and commented out highlight-regexp and unhighlight-regexp. When moving the point around with more complex functions, highlight-regexp does not reliably highlight the entire string -- this may be because the screen has not refreshed, or it may also be caused by other factors -- e.g., hl-line-mode, etc.) -- placing various sit-for 0 did not fix the issue with highlight-regexp -- isearch-highlight works better.
EDIT (January 6, 2014):  See also this related thread for a complete regexp to match any element of the entire todo from stars through to the end of the notes:  https://stackoverflow.com/a/20960301/2112489
(require 'org)
(defvar lawlist-org-heading-regexp
"^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*\\(\n.*DEADLINE.*$\\)"
"Match headline, plus second line with a deadline.")
(defun example ()
(interactive)
(switch-to-buffer (get-buffer-create "foo"))
(org-mode)
(insert "* Example\n\n")
(insert "** Active [#A] This is an active todo. :lawlist:\n")
(insert " DEADLINE: <2013-12-15 Sun 08:00> SCHEDULED: <2013-12-15 Sun>\n\n")
(insert "** Next-Action [#B] This is an inactive todo. :lawlist:\n")
(insert " DEADLINE: <2013-12-16 Mon 08:00> SCHEDULED: <2013-12-16 Mon>")
(goto-char (point-min))
(sit-for 2)
(re-search-forward (regexp-quote "** Active [#A] "))
(sit-for 2)
(let ((init-pos (point)))
(org-back-to-heading t)
(let* (
lawlist-item-whole
lawlist-item-partial
(beg (point)))
(if (and
(looking-at org-heading-regexp)
(and (looking-at lawlist-org-heading-regexp) (match-string 3)))
(re-search-forward lawlist-org-heading-regexp nil t)
(re-search-forward org-heading-regexp nil t))
(let ((end (point)))
(setq lawlist-item-whole (buffer-substring-no-properties beg end))
(setq lawlist-item-partial (buffer-substring-no-properties beg init-pos))
(re-search-backward (regexp-quote lawlist-item-whole) nil t)
;; (highlight-regexp (regexp-quote lawlist-item-whole))
(isearch-highlight beg end)
(sit-for 2)
;; (unhighlight-regexp (regexp-quote lawlist-item-whole))
(isearch-dehighlight)
(re-search-forward (regexp-quote lawlist-item-partial) nil t)
(sit-for 2)
(kill-buffer "foo")))))
EDIT (October 27, 2013):  Prior solution that is being preserved temporarily as a historical part of the evolution process towards a final answer. However, it is no longer a preferred method.
(defun lawlist-org-heading-components ()
(org-back-to-heading t)
(if (let (case-fold-search) (looking-at org-complex-heading-regexp))
(concat
(cond
((equal (org-match-string-no-properties 1) "**")
"^[*][*]")
((equal (org-match-string-no-properties 1) "*")
"^[*]"))
(cond
((and (match-end 2) (aref (match-string 2) 1))
(concat " " (org-match-string-no-properties 2))))
(cond
((and (match-end 3) (aref (match-string 3) 2))
(concat " \\" (org-match-string-no-properties 3))))
(cond
((and (match-end 4) (aref (match-string 4) 3))
(concat " " (org-match-string-no-properties 4))))
(cond
((and (match-end 5) (aref (match-string 5) 4))
(concat " " (org-match-string-no-properties 5)))))))

Subsequently running the same function, yielding different results

I feel a bit silly for asking this question, but I feel like my code is as inefficient as it can be. I think I do not have the logic going on too well here.
Basically, I would like to have some different things happen on subsequently running the same commands.
My idea was to have a (cond ), in which for each case I have a test whether the command used before is the same AND the value of a variable which is set according to how many times it was pressed.
I also feel like I am not getting the title/tags correctly in this case, so feel free to edit.
((and (eq last-repeatable-command 'thecommand)
(= varcounter 1))
(message "second time called")
(setq varcounter 2))
When it is pressed again, the next clause would fire.
While the code below works, I believe this could be done way more efficiently, and I hope someone can give directions on how to approach this problem.
Long code example:
(defun incremental-insert-o ()
(interactive)
; init if not bound
(when (not (boundp 'iivar)) (setq iivar 0))
(cond
((and (eq last-repeatable-command 'incremental-insert-o)
(= iivar 1))
(insert "o o ")
(setq iivar 2))
((and (eq last-repeatable-command 'incremental-insert-o)
(= iivar 2))
(insert "o o o ")
(setq iivar 3))
((and (eq last-repeatable-command 'incremental-insert-o)
(= iivar 3))
(insert "o o o "))
(t
(insert "o ")
(setq iivar 1)))
)
(global-set-key [f8] 'incremental-insert-o)
Now, you're asking for more efficient code. There are a few things you could mean by this. You could mean that you want code that executes faster. How slow is the code now? When I run it on my Emacs, it's instant. Given that this code, by definition, is called from a buttonpress, it doesn't have to be super fast. Your code is more than fast enough for its use case, so I wouldn't worry about making it any faster. It also doesn't use memory: if you call it n times, it'll still only use enough memory to store one integer: this algorithm is O(1). Sounds good to me.
You could also mean "write this in fewer lines". This will also make the code less error-prone, and easier to understand. That's certainly a reasonable goal. Your code isn't awful to begin with, so it's not a necessity, but nor is it a bad idea. There are a few modifications we could make to your function. You could drop the entire third clause of your cond, and let the (= iivar 2) case be the final one, eliminating the need to set iivar to 3 there. Well, that's better already.
But wait, the function calls (eq last-repeatable-command 'incremental-insert-o) up to three times! That's a lot. Let me try to rewrite it! First, let's start with a base function definition, with an interactive call, as you have:
(defun incremental-insert-o ()
(interactive))
Now, I'm going to restructure things from your code. First, let's see if we can keep track of iivar correctly. I'm going to rename that variable to incremental-insert-o-consecutive, for readability, and because Emacs Lisp has a single namespace, so anything else using a variable named iivar will read and write to the same place your code's looking at:
(defun incremental-insert-o ()
(interactive)
(if (eq last-repeatable-command 'incremental-insert-o)
(setq incremental-insert-o-consecutive
(1+ incremental-insert-o-consecutive))
(setq incremental-insert-o-consecutive
1)))
Is that working? I'll bind it to [F8] as you did: (global-set-key [f8] 'incremental-insert-o). Now, hit [F8] to run it, but it doesn't tell you what the return value is. Let's change the function slightly to test it:
(defun incremental-insert-o ()
(interactive)
(if (eq last-repeatable-command 'incremental-insert-o)
(setq incremental-insert-o-consecutive
(1+ incremental-insert-o-consecutive))
(setq incremental-insert-o-consecutive
1))
(message "incremental-insert-o-consecutive is currently %s" incremental-insert-o-consecutive))
Hit [F8] a few times to make sure it works, and it does! It starts at 1, increases by 1 each consecutive time it's called, and resets when you do something else. Now, we just need to print out the right message. What do we want to print? Well, the first time you call the function, print out one "o ", then the second time, print out "o o ", then the third and all other times, print "o o o ". Note that printing the second string is just printing the first string twice, and the third string is printing the first string three times:
(defun incremental-insert-o ()
(interactive)
(if (eq last-repeatable-command 'incremental-insert-o)
(setq incremental-insert-o-consecutive
(1+ incremental-insert-o-consecutive))
(setq incremental-insert-o-consecutive
1))
(dotimes (i incremental-insert-o-consecutive)
(insert "o ")))
This is almost right! It does the right thing for times 1 through 3, but doesn't cap off at inserting "o o o "; it goes on to print "o o o o ", etc. So we just need to cap off the limit of repeats at 3:
(defun incremental-insert-o ()
(interactive)
(if (eq last-repeatable-command 'incremental-insert-o)
(setq incremental-insert-o-consecutive
(1+ incremental-insert-o-consecutive))
(setq incremental-insert-o-consecutive
1))
(dotimes (i (min incremental-insert-o-consecutive
3))
(insert "o ")))
Now, this seems to do exactly what you want. Let's look at the changes from the original function. This counts the number of repeats beyond 3. But the output behavior is the same, so I don't think this matters, and it seems nicer to keep the actual count of repeats. It will break if you ever overflow the integer, but that seems unlikely. Emacs guarantees at least 536870911 as MAXINT. So let's call that a day. We did get the code shorter, and have no repeated parts. I think that makes it more readable.
Here's something I could think of, however, take it with a grain of salt, because it may be overly complex, and you don't want to bring this much complexity into what you do:
(defstruct command-state
action next-state)
(defmacro define-action-states (name condition &rest actions)
(labels ((%make-command-state
(action name)
`(make-command-state :action (lambda () ,action))))
`(let ((head ,(%make-command-state (car actions) name)))
(defvar ,name nil)
(setq ,name head)
,#(loop for action in (cdr actions)
collect
`(setf (command-state-next-state ,name)
,(%make-command-state action name)
,name (command-state-next-state ,name)))
(setf (command-state-next-state ,name) head
,name head)
(defun ,(intern (concat (symbol-name name) "-command")) ()
(when ,condition
(unwind-protect
(funcall (command-state-action ,name))
(setq ,name (command-state-next-state ,name))))))))
(define-action-states print-names (= 1 1)
(message "first state")
(message "second state")
(message "third state")
(message "fourth state"))
(print-names-command)
;; will print messages looping through them,
;; each time you call it
I've made it to use a struct, so that you could add more conditions, independent of the state itself, for example, but mostly so the names would be more self-explanatory.
Also, probably, that's not the place you should really care about efficiency - so far your fingers cannot outrun the eLisp interpreter, it's all good ;)
Here's something I did to your code to possibly improve it a bit (now the worst case scenario will only check 5 conditions instead of 6 :)
(defun smart-killer ()
(interactive)
(let* ((properties (symbol-plist 'smart-killer))
(counter (plist-get properties :counter)))
(if (region-active-p)
(kill-region (region-beginning) (region-end))
(if (eq last-repeatable-command 'smart-killer)
(if (> counter 3)
(message "Kill ring is already filled with paragraph.")
(if (> counter 2)
(progn
(yank)
(kill-new "")
(mark-paragraph -1)
(kill-region (region-beginning) (region-end)))
(if (> counter 1)
(kill-region (point) (line-beginning-position))
(kill-line))))
(when (not (looking-at "\\<\\|\\>")) (backward-word)) ; begin/end of word
(kill-word 1))
(plist-put properties :counter (mod (1+ counter) 5)))))
(put 'smart-killer :counter 0)
This is what I came up with in the end:
(defun smart-killer ()
(interactive)
(cond
; [1] If region active, kill region
((region-active-p)
(kill-region (region-beginning) (region-end)))
; [2] If this command was last called, check how many times before it ran
((eq last-repeatable-command 'smart-killer)
(cond
; [2a]
((= sm-killer 1)
(kill-line))
; [2b]
((= sm-killer 2)
(kill-region (point) (line-beginning-position)))
; [2c]
((= sm-killer 3)
(yank)
(kill-new "")
(mark-paragraph -1)
(kill-region (region-beginning) (region-end)))
; [2d]
((= sm-killer 4)
(message "Kill ring is already filled with paragraph.")))
(incf sm-killer))
; [3]
(t
(when (not (looking-at "\\<\\|\\>")) (backward-word)) ; begin/end of word
(kill-word 1)
(setq sm-killer 1)))
)

How do I get the region (selection) programmatically in Emacs Lisp?

I need to access the selection in Emacs buffer.
I have found this article How do I access the contents of the current region in Emacs Lisp?
and it helps me a lot.
But there is a problem. The first time I select (highlight) a region, it works okay, but when I press C-g, and move cursor normally to another place without highlighting any chars, I got a string from last mark to the current point while I expect an empty one.
Actually I need to implement a function which will return the current selection (highlighted) as a string, or empty string if nothing is highlighted. The following code may express me more clearly.
(defun get-search-term ()
(interactive)
(let (
(selection (buffer-substring-no-properties (region-beginning) (region-end))))
(if (= (length selection) 0)
(message "empty string")
(message selection))))
Any suggestions? Thanks a lot!
"r" specification of interactive is dumb. You're seeing why.
(defun get-search-term (beg end)
"message region or \"empty string\" if none highlighted"
(interactive (if (use-region-p)
(list (region-beginning) (region-end))
(list (point-min) (point-min))))
(let ((selection (buffer-substring-no-properties beg end)))
(if (= (length selection) 0)
(message "empty string")
(message selection))))
I don't mean "dumb" as in stupid and not useful; just that it doesn't care
about whether the mark is active or not. I think it predates
transient-mark-mode.
EDIT: Using (point-min) twice above makes the code harder to understand
when re-reading. Here is a better implementation:
(defun get-search-term (beg end)
"message region or \"empty string\" if none highlighted"
(interactive (if (use-region-p)
(list (region-beginning) (region-end))
(list nil nil)))
(message "%s" (if (and beg end)
(buffer-substring-no-properties beg end)
"empty string")))
Check variable mark-active eg. C-h v mark-active
==> mark-active is a variable defined in `C source code'.
Its value is nil
Local in buffer Apropos; global value is nil
Automatically becomes buffer-local when set in any fashion.
Documentation:
Non-nil means the mark and region are currently active in this buffer.
(defun get-search-term ()
(interactive)
(if mark-active
(let (
(selection (buffer-substring-no-properties (region-beginning) (region-end))))
(if (= (length selection) 0)
(message "empty string")
(message selection))
)
(error "mark not active"))
)

How to define a function which repeats itself when passed an argument

Is there an easy way to define a function which repeats itself when passed an argument?
For example, I've defined the following function
(defun swap-sign ()
(interactive)
(search-forward-regexp "[+-]")
(if (equal (match-string 0) "-")
(replace-match "+")
(replace-match "-"))
)
I'd like C-u swap-sign to call swap-sign four times.
I've tried
(defun swap-sign (&optional num)
(interactive)
(let ((counter 0)
(num (if num (string-to-number num) 0)))
(while (<= counter num)
(search-forward-regexp "[+-]")
(if (equal (match-string 0) "-")
(replace-match "+")
(replace-match "-"))
(setq counter (1+ counter)))))
but C-u swap-sign still only runs swap-sign (or perhaps more precisely, the body of the while-loop) once. I'm guessing it is because if num is not the right way to test if num is an empty string.
Am I on the right track, or is there a better/easier way to extend swap-sign?
(defun swap-sign (arg)
(interactive "p")
(dotimes (i arg)
(search-forward-regexp "[+-]")
(if (equal (match-string 0) "-")
(replace-match "+")
(replace-match "-"))))
See the documentation of the interactive special form for more details:
C-h finteractiveRET.
You need to tell emacs to expect, and pass the parameter in, by adding a "p" as the parameter specification for interactive (M-x apropos interactive to get the documentation). Here I've made the minimal change to your code to get it to work - note, however, that you don't need the let/while to do the iteration, and the arg doesn't need to be optional.
(defun swap-sign (&optional num)
(interactive "p")
(let ((counter 1))
(while (<= counter num)
(search-forward-regexp "[+-]")
(if (equal (match-string 0) "-")
(replace-match "+")
(replace-match "-"))
(setq counter (1+ counter)))))
Note that you don't need to convert the parameter from a string - using "p" tells emacs to do this for you.