简体   繁体   English

Emacs lisp:替换缓冲区内容时保持光标位置

[英]Emacs lisp : keep cursor position when replacing buffer content

I'm trying to fix an issue on in the web-beautify package.我正在尝试解决web-beautify包中的问题。

An elisp function uses an external tool to reformat the content of the buffer. elisp 函数使用外部工具重新格式化缓冲区的内容。 It then does the following, to try and keep the cursor position :然后它会执行以下操作,以尝试保持光标位置:

(let ((p (point)))
   (save-excursion
     (with-current-buffer (current-buffer)
       (erase-buffer)
       (insert-buffer-substring outputbuf)))
   (goto-char p)
   ...

If any line is added before the point, the (goto-char p) can cause the buffer to scroll erratically.如果在该点之前添加任何行,则(goto-char p)会导致缓冲区不规则滚动。

Following this , I tried replacing p with (create-marker (point) t) ;之后,我尝试用(create-marker (point) t)替换p It does seem to handle text added at the beginning of the buffer better, in general ;一般来说,它似乎确实可以更好地处理在缓冲区开头添加的文本; however in this case, it does not work at all (presumably because the content of the buffer is completely replace.)但是在这种情况下,它根本不起作用(大概是因为缓冲区的内容被完全替换了。)

How would you attack this ?你会如何攻击这个?

I don't think there can be a fully general answer to this question.我认为这个问题没有一个完全通用的答案。 The notion of the place in the new text which corresponds to a particular spot in the original text completely depends on our human understanding of what the text is and how it's modified and what matters and what doesn't.新文本中与原始文本中特定位置相对应的位置的概念完全取决于我们人类对文本是什么以及它如何修改以及什么重要什么不重要的理解。

So you need to look at the kind of changes operated by the external tool and try to figure out a way to find what you consider to be the corresponding spot.因此,您需要查看外部工具操作的更改类型,并尝试找出一种方法来找到您认为对应的位置。 Eg if the tool doesn't add/remove lines, then you can preserve the line-position, on the contrary if the tool only adds/removes lines then you can look at the text surrounding point and try to find it again in the new text.例如,如果该工具不添加/删除行,那么您可以保留行位置,相反,如果该工具仅添加/删除行,则您可以查看点周围的文本并尝试在新的文本。

Looks like replace-buffer should do the trick.看起来replace-buffer应该可以解决问题。

Source: https://emacs.stackexchange.com/a/47889/10669来源: https : //emacs.stackexchange.com/a/47889/10669

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM