Close HTML tags as soon as you open them

I would like for the corresponding closing HTML tag to be automatically inserted when I open it.

So, if I type

<div> 

I have to get

 <div></div> 

Without having to call sgml-close-tag .

How to do it?

+4
source share
4 answers

Instead of invoking the hook function after each individual keystroke, it only makes sense to invoke it after entering > . This can be achieved by reassigning the > character in the keyboard layout used by sgml-mode .

In addition, sgml-close-tag should not be called if the tag is already closed. Therefore, the following code adds a simple regular expression for this:

 (defun my-sgml-insert-gt () "Inserts a `>' character and calls `my-sgml-close-tag-if-necessary', leaving point where it is." (interactive) (insert ">") (save-excursion (my-sgml-close-tag-if-necessary))) (defun my-sgml-close-tag-if-necessary () "Calls sgml-close-tag if the tag immediately before point is an opening tag that is not followed by a matching closing tag." (when (looking-back "<\\s-*\\([^</> \t\r\n]+\\)[^</>]*>") (let ((tag (match-string 1))) (unless (and (not (sgml-unclosed-tag-p tag)) (looking-at (concat "\\s-*<\\s-*/\\s-*" tag "\\s-*>"))) (sgml-close-tag))))) (eval-after-load "sgml-mode" '(define-key sgml-mode-map ">" 'my-sgml-insert-gt)) 
+2
source

If you like paredit (and if you're an emacs user, most likely you do), you might be interested in tagedit , an emacs package written by Magnar Sveen that provides paredit html editing features.

The library is located here: https://github.com/magnars/tagedit and can be installed via Melpa / Marmalade ( package-install tagedit ).

If you enable the experimental features (tagedit-add-experimental-features) , it will automatically close the tags for you and save the corresponding closing tag text corresponding to the text of the open tag. This, besides the possibility of splicing, slurp, barf and all the other crazy things that paredit allows you to do when working with balanced expressions ... I think it's great!

+3
source

I use yasnippet for this purpose. To print the labels of this answer, for example <kbd>Co</kbd> , I have the following snippet:

 # -*- mode: snippet -*- # name: kbd # key: kbd # -- <kbd>$0</kbd> 

So, I type kbd Co and expand to <kbd></kbd> with the cursor right in the center. You can have the same behavior for a div .

+1
source

You can evaluate this in your sgml buffer or add ii to your sgml-hook:

 (add-hook 'post-self-insert-hook (lambda () (and (eq (char-before) ?>) (sgml-close-tag))) nil t) 

Whenever you insert ">", the sgml-close-tag function will be run for you

+1
source

Source: https://habr.com/ru/post/1500674/


All Articles