Skip to content

Commit dc3ca39

Browse files
committed
Ensure window-start and window-hscroll remain unchanged
This commit ensures that `markdown-toc-generate-toc` does not change the window start or window hscroll, addressing a common issue that can alter these settings.
1 parent ba74a85 commit dc3ca39

File tree

1 file changed

+27
-9
lines changed

1 file changed

+27
-9
lines changed

markdown-toc.el

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -272,15 +272,33 @@ the deleted TOC region, effectively replacing it."
272272
"Generate a TOC for markdown file at current point.
273273
Deletes any previous TOC."
274274
(interactive)
275-
(save-excursion
276-
(when (markdown-toc--toc-already-present-p)
277-
;; when toc already present, remove it
278-
(markdown-toc--delete-toc t))
279-
(->> (funcall imenu-create-index-function)
280-
markdown-toc--compute-toc-structure
281-
(funcall markdown-toc-user-toc-structure-manipulation-fn)
282-
markdown-toc--generate-toc
283-
insert)))
275+
;; Set truncate-lines to t because count-screen-lines is not reliable enough
276+
;; when truncate-lines is set to nil.
277+
(let* ((truncate-lines t)
278+
(window-hscroll (window-hscroll))
279+
(point (save-excursion (vertical-motion 0)
280+
(point)))
281+
(window-start (save-excursion (goto-char (window-start))
282+
(vertical-motion 0)
283+
(point)))
284+
(lines-before-marker (count-screen-lines window-start point)))
285+
(unwind-protect
286+
(save-excursion
287+
(when (markdown-toc--toc-already-present-p)
288+
;; When toc already present, remove it
289+
(markdown-toc--delete-toc t))
290+
(->> (funcall imenu-create-index-function)
291+
markdown-toc--compute-toc-structure
292+
(funcall markdown-toc-user-toc-structure-manipulation-fn)
293+
markdown-toc--generate-toc
294+
insert))
295+
(let ((window-start (save-excursion
296+
(vertical-motion 0)
297+
(line-move-visual (* -1 lines-before-marker))
298+
(vertical-motion 0)
299+
(point))))
300+
(set-window-start (selected-window) window-start t))
301+
(set-window-hscroll (selected-window) window-hscroll))))
284302

285303
(defalias 'markdown-toc/generate-toc 'markdown-toc-generate-toc)
286304

0 commit comments

Comments
 (0)