Emacs, moving point to first visible character - emacs

Is there any way to move point to the first currently visible character within a buffer? I would like to find this point because for a function it would really be faster to look from "first visible character" instead of "beginning of buffer".
EDIT: Actually, obtaining the value of the position would also be fine instead of moving the point actually there. PageUp and PageDown seem to have some weird behavior with this with big pieces of text.

If you want the point the current window is scrolled to:
(window-start)
If you want to skip over text that is hidden by text attributes, use invisible-p to skip past them:
(let ((pos (window-start)))
(while (and (invisible-p pos) (< pos (point-max)))
(setq pos (1+ pos)))
pos)

nschum gives the answer to obtaining the position value by: (window-start)
For moving point to this value use:
Based on nschum's answer:
(defun goto-window-start ()
(interactive)
(let ((pos (window-start)))
(while (and (invisible-p pos) (< pos (point-max) )
(setq pos (1+ pos)))
(goto-char pos))
)

Update: Handles empty buffer.
(defun goto-first-visible ()
(interactive)
(goto-char (point-min))
(save-match-data
(let ((pos (search-forward-regexp (rx graphic) nil t)))
(when pos
(goto-char (- pos 1))))))

Here is an efficient version that may work better for large chunks of invisible text. The hack here is to use the fact that invisible text is controlled by text properties, and emacs has built-in facilities for determining locations of text property changes:
(defun goto-first-visible ()
(interactive)
(goto-char (point-min))
(while (and (not (eobp)) (invisible-p (point)))
(goto-char (next-char-property-change (point)))))

Related

Function to Explode paragraph into org-bullets by sentences

I am trying to write a simple Elisp Emacs function that takes a paragraph (point indicated by [X]) and expands it into a series of bullet points with each bullet containing a sentence.
much more useful, especially with huge windows. In my experience, it slows down redraw a little bit, but it’s worth it.There are two ways to enable it: the first is with M-x visual-line-mode[X] (for those with real menus, apparently Options->Line Wrapping in this Buffer->Word Wrap), which will give you a minor mode “wrap” in the mode line.
and returns
+ much more useful, especially with huge windows.
+ In my experience, it slows down redraw a little bit, but it’s worth it.
+ There are two ways to enable it: the first is with M-x visual-line-mode[X] (for those with real menus, apparently Options->Line Wrapping in this Buffer->Word Wrap), which will give you a minor mode “wrap” in the mode line.
Here is what I have so far:
(defun jds/explode ()
"explode paragraph, more documentation needed"
(interactive)
(save-excursion
(let ((bop (copy-marker (progn (backward-paragraph) (point))))
(eop (copy-marker (progn (forward-paragraph) (point)))))
(goto-char bop)
(back-to-indentation) ;; goto first non-whitespace character
(if (re-search-forward "^[:blank:]*[+-x] " nil t) nil (insert "+ "))
(while (< (point) eop)
(forward-sentence)
(forward-whitespace 1)
(unless (>= (point) eop)
(org-meta-return)))))))))
But this just seems to run but not do anything. I think the problem may be that the backward-paragraph function may not be putting the point on the first non-black character (the m in much). But that said, my Elisp is very weak and I am struggling to figure out the problem.
Turns out this works - just needed to add +/-1 to point
(defun jds/explode ()
"explode paragraph, more documentation needed"
(interactive)
(save-excursion
(let ((bop (copy-marker (progn (backward-paragraph) (+ (point) 1))))
(eop (copy-marker (progn (forward-paragraph) (- (point) 1)))))
(goto-char bop)
(if (looking-at-p "^[:blank:]*[+-x] ") nil (insert "+ "))
(while (< (point) eop)
(forward-sentence)
(forward-whitespace 1)
(unless (>= (point) eop)
(org-meta-return))))))
(defun explode-paragraph ()
"Explode paragraph. If run twice it changes list marker."
(interactive)
(save-mark-and-excursion
(let ((bop (copy-marker (progn (backward-paragraph) (1+ (point)))))
(eop (copy-marker (progn (forward-paragraph) (point)))))
(goto-char bop)
(if (looking-at-p "^\s*[\-\+x] ") nil (insert "+ "))
(while (< (point) eop)
(forward-sentence)
(forward-whitespace 1)
(unless (>= (point) eop)
(org-meta-return))))))
I extended your implementation to work for my use-case. I changed a couple of things:
I changed [:blank:] to \s because it was matching on lines under a header (if anyone knows why this is I'd be happy to be educated).
I used the (+1 (point) notation and removed the -1 from the eop, as I didn't find it necessary.
I escaped the special symbols inside [...] because -x was matching lines starting with 'A'.
In my own version of this function I have the first line (summary sentence) a level up from the other sentences, but I think this should cover most cases for its original intended purpose.

emacs - scroll past top of buffer?

Emacs (and all other text editors) by default show blank space below the bottom lines of a buffer. I want emacs to be able to also scroll above/show blank space like this above the top lines in a buffer as well so that the top lines can be viewed in the center of the screen for small files.
With guidance from Thomas's answer here I have created a minor mode for this which is now available on MELPA:
TopSpace - Recenter line 1 with scrollable upper margin/padding
I've started a small minor-mode to accomplish this. However, as first versions go, it's probably buggy, doesn't handle all edge cases (such as e.g., narrowing), and isn't particularly efficient.
Thus, I'd be happy to accept improvements: feel free to directly edit this answer if you can make this code better or to extend it.
(defvar vertical-center-num-buffers 0
"The number of buffers in which `vertical-center-mode' is activated.")
(define-minor-mode vertical-center-mode
"This minor mode displays the contents of a buffer vertically
centered with respect to the window height. This, of course, only
makes sense for buffers whose content is shorter than the window
height."
nil
" vc"
nil
;; is the mode being turned on or off?
(if vertical-center-mode
;; on
(progn
;; keep track of the number of lines in the buffer
(setq-local vertical-center-num-lines (count-lines (point-min) (point-max)))
;; use an overlay to display empty lines at the beginning of the buffer
(setq-local vertical-center-overlay (make-overlay (point-min) (point-max)))
;; initial call to the function that centers the buffer contents
(vertical-center--lines-changed 0)
;; react to changes to the buffer or the window
(add-hook 'kill-buffer-hook 'vertical-center--kill-buffer)
(add-hook 'window-size-change-functions 'vertical-center--window-size-changed)
(when (= vertical-center-num-buffers 0)
(add-hook 'before-change-functions 'vertical-center--before-change)
(add-hook 'after-change-functions 'vertical-center--after-change))
;; this is just to play nice and remove the above hook
;; functions when they're no longer needed. Let's keep our
;; fingers crossed that we'll always stay in sync.
(setq vertical-center-num-buffers (1+ vertical-center-num-buffers)))
;; off
;; delete/unset data structures when the mode is turned off
(delete-overlay vertical-center-overlay)
(makunbound 'vertical-center-num-lines)
(makunbound 'vertical-center-overlay)
(setq vertical-center-num-buffers (1- vertical-center-num-buffers))
;; remove hook functions when they're no longer needed
(when (= vertical-center-num-buffers 0)
(remove-hook 'kill-buffer-hook 'vertical-center--kill-buffer)
(remove-hook 'window-size-change-functions 'vertical-center--window-size-changed)
(remove-hook 'before-change-functions 'vertical-center--before-change)
(remove-hook 'after-change-functions 'vertical-center--after-change))))
;; handle killing of buffers
(defun vertical-center--kill-buffer ()
(when vertical-center-mode
(setq vertical-center-num-buffers (1- vertical-center-num-buffers))))
;; react to changes in the window height
(defun vertical-center--window-size-changed (arg)
(vertical-center--lines-changed 0))
;; handle deletions of buffer text
(defun vertical-center--before-change (beginning end)
(when (boundp 'vertical-center-num-lines)
(let ((num-lines 0))
(while (< beginning end)
(when (= (char-after beginning) ?\n)
(setq num-lines (1- num-lines)))
(setq beginning (1+ beginning)))
(when (< num-lines 0)
(vertical-center--lines-changed num-lines)))))
;; handle insertions into the buffer
(defun vertical-center--after-change (beginning end previous-length)
(when (boundp 'vertical-center-num-lines)
(let ((num-lines 0))
(while (< beginning end)
(when (= (char-after beginning) ?\n)
(setq num-lines (1+ num-lines)))
(setq beginning (1+ beginning)))
(when (> num-lines 0)
(vertical-center--lines-changed num-lines)))))
;; update the display when either the buffer content or the window
;; height has changed
(defun vertical-center--lines-changed (num-lines)
(setq vertical-center-num-lines (+ vertical-center-num-lines num-lines))
(let ((top-margin (/ (- (window-height) vertical-center-num-lines) 2)))
;; set the top margin
(overlay-put vertical-center-overlay 'before-string
(when (> top-margin 0)
(make-string top-margin ?\n)))))
Save the above code in a file named "vertical-center.el" in a directory of your choice, and then add the following lines to your .emacs file:
(setq load-path (append load-path "<directory>"))
(autoload 'vertical-center-mode "vertical-center")
Here, <directory> should be the path to the directory in which you saved the "vertical-center.el" file.
After restarting Emacs, you can now activate or deactivate the mode by typing M-x vertical-center-mode.

A Simple 'copy-form Command

I want a command that copies a form to the kill ring. In emacs-live, the closest thing I could find was this command / key-binding
(global-set-key (kbd "M-]") 'kill-ring-save)
However kill-ring-save has some wonky behaviour. Ii copies more than 1 form, past the cursor. Ultimately, I want a simple function along the lines of what's below (this doesn't quite work).
(defun copy-form ()
(kill-ring-save (line-beginning-position) (live-paredit-forward)))
(global-set-key (kbd "M-]") 'copy-form)
I've searched high and low ( SO question and Google search), but can't seem to find a simple, working command to copy a balanced expression. Has someone already done this?
Thanks
Tim
Function sexp-at-point gives you the sexp ("form") at the cursor. Just copy that to the kill-ring, using kill-ring-save. E.g.:
(defun copy-sexp-at-point ()
(interactive)
(let ((bnds (bounds-of-thing-at-point 'sexp)))
(kill-ring-save (car bnds) (cdr bnds))))
Alternatively, just use kill-new:
(defun copy-sexp-at-point ()
(interactive)
(kill-new (thing-at-point 'sexp)))
The reason your copy-form cannot be bound to a key is that it is a function, not a command - it is missing an interactive form.
However, in your case you don't even need to write a new function.
Try a combination of
mark-sexp is an interactive compiled Lisp function in `lisp.el'.
It is bound to C-M-#, C-M-SPC.
and
M-w runs the command kill-ring-save, which is an interactive compiled
Lisp function in `simple.el'.
It is bound to <C-insertchar>, M-w, <menu-bar> <edit> <copy>.
I'm not sure I understand the question, but when I need to do what I consider as "copy a balanced form", I do: M-C-SPC M-w. If I want to cut it instead, I do M-C-SPC C-w.
Here's what I generally use. Somehow it's more useful for me
to kill the balanced expression instead of copying. If I want a
copy instead, I first kill, then undo.
This function kills a string, if the point is inside string,
otherwise the balanced expression, i.e. (),[],{},<>
or whatever is defined by the syntax.
(defun kill-at-point ()
"Kill the quoted string or the list that includes the point"
(interactive)
(let ((p (nth 8 (syntax-ppss))))
(cond
;; string
((eq (char-after p) ?\")
(goto-char p)
(kill-sexp))
;; list
((ignore-errors (when (eq (char-after) ?\()
(forward-char))
(up-list)
t)
(let ((beg (point)))
(backward-list)
(kill-region beg (point)))))))
I've also tried to add a special case for when the point is
inside the comment, but I couldn't find a generic
way to determine bounds of comment at point. If anyone knows,
please tell me.
This other function can be relevant as well. It marks instead
of killing, like the previous one. The nice thing that it
extends the region each time it's called.
I bind the first one to C-, and the second to
C-M-,.
(defun mark-at-point ()
"Mark the quoted string or the list that includes the point"
(interactive)
(let ((p (nth 8 (syntax-ppss))))
(if (eq (char-after p) ?\")
(progn
(goto-char p)
(set-mark (point))
(forward-sexp))
(progn
(when (eq (char-after) 40)
(forward-char))
(condition-case nil
(progn
(up-list)
(set-mark (point))
(let ((beg (point)))
(backward-list)
(exchange-point-and-mark)))
(error
(when (looking-back "}")
(exchange-point-and-mark)
;; assumes functions are separated by one empty line
(re-search-backward "^[^A-Z-a-z]" nil t)
(forward-char))))))))

'Semantic' movement across a line

Consider the following line of Lisp code:
(some-function 7 8 | 9) ;; some comment. note the extra indentation
The point is placed between '8' and '9'. If I perform (move-beginning-of-line), the point will be placed at the absolute beginning of the line, rather than at '('.
Same for move-end-of-line: I'd find it more desirable for it to place the point at ')' if I perform it once, and at the absolute end of the line if I perform it a second time. Some IDEs behave like that.
I tried to implement this but got stuck, my solution behaves particularly bad near the end of a buffer, and on the minibuffer as well. Is there a library that provides this functionality?
I don't know of any library, but it can be done in a few lines of Elisp.
For the beginning of line part, the bundled functions beginning-of-line-text and back-to-indentation (M-m) move to the beginning of the “interesting” part of the line. back-to-indentation ignores only whitespace whereas beginning-of-line-text skips over the fill prefix (in a programming language, this is typically the comment marker, if in a comment). See Smart home in Emacs for how to flip between the beginning of the actual and logical line.
For the end of line part, the following function implements what you're describing. The function end-of-line-code moves to the end of the line, except for trailing whitespace and an optional trailing comment. The function end-of-line-or-code does this, except that if the point was already at the target position, or if the line only contains whitespace and a comment, the point moves to the end of the actual line.
(defun end-of-line-code ()
(interactive "^")
(save-match-data
(let* ((bolpos (progn (beginning-of-line) (point)))
(eolpos (progn (end-of-line) (point))))
(if (comment-search-backward bolpos t)
(search-backward-regexp comment-start-skip bolpos 'noerror))
(skip-syntax-backward " " bolpos))))
(defun end-of-line-or-code ()
(interactive "^")
(let ((here (point)))
(end-of-line-code)
(if (or (= here (point))
(bolp))
(end-of-line))))
Some suggestions that almost do what you ask:
In lisp code, you can sort-of do what you want, with the sexp movement commands. To get to the beginning of the expression from somewhere in the middle, use backward-up-list, which is bound to M-C-u. In your example, that would bring you to the open parenthesis. To move backwards over individual elements in the list, use backward-sexp, bound to M-C-b; forward-sexp moves the other way, and is bound to M-C-f. From the beginning of an sexp, you can skip to the next with M-C-n; reverse with M-C-p.
None of these commands are actually looking at the physical line you are on, so they'll go back or forward over multiple lines.
Other options include Ace Jump mode, which is a very slick way to quickly navigate to the beginning of any word visible on the screen. That might eliminate your need to use line-specific commands. For quick movement within a line, I usually use M-f and M-b to jump over words. Holding the M key down while tapping on b or f is quick enough that I end up using that by default most of the time.
Edit:
Forgot one other nice command - back-to-indentation, bound to M-m. This will back you up to the first non-whitespace character in a line. You could advice this to behave normally on the first call, and then to back up to the beginning of the line on the second call:
(defadvice back-to-indentation (around back-to-back)
(if (eq last-command this-command)
(beginning-of-line)
ad-do-it))
(ad-activate 'back-to-indentation)
I just wrote these two functions that have the behavior you are looking for.
(defun move-beginning-indent ()
(interactive)
(if (eq last-command this-command)
(beginning-of-line)
(back-to-indentation))
)
(defun move-end-indent ()
(interactive)
(if (eq last-command this-command)
(end-of-line)
(end-of-line)
(search-backward-regexp "\\s)" nil t) ; searches backwards for a
(forward-char 1)) ; closed delimiter such as ) or ]
)
(global-set-key [f7] 'move-beginning-indent)
(global-set-key [f8] 'move-end-indent)
Just try them out, they should behave exactly the way you'd want them to.
I use this:
(defun beginning-of-line-or-text (arg)
"Move to BOL, or if already there, to the first non-whitespace character."
(interactive "p")
(if (bolp)
(beginning-of-line-text arg)
(move-beginning-of-line arg)))
(put 'beginning-of-line-or-text 'CUA 'move)
;; <home> is still bound to move-beginning-of-line
(global-set-key (kbd "C-a") 'beginning-of-line-or-text)
(defun end-of-code-or-line ()
"Move to EOL. If already there, to EOL sans comments.
That is, the end of the code, ignoring any trailing comment
or whitespace. Note this does not handle 2 character
comment starters like // or /*. Such will not be skipped."
(interactive)
(if (not (eolp))
(end-of-line)
(skip-chars-backward " \t")
(let ((pt (point))
(lbp (line-beginning-position))
(comment-start-re (concat (if comment-start
(regexp-quote
(replace-regexp-in-string
"[[:space:]]*" "" comment-start))
"[^[:space:]][[:space:]]*$")
"\\|\\s<"))
(comment-stop-re "\\s>")
(lim))
(when (re-search-backward comment-start-re lbp t)
(setq lim (point))
(if (re-search-forward comment-stop-re (1- pt) t)
(goto-char pt)
(goto-char lim) ; test here ->
(while (looking-back comment-start-re (1- (point)))
(backward-char))
(skip-chars-backward " \t"))))))
(put 'end-of-code-or-line 'CUA 'move)
;; <end> is still bound to end-of-visual-line
(global-set-key (kbd "C-e") 'end-of-code-or-line)

Emacs Lisp buffer not running font lock mode until opened by user

My problem is I am opening a buffer using (set-buffer (find-tag-noselect (current-word))) and then I try to copy some text out of that buffer. The text that I get back has only the properties (fontified nil). find-tag-noselect automatically opens the buffer found in the TAGS file but it seems it does not run the font lock mode over it. When I manually switch to this buffer after it has been opened and then run the function again when it copies the text it has all the correct text properties attached. So what do I need to do to have this buffer completely initialized so that the correct syntax highlighting will be copied in?
(defvar newline-string "
")
(defun get-initial-indent-regexp-python()
"Gets the initial amount of spaces for the function we are looking at, does not account for tabs"
(concat "^" (get-current-indent-string) (concat "[^ #" newline-string "]")))
(defun get-end-of-function-python(spaces-regex)
"Gets the point at the end of a python block"
(save-excursion
(forward-line 1)
(while (and (not (looking-at spaces-regex)) (equal (forward-line 1) 0)))
(point)))
(defun get-point-at-end-of-function ()
"This might be better served checking the major mode."
(setq extension (file-name-extension (buffer-file-name)))
(if (equal extension "py")
(get-end-of-function-python (get-initial-indent-regexp-python))))
(defun inline-function ()
"Must change to overlays, be able to toggle visibility"
(interactive)
(let (text indent-string)
; clean all overlays without attached buffer
(save-excursion
(set-buffer (find-tag-noselect (current-word)))
(setq text (buffer-substring (point) (get-point-at-end-of-function))))
(setq text (concat newline-string text))
(save-excursion
(move-end-of-line nil)
(let (overlay)
(setq overlay (make-overlay (point) (+ (point) 1) (current-buffer)))
(overlay-put overlay 'display text)
(setq inline-func-overlays (cons overlay inline-func-overlays))))))
What's happening is that font-lock is done on-the-fly, so only the displayed parts of the buffer get "fontified". If you want/need to overrule this optimization, you need different functions depending on the circumstance (depending on how font-lock happens to be configured). We should add a new font-lock-ensure-fontified function for that, but in the mean time, you can take ps-print-.el as an example:
(defun ps-print-ensure-fontified (start end)
(cond ((and (boundp 'jit-lock-mode) (symbol-value 'jit-lock-mode))
(jit-lock-fontify-now start end))
((and (boundp 'lazy-lock-mode) (symbol-value 'lazy-lock-mode))
(lazy-lock-fontify-region start end))))
I'm not exactly sure what you're trying to do, but set-buffer does not display the buffer, so its effect ends when the current command terminates. It's generally useful only for temporary buffer switches inside a function and I guess this is the reason it doesn't run font-lock on the buffer. When you manually go to the buffer you're probably using a different function - switch-to-buffer.
Try explicitly calling 'font-lock-fontify-buffer'.