patch 8.0.1540: popup menu positioning fails with longer string

Problem:    Popup menu positioning fails with longer string.
Solution:   Only align with right side of window when width is less than
            'pumwidth' (closes #2661)
diff --git a/src/testdir/dumps/Test_popup_position_04.dump b/src/testdir/dumps/Test_popup_position_04.dump
new file mode 100644
index 0000000..b1a3af2
--- /dev/null
+++ b/src/testdir/dumps/Test_popup_position_04.dump
@@ -0,0 +1,10 @@
+|1+0&#ffffff0|2|3|4|5|6|7|8|9|_|1|2|3|4|5|6|7|8|9|_|1|2|3|4|5|6|7|8|9|_|1|2|3|4|5|6|7||+1&&|1+0&&|2|3|4|5|6|7|8|9|_|1|2|3|4|5|6|7|8|9|_|1|2|3|4|5|6|7|8|9|_|1|2|3|4|5|6|7
+|8|9|_|a| @32||+1&&|8+0&&|9|_|a| @32
+|1|2|3|4|5|6|7|8|9|_|1|2|3|4|5|6|7|8|9|_|1|2|3|4|5|6|7|8|9|_|1|2|3|4|5|6|7||+1&&|1+0&&|2|3|4|5|6|7|8|9|_|1|2|3|4|5|6|7|8|9|_|1|2|3|4|5|6|7|8|9|_|1|2|3|4|5|6|7
+|8|9|_|b| @32||+1&&|8+0&&|9|_|b| @32
+@12|1|2|3|4|5|6|7|8|9|_|1|2|3|4|5|6|7|8|9|_|1|2|3|4|5||+1&&| +0&&@11|1|2|3|4|5|6|7|8|9|_|1|2|3|4|5|6|7|8|9|_|1|2|3|4|5
+|6|7|8|9|_|1|2|3|4|5|6|7|8|9|_|a| @20||+1&&|6+0&&|7|8|9|_|1|2|3|4|5|6|7|8|9|_|a| @20
+|~+0#4040ff13&| @35||+1#0000000&|~+0#4040ff13&| @9| +0#0000001#e0e0e08|1|2|3|4|5|6|7|8|9|_|1|2|3|4|5|6|7|8|9|_|1|2|3|4|5
+|~+0#4040ff13#ffffff0| @35||+1#0000000&|~+0#4040ff13&| @9| +0#0000001#ffd7ff255|1|2|3|4|5|6|7|8|9|_|1|2|3|4|5|6|7|8|9|_|1|2|3|4|5
+|~+0#4040ff13#ffffff0| @35||+1#0000000&|~+0#4040ff13&| @35
+|~| @35||+1#0000000&|~+0#4040ff13&| @35
diff --git a/src/testdir/screendump.vim b/src/testdir/screendump.vim
index 584f9ac..1016646 100644
--- a/src/testdir/screendump.vim
+++ b/src/testdir/screendump.vim
@@ -48,7 +48,7 @@
 " Stop a Vim running in terminal buffer "buf".
 func StopVimInTerminal(buf)
   call assert_equal("running", term_getstatus(a:buf))
-  call term_sendkeys(a:buf, ":qa!\<cr>")
+  call term_sendkeys(a:buf, "\<Esc>\<Esc>:qa!\<cr>")
   call WaitFor('term_getstatus(' . a:buf . ') == "finished"')
   only!
 endfunc
diff --git a/src/testdir/test_popup.vim b/src/testdir/test_popup.vim
index b0024e6..499b08b 100644
--- a/src/testdir/test_popup.vim
+++ b/src/testdir/test_popup.vim
@@ -772,6 +772,15 @@
   call term_sendkeys(buf, "GA\<C-N>")
   call VerifyScreenDump(buf, 'Test_popup_position_03', {'rows': 8})
 
+  " completed text wider than the window and 'pumwidth' smaller than available
+  " space
+  call term_sendkeys(buf, "\<Esc>u")
+  call term_sendkeys(buf, ":set pumwidth=20\<CR>")
+  call term_sendkeys(buf, "ggI123456789_\<Esc>")
+  call term_sendkeys(buf, "jI123456789_\<Esc>")
+  call term_sendkeys(buf, "GA\<C-N>")
+  call VerifyScreenDump(buf, 'Test_popup_position_04', {'rows': 10})
+  
   call term_sendkeys(buf, "\<Esc>u")
   call StopVimInTerminal(buf)
   call delete('Xtest')