如何在elisp中获得可靠的缩进 [英] How to get reliable indentation in elisp

查看:168
本文介绍了如何在elisp中获得可靠的缩进的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Emacs的新手。

I'm new to Emacs.

我正在尝试编写一个适用于所有模式的elisp函数。具体来说,我想编写一个插入大括号的函数(有点像 insert-bracketheses ),方式与以下键序列相同,只能支持auto-缩进:

I'm trying to write an elisp function that works across all modes. Specifically, I want to write a function that inserts braces (a bit like insert-parentheses) in the same way the following key sequence does for a dumb editor that only supports auto-indent:

"{" <ret> "}" <up-arrow> <end> <ret> <tab>

此键序列适用于Java和C#(bsd)样式缩进。我需要它在所有大括号emacs模式下工作,还有纯文本文件 - 我有其他格式没有emacs模式,但仍然使用大括号。

This key sequence works for both Java and C# (bsd) style indentation. I need it to work in all brace-y emacs modes, and also in plain text files - I have other formats that have no emacs modes but still use braces.

这里是我的第12次尝试:

Here's my 12th attempt or so:

(defun insert-braces-macro ()
  (interactive)
  (insert "{")
  (newline)
  (indent-relative t)
  (insert "}")
  (forward-line -1)
  (end-of-line)
  (newline)
  (indent-relative t)
  (indent-relative nil))

不幸的是,这并不正确。我不认为 indent-relative 是正确的功能,因为它不能在Java风格中正确缩进:

Unfortunately, this doesn't work quite right. I don't think indent-relative is the right function, because it doesn't indent correctly in Java-style:

f |

扩展到:

f {
  |
}

和C模式:

somelongword another |

展开为:

somelongword another {
             |
}

但是 indent-upon-to-mode 也是不对的,因为它会在C-ish模式中缩进太多(尾随的'}'缩进),而不是在基本模式下。

But indent-according-to-mode isn't right either, because it will indent too much in C-ish modes (the trailing '}' is indented) and not at all in Fundamental mode.

正确的处理方式是什么?

What's the right way to handle this?

推荐答案

indent-to-mode 是正确的答案,但是您需要记住,它无法预测未来,因此您需要在插入文本之后调用而不是之前: ($)

indent-according-to-mode is the right answer, I think, but you need to remember that it can't predict the future, so you need to call it after inserting the text rather than before:

(defun insert-braces-macro ()
  (interactive)
  (insert "{")
  (newline) (indent-according-to-mode)
  (save-excursion
    (newline)
    (insert "}")
    (indent-according-to-mode)))

这篇关于如何在elisp中获得可靠的缩进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆