Emacs - How to wrap selection in org-mode source code block? - emacs

I have a bunch of elisp and other code with some notes i wanted to reformat to be more organized, and i found that having to type
#+BEGIN_SRC emacs-lisp ... #+END_SRC
all the time around what i want, is taking a bit longer than expected...
So what i wanted to do instead is to wrap/or put the selected content (with C-space) and put it in a template source code block for org-mode (in my case it's mostly elisp code, but i plan to use it for other things maybe)
How could i do this in emacs or in elisp?

There is a new templating mechanism in recent Org mode (>= 9.0 IIRC) that allows you tor wrap a region in a block: after selecting the region in the usual manner, you say C-c C-, s. You still have to type the emacs-lisp part though. That's the disadvantage. The advantage is that it is general enough to allow you to wrap a region in any kind of block. In your case, I think the disadvantage outweighs the advantage, so I would go with the wrap-region method in the other answer, but this one is good to know as well.

You can try wrap-region. It will allow you to define what type of string you want to wrap around a selection.
Put this in your init.el and evaluate it.
(wrap-region-global-mode t)
(wrap-region-add-wrapper "#+BEGIN_SRC emacs-lisp\n" "#+END_SRC" "#" 'org-mode)
Then, while you are editing your org files, you can select a block of text and type #, which will wrap it with your string. You can change the # to another character that will do the wrapping.

There is a feature in org-mode to do exactly that. It's like a snippet of some sort where you enter <eland hit TAB, the < char is here to say we're gonna use a template and the el part tells which template to use. But of course, you have to configure it first.
For that, you can just add this to an org-mode file or to your init.el file :
#+begin_src emacs-lisp
;; This is needed as of Org 9.2
(require 'org-tempo)
(add-to-list `org-structure-template-alist `("sh" . "src shell"))
(add-to-list `org-structure-template-alist `("el" . "src emacs-lisp"))
(add-to-list `org-structure-template-alist `("py" . "src python"))
#+end_src
There a bunch of way to use this, it's actually more useful than just use it as a template, you can go check the documentation here.

Related

Is there a way to disable indentation for one specific org-mode src block at a time?

I'm using most of the standard features of org-mode that come with the spacemacs develop branch, but I haven't been able to find a way to disable the automatic indentation for source code blocks on a case by case basis. I use tangle and I'm writing Dockerfile's in the same file that I'm writing groovy code or javascript for example. The Dockerfile's are the only ones I want not to be indented so I can get syntax highlighting. Here's what it looks like without the indentation:
And here's what it looks like with the indentation that automatically happens if I edit the text:
The automatic indentation is fine for groovy for example, so I have no issue with the automatic indentation here. (in fact, if I still got the syntax highlighting for Dockerfile's I probably wouldn't mind too much except the weird word wrapping not respecting the background face). Here's the example with groovy:
As you can see, I tried a :noindent property I found in the org-mode docs that's usually in a #+STARTUP directive. I also searched stack overflow, but I didn't find anything fruitful that didn't disable indenting for all source blocks or for the entire file.
In my practice (I'm not sure it is a good practice or not, just share it to you):
I setup org-src-tab-acts-natively to true for using the language’s major-mode indentation. In your case, it will format the src block with the formatting rules of dockerfile-mode.
I created a new major-mode plain-mode for the content which should not be indented automatically. Personally, I use this mode for something like:
shell outputs
ASCII diagrams
...
#+begin_src plain
this will not
be
auto
indented
#+end_src
Above src block will not be indented when you select them as region, and TAB on them.
In this way, the src blocks will always behavior as expected when formatting them.
Aside, the example code of plain-mode:
(define-derived-mode plain-mode
clean-mode "Plain"
"Major mode for plain text."
;; preserve the auto indentation on line
(setq-local indent-line-function 'indent-relative)
;; disable auto indentation on region
(setq-local indent-region-function (lambda (start end))))

Set emacs comment style based on file extension

There are multiple questions along these lines but I haven't been able to find what I need from start to finish. I have been using emacs for a few years but am not used to its customization.
I have a unique file type, identified by its extension, which emacs is not configured for. Its comment style is
<!-- text -->
and I would like to set the variables comment-start and comment-end to the relevant values (which I am assuming will allow me to use comment-region). I don't know the correct way to do this so that it will always be configured when I open this file type but won't affect the default behavior of emacs.
Do I need to make a new major mode for this file type, and then set the variables, or is there an easier way of doing it? An example of the complete requirements for my .emacs file would be much appreciated!
See here. I think this will work:
(add-to-list 'auto-mode-alist
'("\\.extension\\'" . (lambda ()
(setq-local comment-start "<!--")
(setq-local comment-end "-->"))))
Alternatively, if this file extension is well known (or if these files are close enough to a well known syntax), you may be able to just find a major-mode online that does what you want. For example, NXML Mode may just give you the comment syntax you want along with some other useful features.

The major mode name of emacs-lisp

I want to load emacs init files faster, so I use the 'eval-after-load.
For example, when I load clojure file, I just put
(eval-after-load 'clojure-mode
'do-something)
It works.
But when I try
(eval-after-load 'emacs-lisp-mode
'do-something)
It doesn't work. I wonder to know the right major mode name of emacs-lisp.
Thanks.
Please read the documentation of eval-after-load:
eval-after-load LIBRARY FORM
This function arranges to evaluate form at the end of loading the file LIBRARY, each time LIBRARY is loaded. If LIBRARY is already loaded, it evaluates form right away. Don't forget to quote form!
[…] LIBRARY can also be a feature (i.e., a symbol), in which case form is evaluated at the end of any file where (provide LIBRARY) is called.
You have to pass the name of the file or library, which defines the major mode, as argument.
While some modes are defined in files of the same name (e.g. clojure-mode in clojure-mode.el), many files a different name, especially if the actually define multiple major modes.
emacs-lisp-mode is defined in lisp-mode.el, along with some other modes for Emacs Lisp editing (e.g. lisp-mode as a generic Lisp language mode, or lisp-interaction-mode for *scratch* buffers).
Hence, use (eval-after-load 'lisp-mode …)
Also, you have to give a single sexp as second argument, so you'll likely want to use (eval-after-load 'lisp-mode '(do-something)), to call the function do-something.
If you are using a snapshot build of Emacs, use with-eval-after-load, i.e. (with-eval-after-load 'lisp-mode (do-something)). It allows for more than a single form, and doesn't require quoting.
Just eval with M-: the variable major-mode. It actually is emacs-lisp-mode.
Note that *scratch* is actually in lisp-interaction-mode.
As to what you're trying to do, use (eval-after-load "lisp-mode").
As explained by #lunaryom, the arg passed to eval-after-load is not a function name but a feature name, which is basically a file name. So you need to find the name of the file from which the function is loaded.
We could provide a feature like eval-after-defun, and indeed it might be a good idea to do so. If you'd like such a thing, ask for it via M-x report-emacs-bug.

Font-locking for SQL-MODE inside of ORG-MODE not font-locking

Related to question: org-mode: fontify code blocks natively
I've got the latest org-mode and emacs versions as of November 1, 2012 (org stored in org-20121105).
I've also got the sql-mode that comes with emacs-24.
I've got fontification turned one:
;; fontify code in code blocks
(setq org-src-fontify-natively t)
Yet this does not fontify in my org documents. Java, bash, etc. all work.
#+BEGIN_SRC SQL
SELECT foo FROM bar
#+END_SRC
When I open a file foobar.sql, the mode indicator says SQL[ANSI] (which I also tried as the source type), and font-locking works.
Thanks in advance for any tips.
Firstly, the name of the SRC block mode is case-sensitive. It should be sql instead of SQL.
#+BEGIN_SRC sql
SELECT foo FROM bar
#+END_SRC
Secondly, the initial font-lock of sql-mode seams not to highlight SQL keywords, (at least to me, it looks no difference no matter you turn it on or off). Therefore, you need to specify which kind of SQL you want to highlight. If you are using MySQL for example:
(add-hook 'sql-mode-hook
(lambda ()
(sql-highlight-mysql-keywords)))
Then Restart Emacs. It should work now.
Oh, wait, try putting #+BEGIN_SRC sql in lower case. See here for identifiers.
Try refreshing the display, by making the block be reparsed (break the syntax and undo, or something). It often happens to me with python or bibtex blocks, but this fixes it.
I can't see why it wouldn't fontify inline if it finds the right mode when you C-c '.
Also, I'm afraid fontification, while being one of org-mode's nicer features, is not exactly perfectly handled. From the mailing list :
The fontification engine is not very powerful and get easily fooled.

Starting any Emacs buffer with a .c extension with a template

I write a lot of short throwaway programs, and one of the things I find myself doing repeatedly is typing out code like
#include <stdio.h>
#include <stdlib.h>
int main(void){
}
To save some tendon hits I was wondering if it was possible to insert a simple template above whenever I create a buffer with the extension of .c.
Put somthing like this in .emacs
(define-skeleton c-throwaway
"Throwaway C skeleton"
nil
"#include <stdio.h>\n"
"#include <stdlib.h>\n"
"\n"
"int main(void){\n"
"\n"
"}\n")
And eval (C-x C-e) it. That'll give you a
function (c-throwaway) that inserts your template.
To get this inserting automaticly you'll need to activate
auto-insert-mode. Once you do this you can describe-variable
auto-mode-alist and read up on how emacs does some of its open
file magic. Then define auto-insert-alist to apply it when you
find a new file.
Maybe something like this
(define-auto-insert "\\.\\([Cc]\\|cc\\|cpp\\)\\'" 'c-throwaway)
More detail:
Auto Insert Mode
Autotype
I use template.el from http://emacs-template.sourceforge.net/
Basically, I create a file called ~/.templates/TEMPLATE.c, and then that gets inserted into my .c files. You can also use special markup and arbitrary lisp expressions, if you don't just want to dump text into the buffer. I use this feature so that Perl modules start with "package Foo::Bar" when they are named lib/Foo/Bar.pm. Very handy.
The following function will ask for a filename and then insert a file and change to c-mode. The only problem is that you have to call this function to create the buffer instead of your normal way.
(defun defaultCtemplate(cfilename)
(interactive "sFilename: ")
(switch-to-buffer (generate-new-buffer cfilename))
(insert-file-contents "~/Desktop/test.c")
(c-mode)
)
P.S Thanks for the question, now I know how to do this for myself :)
You can also use the YASnippet template system for Emacs, which just has a builtin template called main. So while writing your code, just type main, hit TAB, and it will expand it to the form you want. (And you can always write your own snippet templates.)
I use following code to create files from templates. There are several templates, that are substitutes with actual file names, etc
This question is old, but this might help someone. Looking at this site, I copied and pasted this part into my .emacs file:
;; automatic insertion of templates
(require 'autoinsert)
(auto-insert-mode) ;;; Adds hook to find-files-hook
(setq auto-insert-directory "~/Documents/Emacs/templates/") ;;; *NOTE* Trailing slash important
;;(setq auto-insert-query nil) ;;; If you don't want to be prompted before insertion
(define-auto-insert "\.tex" "my-latex-template.tex")
(define-auto-insert "\.cpp" "my-cpp-template.cpp")
(define-auto-insert "\.h" "my-cpp-template.h")
After changing the directory and filenames, it works perfectly.
Here's how I do it (because I didn't know about auto insert mode :-)
(require 'tempo)
(setq c-new-buffer-template
'(
"#include <stdio.h>\n"
"#include <stdlib.h>\n"
"\n"
"int main(void){\n"
"\n"
"}\n"
))
(defun my-c-style ()
"My editing style for .c files."
(c-mode)
(if (zerop (buffer-size))
(tempo-template-c-skeleton)))
(setq auto-mode-alist
(cons '("\\.c\\'" . my-c-style) auto-mode-alist))
(tempo-define-template "c-skeleton" c-new-buffer-template
nil
"Insert a skeleton for a .c document")
I use a combination of Defaultcontent.el and YASnippet.el. The former fills brand-new files with default content. The latter is a sort of lightweight code-gen macro thing. Key in "for" and hit TAB and the skeleton of a for loop is inserted. Etc. You can define your own snippets pretty easily. "swi TAB" gets you a complete switch statement. And so on.
yasnippet is good at expand template in your file, and is very easy to create your snippets.
auto-insert is good at fill a new file with template, but write your own template is hard. There is a great package yatemplate bridges the gap between YASnippet and auto-insert-mode, i can write auto-insert rules with YASnippet.