As discussed on emacs-helpĀ  I'm posting this example here which reorders the file and runs slowly. Though it's an sql dump file with long lines, the file is navigable without any problem or slowness. Only this snippet runs slowly. Here's the snippet: (progn (goto-char (point-min)) (when (search-forward "INSERT INTO `test2` (`aa`, `bb`) VALUES" nil t) (beginning-of-line) (while (looking-at "INSERT INTO `test2`.+,\\([0-9]+\\));") (let ((item (match-string 1)) (line (buffer-substring (line-beginning-position) (line-end-position)))) (message item) (save-excursion (re-search-backward (concat "INSERT INTO `test1`.+" "VALUES (" item ",")) (end-of-line) (insert "\n" line)) (delete-region (line-beginning-position) (1+ (line-end-position))) )))) And the example file to run it on is attached. (anonymized sql dump)