Auto-formatting a source file in emacs - 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

Related

How to enable auto-complete in Emacs Org-babel?

I would like to enable auto-complete for Babel code blocks in org-mode:
#+begin_src emacs-lisp
(setq ) <--- language-aware auto-completion here
#+end_src
What do I need to add to my .emacs file in order to configure auto-complete to do this?
Late to the party but today the default (and recommended way without other hacks) is to switch to the dedicated elisp buffer for that "hunk" using 'org-edit-special which today is mapped to
C-c- '
Hit the same to return to your org file editing.
You can switch to a dedicated session with the right mode and auto-completion
simply with C-c C-v z when you are in a code block.
C-c C-v z or C-c C-v org-babel-switch-to-session-with-code
Check the org-documentation 14.11 Key bindings and useful functions for more information.
The most robust (and entirely not org-mode specific) way to do this involves an indirect buffer. Here's a blog post that explains indirect buffers in depth. Basically an indirect buffer mirrors the contents of a section of another buffer.
(defun narrow-to-region-indirect (start end)
"Restrict editing in this buffer to the current region, indirectly."
(interactive "r")
(deactivate-mark)
(let ((buf (clone-indirect-buffer nil nil)))
(with-current-buffer buf
(narrow-to-region start end))
(switch-to-buffer buf)))
At this point, you will have a new buffer that contains the region you previously made. You can enable a major mode for that buffer and edit to your satisfaction--the changes you make are (like any good mirror should do) reflected in the original document.

How can I reload .emacs after changing it?

How can I get Emacs to reload all my definitions that I have updated in .emacs without restarting Emacs?
You can use the command load-file (M-x load-file, and then press Return twice to accept the default filename, which is the current file being edited).
You can also just move the point to the end of any sexp and press C-x, C-e to execute just that sexp. Usually it's not necessary to reload the whole file if you're just changing a line or two.
There is the very convenient
M-x eval-buffer
It immediately evaluates all code in the buffer. It's the quickest method if your .emacs file is idempotent.
You can usually just re-evaluate the changed region. Mark the region of ~/.emacs that you've changed, and then use M-x eval-region RET. This is often safer than re-evaluating the entire file since it's easy to write a .emacs file that doesn't work quite right after being loaded twice.
If you've got your .emacs file open in the currently active buffer:
M-x eval-buffer
Solution
M-: (load user-init-file)
Notes
you type it in Eval: prompt (including the parentheses)
user-init-file is a variable holding the ~/.emacs value (pointing to the configuration file path) by default
(load) is shorter, older, and non-interactive version of (load-file); it is not an Emacs command (to be typed in M-x), but a mere Elisp function
Conclusion
M-: > M-x
M-x load-file
~/.emacs
Others already answered your question as stated, but I find that I usually want to execute the lines that I just wrote.
For that, Ctrl + Alt + X in the Elisp part works just fine.
The following should do it...
M-x load-file
I suggest that you don't do this, initially. Instead, start a new Emacs session and test whatever changes you made to see if they work correctly. The reason to do it this way is to avoid leaving you in a state where you have an inoperable .emacs file, which fails to load or fails to load cleanly. If you do all of your editing in the original session, and all of your testing in a new session, you'll always have something reliable to comment out offending code.
When you are finally happy with your changes, then go ahead and use one of the other answers to reload. My personal preference is to eval just the section you've added/changed, and to do that just highlight the region of added/changed code and call M-x eval-region. Doing that minimizes the code that's evaluated, minimizing any unintentional side-effects, as luapyad points out.
Keyboard shortcut:
(defun reload-init-file ()
(interactive)
(load-file user-init-file))
(global-set-key (kbd "C-c C-l") 'reload-init-file) ; Reload .emacs file
C-x C-e ;; current line
M-x eval-region ;; region
M-x eval-buffer ;; whole buffer
M-x load-file ~/.emacs.d/init.el
Define it in your init file and call by M-x reload-user-init-file
(defun reload-user-init-file()
(interactive)
(load-file user-init-file))
I'm currently on Ubuntu 15.04 (Vivid Vervet); I like to define a key for this.
[M-insert] translates to Alt + Ins on my keyboard.
Put this in your .emacs file:
(global-set-key [M-insert] '(lambda() (interactive) (load-file "~/.emacs")))
Besides commands like M-x eval-buffer or M-x load-file, you can restart a fresh Emacs instance from the command line:
emacs -q --load "init.el"
Usage example: Company backends in GNU Emacs
Here is a quick and easy way to quick test your config. You can also use C-x C-e at the end of specific lisp to execute certain function individually.
C-x C-e runs the command eval-last-sexp (found in global-map), which
is an interactive compiled Lisp function.
It is bound to C-x C-e.
(eval-last-sexp EVAL-LAST-SEXP-ARG-INTERNAL)
Evaluate sexp before point; print value in the echo area.
Interactively, with prefix argument, print output into current buffer.
Normally, this function truncates long output according to the value
of the variables ‘eval-expression-print-length’ and
‘eval-expression-print-level’. With a prefix argument of zero,
however, there is no such truncation. Such a prefix argument also
causes integers to be printed in several additional formats (octal,
hexadecimal, and character).
If ‘eval-expression-debug-on-error’ is non-nil, which is the default,
this command arranges for all errors to enter the debugger.
Although M-x eval-buffer will work, you may run into problems with toggles and other similar things. A better approach might be to "mark" or highlight what’s new in your .emacs file (or even scratch buffer if you're just messing around) and then M-x eval-region.
You can set a key binding for Emacs like this:
;; Reload Emacs configuration
(defun reload-init-file ()
(interactive)
(load-file "~/.emacs"))
(global-set-key (kbd "C-c r") 'reload-init-file)
If you happen to have a shell opened inside Emacs, you can also do:
. ~/.emacs
It may save a few key strokes.

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.

How do I use astyle within 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)

How can I apply a new Emacs C style to reformat all my source files?

I'd like to re-format all my source files using the Google formatting function for emacs: google-c-style.el (see here).
How can I apply this function to all my source files at once, so that they are all formatted and indented correctly according to the Google style?
There are several pieces to this:
you need to come up with EMACS functions to do all the reformatting you want. indent-region is a start, but you might also want to untabify or some other things.
you need to invoke them on each file, and since the indent functions work on ranges, you need a function that sets mark to cover the whole file: mark-whole-buffer.
you need to invoke EMACS on each file: this means invoking emacs with the --batch file.
There's a couple of nice blog posts on doing this here and here.
I have done this before by using a keyboard defined macro. I would load all of the files into emacs (something like find . -name "*.cpp" | xargs emacs) and then type the following keys. I've annotated each key combination with what it does.
C-x-( 'Begin recording macro
M-< 'Go to start of file
C-space 'Mark current location (now start of file)
M-> 'Go to end of file
M-x indent-region 'Indent entire file according to coding style
C-x C-s 'Save the current buffer
C-x C-k 'Close the current buffer
C-x-) 'End recording macro
Now you can run this on a buffer by typing C-x e. If you have loaded several files you can run something like C-u 100 C-x e to run this on 100 files. If this is more than the number of files, that is ok, you'll just get some "bell ring" or other error you can ignore once all the processing is complete.
I believe that this script does not do reformatting. Instead it's an example of how to build a custom "style" as described in: CC mode manual - Styles
CC-mode manual also says:
If you want to reformat old code, you're probably better off using some other tool instead, e.g. GNU indent, which has more powerful reformatting capabilities than CC Mode.
CC mode manual - Limitations-and-Known-Bugs
If you want to mark the source files in a dired buffer and then run a function to format each you can do something like this:
(defun clean-file(filename)
(your-function-goes-here))
(defun clean-each-dired-marked-file()
(interactive)
(for-each-dired-marked-file 'clean-file))
(defun for-each-dired-marked-file(fn)
"Do stuff for each marked file, only works in dired window"
(interactive)
(if (eq major-mode 'dired-mode)
(let ((filenames (dired-get-marked-files)))
(mapcar fn filenames))
(error (format "Not a Dired buffer \(%s\)" major-mode))))