How do I use astyle within Emacs? - emacs

I am using windows emacs with specifications below.
GNU Emacs 23.0.91.1 (i386-mingw-nt5.1.2600) of 2009-02-26
I want to be able to run astyle so it can reformat the code by using a key command or menu. What is some other equivalent in emacs?

Something like this might do:
(defun astyle-this-buffer (pmin pmax)
(interactive "r")
(shell-command-on-region pmin pmax
"astyle" ;; add options here...
(current-buffer) t
(get-buffer-create "*Astyle Errors*") t))
This will run the "astyle" command on the selected region.
Or, you could simply use emacs' built-in code formatting by typing something like
C-x h C-M-\
(I.e. select the whole buffer and run indent-region)

Related

emacs terminal mode: how to copy and paste efficiently

I'm having a hard time making this emacs -nw work effectively under the terminal mode (emacs -nw).
Some setup information:
The working server is connected via SSH, and emacs is running on the server. Usually I'm connecting using SSH and "emacs -nw" to work on my files.
The emacs config is picked up from: https://hugoheden.wordpress.com/2009/03/08/copypaste-with-emacs-in-terminal/
;; make mouse selection to be emacs region marking
(require 'mouse)
(xterm-mouse-mode t)
(defun track-mouse (e))
(setq mouse-sel-mode t)
;; enable clipboard in emacs
(setq x-select-enable-clipboard t)
;; enable copy/paste between emacs and other apps (terminal version of emacs)
(unless window-system
(when (getenv "DISPLAY")
;; Callback for when user cuts
(defun xsel-cut-function (text &optional push)
;; Insert text to temp-buffer, and "send" content to xsel stdin
(with-temp-buffer
(insert text)
;; I prefer using the "clipboard" selection (the one the
;; typically is used by c-c/c-v) before the primary selection
;; (that uses mouse-select/middle-button-click)
(call-process-region (point-min) (point-max) "xsel" nil 0 nil "--clipboard" "--input")))
;; Call back for when user pastes
(defun xsel-paste-function()
;; Find out what is current selection by xsel. If it is different
;; from the top of the kill-ring (car kill-ring), then return
;; it. Else, nil is returned, so whatever is in the top of the
;; kill-ring will be used.
(let ((xsel-output (shell-command-to-string "xsel --clipboard --output")))
(unless (string= (car kill-ring) xsel-output)
xsel-output )))
;; Attach callbacks to hooks
(setq interprogram-cut-function 'xsel-cut-function)
(setq interprogram-paste-function 'xsel-paste-function)
;; Idea from
;; http://shreevatsa.wordpress.com/2006/10/22/emacs-copypaste-and-x/
;; http://www.mail-archive.com/help-gnu-emacs#gnu.org/msg03577.html
))
The reason to have:
(require 'mouse)
(xterm-mouse-mode t)
(defun track-mouse (e))
(setq mouse-sel-mode t)
is to enable mouse selection over text such that the text region is highlighted just as "C-x SPC" marking the region. Then I can use "M-x w" to copy and "C-x y" to paste text within emacs and between emacs and other apps.
All look perfect except that any operations related to X are REALLY SLOW! My connection to the remote server is smooth -- the latency is usually under 100ms. But to kill one line of text using "C-x k", it takes ~5 seconds! To paste it, it takes another 5 seconds!
When copy/paste is frequent sometimes, this becomes really annoying. I think this is related to the X sever messaging, but not sure if there is good way to fix this.
Any ideas?
Thanks!
This is not an ideal solution per se, but i figured out a way that I feel better than the previous one.
The idea is to get rid of X which causes heavy latency issues, i.e. keep only the following:
;; enable clipboard in emacs
(setq x-select-enable-clipboard t)
The results are:
copy/paste within Emacs is straightforward and fast.
copy from other apps to Emacs: Ctrl+Shift+v
copy from Emacs to other apps: mouse selection is now on X Selection, so right-click and copy shall copy the text into the Selection. Note that 'M-w" now won't copy anything into Selection or system clipboard.
This is again a compromise rather than a solution, but considering the fact that i copy/paste more often than inter-app operations, this is acceptable at the moment.
Still looking forward to a good solution!
You can accomplish this by using a terminal escape code!
There is a unique category of terminal escape codes called "Operating System Controls" (OSC) and one of these sequences (\033]52) is meant for interacting with the system clipboard. The great thing is that your terminal doesn't care where the code came from so it will work in remote sessions as well.
Most terminal emulators support it (iTerm2, OS X Terminal, and I think all Linux terminals besides GNOME). You can test if your terminal supports this sequence by simply running:
$ printf "\033]52;c;$(printf "Hello, world" | base64)\a"
Then paste from your system clipboard. If it pastes "Hello, world" then your terminal supports it!
I have this function in my init.el so when I call yank-to-clipboard Emacs will yank the value from my kill ring into the system clipboard:
(defun yank-to-clipboard ()
"Use ANSI OSC 52 escape sequence to attempt clipboard copy"
(interactive)
(send-string-to-terminal
(format "\033]52;c;%s\a"
(base64-encode-string
(encode-coding-string
(substring-no-properties
(nth 0 kill-ring)) 'utf-8) t))))
As I type this, I stumbled upon an almost-identical script supported by Chromium community: https://chromium.googlesource.com/apps/libapps/+/master/hterm/etc/osc52.el
For those running Emacs inside Tmux:
Tmux consumes the sequence, so you'll need to pipe the sequence to the Tmux active tty for this to work. I have a solution in my blog post here: https://justinchips.medium.com/have-vim-emacs-tmux-use-system-clipboard-4c9d901eef40
To extend on #justinokamoto's answer for use in tmux, it works great and is truly amazing. I haven't debugged it with e.g. tramp or other fancy emacs settings but to get it to work
Follow https://sunaku.github.io/tmux-yank-osc52.html great instructions, modifying your tmux.conf and ~/bin/yank
Make sure terminal access to your clipboard is enabled on your terminal
Then to pull into emacs you can use a function like:
(Caveat emptor, I am very new to elisp. This writes to a temporary file in /tmp/yank)
(defun custom-terminal-yank (&rest args)
(message "-> CLIP")
;; FOR EVIL MODE: UNCOMMENT SO FIRST YANKS TO KILL RING
;; need to yank first, with all those args
;; ;; https://emacs.stackexchange.com/questions/19215/how-to-write-a-transparent-pass-through-function-wrapper
;; (interactive (advice-eval-interactive-spec
;; (cadr (interactive-form #'evil-yank))))
;; (apply #'evil-yank args)
;; https://stackoverflow.com/questions/27764059/emacs-terminal-mode-how-to-copy-and-paste-efficiently
;; https://sunaku.github.io/tmux-yank-osc52.html
(f-write-text (nth 0 kill-ring) 'utf-8 "/tmp/yank")
(send-string-to-terminal (shell-command-to-string "~/bin/yank /tmp/yank"))
)
If anyone else uses evil mode as well (just to make things complicated) you can uncomment those lines and use something like
(define-key evil-visual-state-map "Y" 'jonah-terminal-yank)
So that normal "y" is for normal yanking in visual mode, but "Y" is for cross-clipboard yanking

Opening a window into a specified buffer

How can I open a new window (for example using C-x 3) into a new buffer, rather than a mirrored buffer that just echoes what I type.
So for example, let's say I'm messing around with python and I want to run the script in the shell. As it is currently I do this: C-x 3, M-x shell and then start it up and running. I'd rather just C-x 3 and it automatically opens into shell. I'm really new to Emacs so I don't know where to look for this.
It sounds to me like this, or something similar, is what you are looking for:
(defun pop-to-buff-at-right (buffer)
"Pop to BUFFER at the right of the current window."
(interactive "B")
(pop-to-buffer buffer '(display-buffer-in-side-window
(side . right)
(inhibit-same-window . t))))
You do not want to just split the window, which is specifically about showing the same buffer twice. You want to switch to another buffer, but you want it to be displayed to the right of the current window.
In emacs it is easy to define custom commands and bind it to keys. For instance, if you add this to your init file:
(defun open-shell-at-left ()
(interactive) ;; Tell emacs this function can be called interactively
(split-window-right) ;; Just what C-x 3 does
(shell)) ;; Just what M-x shell does
(global-set-key (kbd "C-c 3") 'open-shell-at-left)
You will have what you want when you type C-c 3. In general, you can find documentation about what a key binding does by typing C-h k and the keybinding. From that point, it is easy to chain existing commands into new ones.

Execute a particular command on multiple emacs buffers

Is there a way to execute emacs command on multiple buffers without having to selecting them individually and executing it on each individual buffer.
I usually open multiple files matching a particular regex, e.g. ~/*.py and wish to enable a particular mode, say hs-minor-mode or glasses-mode on each, or say execute C-c # C-M-h on each. Currently I have to select each one of them and do it individually. So is there a hack or a loop to automate the task.
Lets say I mark the buffers from the buffer-list and then run the command for all those marked.
I tried this but after executing the commands in eval-expression I completely lost access to my minibuffer, meaning whenever I typed M-x the minibuffer returned this
unable to access the minibuffer emacs error "Process Menu Mode doesn't support Hideshow Minor Mode"
and I was forced to actually kill the entire emacs process because the C-x C-s wasn't working neither was the End Task.
PS: I have no experience in elisp
You can use ibuffer mode for this (It is part of the default Emacs distribution).
(global-set-key "\C-x\C-b" 'ibuffer) ;; make ibuffer the default
In *Ibuffer* you can mark the required buffers with m and then
execute a form in each with E.
Generally, ibuffer is a lot more flexible then the usual buffer list and I think ibuffer should really be the default buffer-list in Emacs.
If you do this often, you might want to switch those particular modes on every time you enter python mode by attaching them to the mode-hook:
(add-hook 'python-mode-hook 'hs-minor-mode)
(add-hook 'python-mode-hook 'glasses-mode)
I didn't know ibuffer had that feature!
Anyway, for those who are more familiar with dired, here is a command that do the same. Select the files in dired with m or any other more powerful method. Then do, M-xdired-do-command and write a form or a command just as in M-x.
(defun dired-do-command (command)
"Run COMMAND on marked files. Any files not already open will be opened.
After this command has been run, any buffers it's modified will remain
open and unsaved."
(interactive
(list
(let ((print-level nil)
(minibuffer-history-position 0)
(minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
(unwind-protect
(read-from-minibuffer
"Command: " (prin1-to-string (nth 0 command-history))
read-expression-map t
(cons 'command-history 0))
;; If command was added to command-history as a
;; string, get rid of that. We want only
;; evaluable expressions there.
(if (stringp (car command-history))
(setq command-history (cdr command-history)))))))
(dolist (filename (dired-get-marked-files))
(with-current-buffer (find-file-noselect filename)
(if (symbolp command)
(call-interactively command)
(eval command)))))

Auto-formatting a source file in emacs

How do I apply a set of formatting rules to an existing source file in emacs?
Specifically I have an assembly (*.s) file, but I would like a generic command for all types of files.
I am trying to use M-x c-set-style with gnu style, but I am getting an error:
Buffer *.s is not a CC Mode buffer (c-set-style)
Open the file and then indent it by indenting the entire region:
M-x find-file /path/to/file RET
C-x h (M-x mark-whole-buffer)
C-M-\ (M-x indent-region)
Now, it looks like you're trying to apply C indentation to a buffer that's not in C mode. To get it into C mode
M-x c-mode
Or c++-mode, or whatever mode you want. But, since it's assembler code, you probably want assembler mode (which Emacs will do by default for .s files). In which case, the indentation command above (C-M-\ is also known as M-x indent-region) should work for you.
Note: the command sequence at the top can be rolled into a single command like this:
(defun indent-file (file)
"prompt for a file and indent it according to its major mode"
(interactive "fWhich file do you want to indent: ")
(find-file file)
;; uncomment the next line to force the buffer into a c-mode
;; (c-mode)
(indent-region (point-min) (point-max)))
And, if you want to learn how to associate major-modes with files based on extensions, check out the documentation for auto-mode-alist. To be fair, it's not necessarily extension based, just regular expressions matched against the filename.
Try M-x asm-mode. That will switch to assembler mode. Not sure how it will go with assembler embedded in the middle of a C file.
if you want indent current buffer
(defun iwb ()
"indent whole buffer"
(interactive)
(delete-trailing-whitespace)
(indent-region (point-min) (point-max) nil)
(untabify (point-min) (point-max)))
emacs will use the file name extension to identify the mode, you should add some assemble language mode style in your custom.el file
The major mode it's using for your .s files won't be cc-mode hence c-set-style makes no sense. However you can always manually enter cc-mode (M-x cc-mode) and then do the c-set-style you want. However as the C styles are keyed for C source code and not assembler this is almost certainly not what you want to do.
if you want to indent from the command line use :
emacs --batch <filenames.v> -f verilog-batch-indent

How to configure GNU Emacs to write UNIX or DOS formatted files by default?

I've had these functions in my .emacs.el file for years:
(defun dos2unix ()
"Convert a DOS formatted text buffer to UNIX format"
(interactive)
(set-buffer-file-coding-system 'undecided-unix nil))
(defun unix2dos ()
"Convert a UNIX formatted text buffer to DOS format"
(interactive)
(set-buffer-file-coding-system 'undecided-dos nil))
These functions allow me to easily switch between formats, but I'm not sure how to configure Emacs to write in one particular format by default regardless of which platform I'm using. As it is now, when I run on Windows, Emacs saves in Windows format; when I run in UNIX/Linux, Emacs saves in UNIX format.
I'd like to instruct Emacs to write in UNIX format regardless of the platform on which I'm running. How do I do this?
Should I perhaps add some text mode hook that calls one of these functions? For example, if I'm on Windows, then call dos2unix when I find a text file?
I've got a bunch of these in my .emacs:
(setq-default buffer-file-coding-system 'utf-8-unix)
(setq-default default-buffer-file-coding-system 'utf-8-unix)
(set-default-coding-systems 'utf-8-unix)
(prefer-coding-system 'utf-8-unix)
I don't know which is right, I am just superstitious.
I up-voted question and answer, but spent a couple minutes possibly improving on the info, so I'll add it.
First, I checked documentation on each variable and function in user181548's answer, by (first cutting and pasting into Emacs, then) putting cursor over each, and typing C-h v RET and C-h f RET respectively.
This suggested that I might only need
(prefer-coding-system 'utf-8-unix)
Experimenting with the other lines didn't seem to change pre-existing buffer encodings (typing C-h C RET RET to check (describe-coding-system) and g each time to refresh), so I omitted the other lines and made a key-binding to quickly change any old files that were still DOS, that is,
(defun set-bfr-to-8-unx ()
(interactive)
(set-buffer-file-coding-system
'utf-8-unix)
)
(global-set-key (kbd "C-c u")
'set-bfr-to-8-unx
)
For the curious, to discover the 3rd and 4th line of above function, (set-buffer-file-coding-system 'utf-8-unix), I used C-x RET f RET to manually change the current buffer's encoding, then M-x command-history RET to see how those keys translate to code.
Now maybe my git commit's will stop whining about CRs.