writes: > On Wed, Aug 11, 2021 at 11:00:53AM +0800, Hongyi Zhao wrote: >> On Wed, Aug 11, 2021 at 9:51 AM Drew Adams wrote: > > [...] > >> Thank you for your solution, but it seems so complicated to me. > > You prefer something to hack on yourself ;-) > > OK, here's one attempt. But be careful. I just tested it > twice, so there may be two bugs left :-) > > (defun goto-longest-line () > (let ((maxpos) > (maxlen 0)) > (goto-char (point-min)) > (while > (let ((len (- (line-end-position) > (line-beginning-position)))) > (when (> len maxlen) > (setq maxlen len > maxpos (point))) > (= (forward-line) 0))) > (goto-char maxpos))) > > Cheers > - t This looks like such a typical school assignement. Usually when students have learned how to open and read files ... Here is mine solution, I had same idea as Thomas, I just did it little bit differently: #+begin_src emacs-lisp (defun longest-line-in-file (filename) (with-temp-buffer (insert-file-contents filename) (goto-char (point-min)) (let (longest (longest-length 0) (current-length 0)) (while (re-search-forward "^\\w.*\\w$" nil t) (setq current-length (- (line-end-position) (line-beginning-position))) (when (< longest-length current-length) (setq longest (cons (line-beginning-position) (line-end-position)) longest-length current-length))) (buffer-substring-no-properties (car longest) (cdr longest))))) #+end_src Run it from M-: (longest-line-in-file "path/to/some/file") or add an `interactive' statement if you prefer M-x. Also add some error checking, for valid file and valid input. It returns first occurence of the longest string in a file. For example in a test file attached: one two three four five six seven eight nine ten You will get "three" back. If you would like the last one (eight), change the checking condition. If you would like all of them, push them all into a list instead of a cons cell. You could also save length with each cons cell, as a pair of cons, or just push all three to a list, if you would like to use it for something later on.