How to insert newline without change column of cursor/point ?

Like in picture-mode:

C-n runs the command picture-move-down (found in picture-mode-map),
which is an interactive compiled Lisp function in ‘picture.el’.

It is bound to C-n, <down>.

(picture-move-down ARG)

Move vertically down, making whitespace if necessary.
With argument, move that many lines.

[back]

In EmacsWiki: Picture Mode, the author say:

What I don’t like is when people respond with “Use picture-mode.” when someone asks the question: “How do I make emacs position the cursor in the same column if I move up or down when the line I move to is shorter than the current one?” . Why don’t I like this? Because I have seen those questions and the answers many times and it is often obvious that the person asking the question does not want picture-mode at all. He wants that feature added as (for example) a minor-mode, to be used when editing source-code.

The author does not give us an answer about the question, hoping you guys could help me. :lollipop:

  1. M-x picture-mode
  2. C-n
  3. Typing…Typing
  4. C-c C-c
1 个赞

我看了quote的这段话然后又去看了下picture-mode,确实是个major mode,楼主自己给的答案似乎并不够好……

How about this:

(defun codedoc/newline-vertical-align ()
  "Insert new line, insert whitespaces to align vertical position with where point was on last line."
  (interactive)
  (let ((padding (- (point) (line-beginning-position))))
    (end-of-line)
    (newline)
    (insert (s-repeat padding " ")))) ; `s-repeat' is from s.el
2 个赞

Emacs 自带 C-M-o (split-line), 似乎能满足你的需求?

(defun split-line (&optional arg)
  "Split current line, moving portion beyond point vertically down.
If the current line starts with `fill-prefix', insert it on the new
line as well.  With prefix ARG, don't insert `fill-prefix' on new line.

When called from Lisp code, ARG may be a prefix string to copy."
  (interactive "*P")
  (skip-chars-forward " \t")
  (let* ((col (current-column))
	 (pos (point))
	 ;; What prefix should we check for (nil means don't).
	 (prefix (cond ((stringp arg) arg)
		       (arg nil)
		       (t fill-prefix)))
	 ;; Does this line start with it?
	 (have-prfx (and prefix
			 (save-excursion
			   (beginning-of-line)
			   (looking-at (regexp-quote prefix))))))
    (newline 1)
    (if have-prfx (insert-and-inherit prefix))
    (indent-to col 0)
    (goto-char pos)))

1 个赞