patch 9.1.0787: cursor position changed when using hidden terminal

Problem:  cursor position changed when using hidden terminal
          and BufFilePost autocommand (Mizuno Jan Yuta)
Solution: Save and restore cursor position

fixes: #15854
closes: #15876

Signed-off-by: Christian Brabandt <cb@256bit.org>
diff --git a/src/testdir/test_terminal3.vim b/src/testdir/test_terminal3.vim
index 3cca1b0..5865d18 100644
--- a/src/testdir/test_terminal3.vim
+++ b/src/testdir/test_terminal3.vim
@@ -975,4 +975,29 @@
   call v9.CheckLegacyAndVim9Success(lines)
 endfunc
 
+" Needs to come before Test_hidden_terminal(), why?
+func Test_autocmd_buffilepost_with_hidden_term()
+  CheckExecutable true
+  new XTestFile
+  defer delete('XTestFile')
+  call setline(1, ['one', 'two', 'three'])
+  call cursor(3, 10)
+  augroup TestCursor
+    au!
+    autocmd BufFilePost * call setbufvar(3, '&tabstop', 4)
+  augroup END
+
+  let buf = term_start(['true'], #{hidden: 1, term_finish: 'close'})
+  call term_wait(buf)
+  redraw!
+  call assert_equal('XTestFile', bufname('%'))
+  call assert_equal([0, 3, 5, 0], getpos('.'))
+
+  augroup TestCursor
+    au!
+  augroup END
+  augroup! TestCursor
+  bw! XTestFile
+endfunc
+
 " vim: shiftwidth=2 sts=2 expandtab