How do you create (automatically inserted) LaTeX template with Emacs+AUCTeX? - templates

I use Emacs+AUCTex for writing LaTeX documents. I have specific needs so my typical preamble is quite long. Today, I have a .tex file with only this preamble (a template so) and I use C-x C-w to write a new file from this template. It isn't the best solution because my template localization could be far away from the new file.
So is there a way to call LaTeX templates in Emacs in another (shorter) way?
EDIT : auto-insert-mode offers a way to achieve what I want but it doesn't put automatically my template (LaTeX preamble) when I create a .tex file. I have to launch M-x auto-insert. How can I automatize this based on the file extension?

At the end of VirTeX-common-initialization (essentially) TeX-master-file is added to find-file-hooks. This is the source for the %%% Local Variables: %%% mode: latex %%% TeX-master: t %%% End: stuff. (Note, that VirTeX-common-initialization is the first thing in LaTeX-common-initialization which is called in TeX-latex-mode being an alias for latex-mode.)
To get ride of the automagically added comments you can remove the hook:
(add-hook 'TeX-mode-hook '(lambda ()
(remove-hook 'find-file-hooks (car find-file-hooks) 'local)))
That looks like a hack. But adding TeX-master-file is quite hard-coded without user-options. So, it seems to me that you have no other chance.
After that correction the auto-insert stuff works automagically.
(At least for me.)
But, I have replaced the entries in auto-insert-alist. Meaning, instead of
(define-auto-insert "\\.tex$" "my-latex-template.tex")
I have something like that:
(let ((el (assoc 'latex-mode auto-insert-alist)))
(if el
(setcdr el "/c/temp/autoinsert.tex")
(define-auto-insert "\\.tex$" "/c/temp/autoinsert.tex")))
Maybe, that is important, maybe not. I've got to get home now and I cannot further investigate that.

You're probably looking for auto-insert-mode. This is orthogonal to AUCTeX - for instance, I use it to insert a class-template for .java files.
Put the following in your .emacs file:
(auto-insert-mode)
;; *NOTE* Trailing slash important
(setq auto-insert-directory "/path/to/template/directory/")
(setq auto-insert-query nil)
(define-auto-insert "\\.tex$" "my-latex-template.tex")
Of course, you could make the regular expression used as the first argument to define-auto-insert more complex e.g. to insert different preambles depending on the working directory.
I adapted this code from an example from the EmacsWiki where you can also find additional information.

This is the simplest solution I can think of:
(defun insert-latex-template()
(when (= (point-max) (point-min))
(insert-file "/path/to/your/template/file")))
(add-hook 'latex-mode-hook 'insert-latex-template)

Related

emacs how to refresh buffer and preserve highlighting - especially for logs

I am often parsing log files, which I help visualize by highlighting specific char sequences via M-s h r + regex, aka the command highlight-regexp or hi-lock-face-buffer. Sometimes I will need to regenerate the log file, which is done via the C-x C-v or find-alternate-file command. Unfortunately, the regeneration also loses all of my highlighting.
TLDR
Is there a way to regenerate my buffer file while maintaining all of the highlighting?
Update
I am using text-mode, and the regexes vary widely depending on my task and the log file. I would like something that carries over all of my highlighting to the refreshed buffer. Does something already exist?
Answer:
Even better than maintaining highlights after a refresh, the selected answer uses an add-hook to create a highlighting scheme for a particular log. Additionally, each log can have different highlight schemes. The result is an automated highlighting scheme that matches a particular log file's name, with the ability to toggle the schemes of various highlights.
You can add-hook that:
(add-hook 'text-mode-hook
(lambda ()
(font-lock-add-keywords nil '(("^\\([^,]*\\)," 1 'font-lock-function-name-face)))))
What regexp you'd like to highlight? If You are using several regexps depending on the log, it might be possible to hook them all. Or you might program the condition: which regexp to hightlight:
(add-hook 'text-mode-hook
(lambda ()
(if (condition)
;; condition true:
(font-lock-add-keywords nil '((regexp1 1 'font-lock-function-name-face)))
;; condition false:
(font-lock-add-keywords nil '((regexp2 1 'font-lock-function-name-face)))
)
))
Also if you control the generation of logs you can generate the hightlight rules in the first line:
# -*- eval: (highlight-regexp REGEXP) -*-
(assuming # is the comment char in your log).
Edit:
Here's defun which toggles hightlighting for TestQueryLogic or invoking fork-join and testGudermann:
(defun testing-MapAppLog.txt ()
"Toggle highlighting `TestQueryLogic' or `invoking fork-join' and `testGudermann'."
(interactive)
(cond
((get this-command 'state)
(highlight-regexp "TestQueryLogic" font-lock-variable-name-face)
(highlight-regexp "invoking fork-join" font-lock-type-face)
(unhighlight-regexp "testGudermann")
(message "Highlighting: TestQueryLogic, invoking fork-join")
(put this-command 'state nil))
(t
(unhighlight-regexp "TestQueryLogic")
(unhighlight-regexp "invoking fork-join")
(highlight-regexp "testGudermann" font-lock-preprocessor-face)
(message "Highlighting: testGudermann")
(put this-command 'state t))))
So call it once to hightlight TestQueryLogic, invoking fork-join, call it again to hightlight testGudermann instead. You can bind to a key:
(define-key text-mode-map (kbd "M-s t") 'testing-MapAppLog.txt)
and press that once or twice depending on what you'd like to highlight.
Rather than C-x C-v which basically says "throw away current buffer and use thise other file instead" an has hence no hope of preserving transient info such as your highlighting patterns, you want to use revert-buffer, or maybe even auto-revert-mode or auto-revert-tail-mode.

Customized google-c-style.el

I am using google-c-style.el to indent my c++ programs.Functions in classes will be indented as below:
Which is not what I want, I'd like this one:
Here is my setting in .emacs:
(setq c-default-style "linux")
(setq c-basic-offset 4)
(require 'cc-mode)
(require 'google-c-style)
(add-hook 'c-mode-common-hook 'google-make-newline-indent)
It looks like you also need:
(add-hook 'c-mode-common-hook 'google-set-c-style)
Currently, even though you require google-c-style, it's not adding the style until that defun above is called. The docstring says it's meant to be added to the hook as well.
More generally, for indenting issues you need to know about c-offsets-alist
It allows you to customize how indentation is performed on different syntactic elements.
An easy way to figure out which element you need to modify is to go to the location (e.g. brace open of fun() in your example) and hit C-c C-s for c-show-syntactic-information
Rather than use this google-style script, personally I would derive from it or another c-style and override the values to suit my taste.
For instance, I notice you expect a c-basic-offset of 4, but google-style uses a c-basic-offset of 2, so you could derive from and override the Google style to replace c-basic-offset.
Check out: How to make Emacs put access level modifiers in their own indentation level in my C++ code? for an example.

How do I beautify lisp source code?

My code is a mess many long lines in this language like the following
(defn check-if-installed[x] (:exit(sh "sh" "-c" (str "command -v " x " >/dev/null 2>&1 || { echo >&2 \"\"; exit 1; }"))))
or
(def Open-Action (action :handler (fn [e] (choose-file :type :open :selection-mode :files-only :dir ListDir :success-fn (fn [fc file](setup-list file)))) :name "Open" :key "menu O" :tip "Open spelling list"))
which is terrible. I would like to format it like so
(if (= a something)
(if (= b otherthing)
(foo)))
How can I beautify the source code in a better way?
The real answer hinges on whether you're willing to insert the newlines yourself. Many systems
can indent the lines for you in an idiomatic way, once you've broken it up into lines.
If you don't want to insert them manually, Racket provides a "pretty-print" that does some of what you want:
#lang racket
(require racket/pretty)
(parameterize ([pretty-print-columns 20])
(pretty-print '(b aosentuh onethunoteh (nte huna) oehnatoe unathoe)))
==>
'(b
aosentuh
onethunoteh
(nte huna)
oehnatoe
unathoe)
... but I'd be the first to admit that inserting newlines in the right places is hard, because
the choice of line breaks has a lot to do with how you want people to read your code.
I use Clojure.pprint often for making generated code more palatable to humans.
it works well for reporting thought it is targeted at producing text. The formatting built into the clojure-mode emacs package produces very nicely formatted Clojure if you put the newlines in your self.
Now you can do it with Srefactor package.
Some demos:
Formatting whole buffer demo in Emacs Lisp (applicable in Common Lisp as well).
Transform between one line <--> Multiline demo
Available Commands:
srefactor-lisp-format-buffer: format whole buffer
srefactor-lisp-format-defun: format current defun cursor is in
srefactor-lisp-format-sexp: format the current sexp cursor is in.
srefactor-lisp-one-line: turn the current sexp of the same level into one line; with prefix argument, recursively turn all inner sexps into one line.
Scheme variants are not as polished as Emacs Lisp and Common Lisp yet but work for simple and small sexp. If there is any problem, please submit an issue report and I will be happy to fix it.

Emacs Brace and Bracket Highlighting?

When entering code Emacs transiently highlights the matching brace or bracket. With existing code however is there a way to ask it to highlight a matching brace or bracket if I highlight its twin?
I am often trying to do a sanity check when dealing with compiler errors and warnings. I do enter both braces usually when coding before inserting the code in between, but have on occasion unintentionally commented out one brace when commenting out code while debugging.
Any advice with dealing with brace and bracket matching with Emacs?
OS is mostly Linux/Unix, but I do use it also on OS X and Windows.
If you're dealing with a language that supports it, give ParEdit a serious look. If you're not using with a Lisp dialect, it's not nearly as useful though.
For general brace/bracket/paren highlighting, look into highlight-parentheses mode (which color codes multiple levels of braces whenever point is inside them). You can also turn on show-paren-mode through customizations (that is M-x customize-variable show-paren-mode); that one strongly highlights the brace/bracket/paren matching one at point (if the one at point doesn't match anything, you get a different color).
my .emacs currently contains (among other things)
(require 'highlight-parentheses)
(define-globalized-minor-mode global-highlight-parentheses-mode highlight-parentheses-mode
(lambda nil (highlight-parentheses-mode t)))
(global-highlight-parentheses-mode t)
as well as that show-paren-mode customization, which serves me well (of course, I also use paredit when lisping, but these are still marginally useful).
Apart from the answer straight from the manual or wiki, also have a look at autopair.
tried on emacs 26
(show-paren-mode 1)
(setq show-paren-style 'mixed)
enable showing parentheses
set the showing in such as highlit the braces char., or if either one invisible higlight what they enclose
for toggling the cursor position / point between both, put this script in .emacs
(defun swcbrace ()(interactive)
(if (looking-at "(")(forward-list)
(backward-char)
(cond
((looking-at ")")(forward-char)(backward-list))
((looking-at ".)")(forward-char 2)(backward-list))
)))
(global-set-key (kbd "<C-next>") 'swcbrace)
it works toggling by press Control-Pgdn
BTW, for the immediate question: M-x blink-matching-open will "re-blink" for an existing close paren, as if you had just inserted it. Another way to see the matching paren is to use M-C-b and M-C-f (which jump over matched pairs of parens), which are also very useful navigation commands.
I second ParEdit. it is very good atleast for lisp development.
FWIW I use this function often to go to matching paren (back and forth).
;; goto-matching-paren
;; -------------------
;; If point is sitting on a parenthetic character, jump to its match.
;; This matches the standard parenthesis highlighting for determining which
;; one it is sitting on.
;;
(defun goto-matching-paren ()
"If point is sitting on a parenthetic character, jump to its match."
(interactive)
(cond ((looking-at "\\s\(") (forward-list 1))
((progn
(backward-char 1)
(looking-at "\\s\)")) (forward-char 1) (backward-list 1))))
(define-key global-map [(control ?c) ?p] 'goto-matching-paren) ; Bind to C-c p
Declaimer: I am NOT the author of this function, copied from internet.
If you just want to check the balanced delimiters, be them parentheses, square brackets or curly braces, you can use backward-sexp (bound to CtrlAltB) and forward-sexp (bound to CtrlAltF) to skip backward and forward to the corresponding delimiter. These commands are very handy to navigate through source files, skipping structures and function definitions, without any buffer modifications.
You can set the below in your init.el:
(setq show-paren-delay 0)
(show-paren-mode 1)
to ensure matching parenthesis are highlighted.
Note that (setq show-paren-delay 0) needs to be set before (show-paren-mode 1) so that there's no delay in highlighting, as per the wiki.
If you want to do a quick check to see whether brackets in the current file are balanced:
M-x check-parens
Both options tested on Emacs 27.1

How do I bind a regular expression to a key combination in emacs?

For context, I am something of an emacs newbie. I haven't used it for very long, but have been using it more and more (I like it a lot). Also I'm comfortable with lisp, but not super familiar with elisp.
What I need to do is bind a regular expression to a keyboard combination because I use this particular regex so often.
What I've been doing:
M-C-s ^.*Table\(\(.*\n\)*?GO\)
Note, I used newline above, but I've found that for isearch-forward-regexp, you really need to replace the \n in the regular expression with the result of C-q Q-j. This inserts a literal newline (without ending the command) enabling me to put a newline into the expression and match across lines.
How can I bind this to a key combination?
I vaguely understand that I need to create an elisp function which executes isearch-forward-regexp with the expression, but I'm fuzzy on the details. I've searched google and found most documentation to be a tad confusing.
How can I bind a regular expression to a key combination in emacs?
Mike Stone had the best answer so far -- not exactly what I was looking for but it worked for what I needed
Edit - this sort of worked, but after storing the macro, when I went back to use it later, I couldn't use it with C-x e. (i.e., if I reboot emacs and then type M-x macro-name, and then C-x e, I get a message in the minibuffer like 'no last kbd macro' or something similar)
#Mike Stone - Thanks for the information. I tried creating a macro like so:
C-x( M-C-s ^.*Table\(\(.*C-q C-J\)*?GO\) C-x)
This created my macro, but when I executed my macro I didn't get the same highlighting that I ordinarily get when I use isearch-forward-regexp. Instead it just jumped to the end of the next match of the expression. So that doesn't really work for what I need. Any ideas?
Edit: It looks like I can use macros to do what I want, I just have to think outside the box of isearch-forward-regexp. I'll try what you suggested.
You can use macros, just do C-x ( then do everything for the macro, then C-x ) to end the macro, then C-x e will execute the last defined macro. Then, you can name it using M-x name-last-kbd-macro which lets you assign a name to it, which you can then invoke with M-x TESTIT, then store the definition using M-x insert-kbd-macro which will put the macro into your current buffer, and then you can store it in your .emacs file.
Example:
C-x( abc *return* C-x)
Will define a macro to type "abc" and press return.
C-xeee
Executes the above macro immediately, 3 times (first e executes it, then following 2 e's will execute it twice more).
M-x name-last-kbd-macro testit
Names the macro to "testit"
M-x testit
Executes the just named macro (prints "abc" then return).
M-x insert-kbd-macro
Puts the following in your current buffer:
(fset 'testit
[?a ?b ?c return])
Which can then be saved in your .emacs file to use the named macro over and over again after restarting emacs.
I've started with solving your problem literally,
(defun search-maker (s)
`(lambda ()
(interactive)
(let ((regexp-search-ring (cons ,s regexp-search-ring)) ;add regexp to history
(isearch-mode-map (copy-keymap isearch-mode-map)))
(define-key isearch-mode-map (vector last-command-event) 'isearch-repeat-forward) ;make last key repeat
(isearch-forward-regexp)))) ;`
(global-set-key (kbd "C-. t") (search-maker "^.*Table\\(\\(.*\\n\\)*?GO\\)"))
(global-set-key (kbd "<f6>") (search-maker "HELLO WORLD"))
The keyboard sequence from (kbd ...) starts a new blank search. To actually search for your string, you press last key again as many times as you need. So C-. t t t or <f6> <f6> <f6>. The solution is basically a hack, but I'll leave it here if you want to experiment with it.
The following is probably the closest to what you need,
(defmacro define-isearch-yank (key string)
`(define-key isearch-mode-map ,key
(lambda ()
(interactive)
(isearch-yank-string ,string)))) ;`
(define-isearch-yank (kbd "C-. t") "^.*Table\\(\\(.*\\n\\)*?GO\\)")
(define-isearch-yank (kbd "<f6>") "HELLO WORLD")
The key combos now only work in isearch mode. You start the search normally, and then press key combos to insert your predefined string.
#Justin:
When executing a macro, it's a little different... incremental searches will just happen once, and you will have to execute the macro again if you want to search again. You can do more powerful and complex things though, such as search for a keyword, jump to the beginning of the line, mark, go to end of the line, M-w (to copy), then jump to another buffer, then C-y (paste), then jump back to the other buffer and end your macro. Then, each time you execute the macro you will be copying a line to the next buffer.
The really cool thing about emacs macros is it will stop when it sees the bell... which happens when you fail to match an incremental search (among other things). So the above macro, you can do C-u 1000 C-x e which will execute the macro 1000 times... but since you did a search, it will only copy 1000 lines, OR UNTIL THE SEARCH FAILS! Which means if there are 100 matches, it will only execute the macro 100 times.
EDIT: Check out C-hf highlight-lines-matching-regexp which will show the help of a command that highlights everything matching a regex... I don't know how to undo the highlighting though... anyways you could use a stored macro to highlight all matching the regex, and then another macro to find the next one...?
FURTHER EDIT: M-x unhighlight-regexp will undo the highlighting, you have to enter the last regex though (but it defaults to the regex you used to highlight)
In general, to define a custom keybinding in Emacs, you'd write
(define-key global-map (kbd "C-c C-f") 'function-name)
define-key is, unsurprisingly, the function to define a new key. global-map is the global keymap, as opposed to individual maps for each mode. (kbd "C-c C-f") returns a string representing the key sequence C-c C-f. There are other ways of doing this, including inputting the string directly, but this is usually the most straightforward since it takes the normal written representation. 'function-name is a symbol that's the name of the function.
Now, unless your function is already defined, you'll want to define it before you use this. To do that, write
(defun function-name (args)
(interactive)
stuff
...)
defun defines a function - use C-h f defun for more specific information. The (interactive) there isn't really a function call; it tells the compiler that it's okay for the function to be called by the user using M-x function-name and via keybindings.
Now, for interactive searching in particular, this is tricky; the isearch module doesn't really seem to be set up for what you're trying to do. But you can use this to do something similar.