From 8abac642bc9ad482a7eab0cfc495dab331fd4221 Mon Sep 17 00:00:00 2001
From: Jerome Reybert <jreybert@gmail.com>
Date: Wed, 11 Nov 2015 15:25:12 +0100
Subject: [PATCH] plugin/magit.vim: smart handle of 'q' mapping (fix #41)

if there is more than 1 window, close the window.
if this is the last window, switch to previous buffer
if there is no previous buffer, quit vim
---
 plugin/magit.vim | 14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)

diff --git a/plugin/magit.vim b/plugin/magit.vim
index 60dc9c1..28311d0 100644
--- a/plugin/magit.vim
+++ b/plugin/magit.vim
@@ -629,7 +629,7 @@ function! magit#show_magit(display, ...)
 	execute "nnoremap <buffer> <silent> " . g:magit_commit_amend_mapping . " :call magit#commit_command('CA')<cr>"
 	execute "nnoremap <buffer> <silent> " . g:magit_commit_fixup_mapping . " :call magit#commit_command('CF')<cr>"
 	execute "nnoremap <buffer> <silent> " . g:magit_ignore_mapping .       " :call magit#ignore_file()<cr>"
-	execute "nnoremap <buffer> <silent> " . g:magit_close_mapping .        " :close<cr>"
+	execute "nnoremap <buffer> <silent> " . g:magit_close_mapping .        " :call magit#close_magit()<cr>"
 	execute "nnoremap <buffer> <silent> " . g:magit_toggle_help_mapping .  " :call magit#toggle_help()<cr>"
 
 	execute "nnoremap <buffer> <silent> " . g:magit_stage_line_mapping .   " :call magit#stage_vselect()<cr>"
@@ -654,6 +654,18 @@ function! magit#show_magit(display, ...)
 	execute "normal! gg"
 endfunction
 
+function! magit#close_magit()
+	try
+		close
+	catch /^Vim\%((\a\+)\)\=:E444/
+		try
+			edit #
+		catch /^Vim\%((\a\+)\)\=:E194/
+			quit
+		endtry
+	endtry
+endfunction
+
 function! s:mg_stage_closed_file(discard)
 	if ( getline(".") =~ g:magit_file_re )
 		let list = matchlist(getline("."), g:magit_file_re)
-- 
GitLab