1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved gvimext by Tianmiao Hu
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
10 * gvimext is a DLL which is used for the "Edit with Vim" context menu
11 * extension. It implements a MS defined interface with the Shell.
13 * If you have any questions or any suggestions concerning gvimext, please
14 * contact Tianmiao Hu: tianmiao@acm.org.
22 # define _strnicmp(a, b, c) strnicmp((a), (b), (c))
25 static char *searchpath(char *name
);
28 // Always get an error while putting the following stuff to the
29 // gvimext.h file as class protected variables, give up and
30 // declare them as global stuff
31 FORMATETC fmte
= {CF_HDROP
,
32 (DVTARGETDEVICE FAR
*)NULL
,
41 /* The buffers size used to be MAX_PATH (256 bytes), but that's not always
46 // Get the name of the Gvim executable to use, with the path.
47 // When "runtime" is non-zero, we were called to find the runtime directory.
48 // Returns the path in name[BUFSIZE]. It's empty when it fails.
51 getGvimName(char *name
, int runtime
)
56 // Get the location of gvim from the registry.
58 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE
, "Software\\Vim\\Gvim", 0,
59 KEY_READ
, &keyhandle
) == ERROR_SUCCESS
)
62 if (RegQueryValueEx(keyhandle
, "path", 0, NULL
, (BYTE
*)name
, &hlen
)
67 RegCloseKey(keyhandle
);
70 // Registry didn't work, use the search path.
72 strcpy(name
, searchpath((char *)"gvim.exe"));
76 // Only when looking for the executable, not the runtime dir, we can
77 // search for the batch file or a name without a path.
79 strcpy(name
, searchpath((char *)"gvim.bat"));
81 strcpy(name
, "gvim"); // finds gvim.bat or gvim.exe
83 // avoid that Vim tries to expand wildcards in the file names
84 strcat(name
, " --literal");
89 // Get the Vim runtime directory into buf[BUFSIZE].
90 // The result is empty when it failed.
91 // When it works, the path ends in a slash or backslash.
94 getRuntimeDir(char *buf
)
101 // When no path found, use the search path to expand it.
102 if (strchr(buf
, '/') == NULL
&& strchr(buf
, '\\') == NULL
)
103 strcpy(buf
, searchpath(buf
));
105 // remove "gvim.exe" from the end
106 for (idx
= (int)strlen(buf
) - 1; idx
>= 0; idx
--)
107 if (buf
[idx
] == '\\' || buf
[idx
] == '/')
116 // GETTEXT: translated messages and menu entries
121 # define _(x) (*dyn_libintl_gettext)(x)
122 # define VIMPACKAGE "vim"
124 # define GETTEXT_DLL "libintl.dll"
128 static char *null_libintl_gettext(const char *);
129 static char *null_libintl_textdomain(const char *);
130 static char *null_libintl_bindtextdomain(const char *, const char *);
131 static int dyn_libintl_init(char *dir
);
132 static void dyn_libintl_end(void);
134 static HINSTANCE hLibintlDLL
= 0;
135 static char *(*dyn_libintl_gettext
)(const char *) = null_libintl_gettext
;
136 static char *(*dyn_libintl_textdomain
)(const char *) = null_libintl_textdomain
;
137 static char *(*dyn_libintl_bindtextdomain
)(const char *, const char *)
138 = null_libintl_bindtextdomain
;
141 // Attempt to load libintl.dll. If it doesn't work, use dummy functions.
142 // "dir" is the directory where the libintl.dll might be.
143 // Return 1 for success, 0 for failure.
146 dyn_libintl_init(char *dir
)
155 {(char *)"gettext", (FARPROC
*)&dyn_libintl_gettext
},
156 {(char *)"textdomain", (FARPROC
*)&dyn_libintl_textdomain
},
157 {(char *)"bindtextdomain", (FARPROC
*)&dyn_libintl_bindtextdomain
},
161 // No need to initialize twice.
165 // Load gettext library, first try the Vim runtime directory, then search
167 strcat(dir
, GETTEXT_DLL
);
168 hLibintlDLL
= LoadLibrary(dir
);
171 hLibintlDLL
= LoadLibrary(GETTEXT_DLL
);
176 // Get the addresses of the functions we need.
177 for (i
= 0; libintl_entry
[i
].name
!= NULL
178 && libintl_entry
[i
].ptr
!= NULL
; ++i
)
180 if ((*libintl_entry
[i
].ptr
= GetProcAddress(hLibintlDLL
,
181 libintl_entry
[i
].name
)) == NULL
)
191 dyn_libintl_end(void)
194 FreeLibrary(hLibintlDLL
);
196 dyn_libintl_gettext
= null_libintl_gettext
;
197 dyn_libintl_textdomain
= null_libintl_textdomain
;
198 dyn_libintl_bindtextdomain
= null_libintl_bindtextdomain
;
202 null_libintl_gettext(const char *msgid
)
204 return (char *)msgid
;
208 null_libintl_bindtextdomain(const char *domainname
, const char *dirname
)
214 null_libintl_textdomain(const char* domainname
)
220 // Setup for translating strings.
223 dyn_gettext_load(void)
225 char szBuff
[BUFSIZE
];
226 char szLang
[BUFSIZE
];
231 strcpy(szLang
, "LANG=");
233 // First try getting the language from the registry, this can be
234 // used to overrule the system language.
235 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE
, "Software\\Vim\\Gvim", 0,
236 KEY_READ
, &keyhandle
) == ERROR_SUCCESS
)
239 if (RegQueryValueEx(keyhandle
, "lang", 0, NULL
, (BYTE
*)szBuff
, &len
)
243 strcat(szLang
, szBuff
);
246 RegCloseKey(keyhandle
);
249 if (!gotlang
&& getenv("LANG") == NULL
)
251 // Get the language from the system.
252 // Could use LOCALE_SISO639LANGNAME, but it's not in Win95.
253 // LOCALE_SABBREVLANGNAME gives us three letters, like "enu", we use
254 // only the first two.
255 len
= GetLocaleInfo(LOCALE_USER_DEFAULT
, LOCALE_SABBREVLANGNAME
,
256 (LPTSTR
)szBuff
, BUFSIZE
);
257 if (len
>= 2 && _strnicmp(szBuff
, "en", 2) != 0)
259 // There are a few exceptions (probably more)
260 if (_strnicmp(szBuff
, "cht", 3) == 0
261 || _strnicmp(szBuff
, "zht", 3) == 0)
262 strcpy(szBuff
, "zh_TW");
263 else if (_strnicmp(szBuff
, "chs", 3) == 0
264 || _strnicmp(szBuff
, "zhc", 3) == 0)
265 strcpy(szBuff
, "zh_CN");
266 else if (_strnicmp(szBuff
, "jp", 2) == 0)
267 strcpy(szBuff
, "ja");
269 szBuff
[2] = 0; // truncate to two-letter code
270 strcat(szLang
, szBuff
);
277 // Try to locate the runtime files. The path is used to find libintl.dll
278 // and the vim.mo files.
279 getRuntimeDir(szBuff
);
282 len
= (DWORD
)strlen(szBuff
);
283 if (dyn_libintl_init(szBuff
))
285 strcpy(szBuff
+ len
, "lang");
287 (*dyn_libintl_bindtextdomain
)(VIMPACKAGE
, szBuff
);
288 (*dyn_libintl_textdomain
)(VIMPACKAGE
);
294 dyn_gettext_free(void)
298 #endif // FEAT_GETTEXT
303 UINT g_cRefThisDll
= 0; // Reference count of this DLL.
304 HINSTANCE g_hmodThisDll
= NULL
; // Handle to this DLL itself.
307 //---------------------------------------------------------------------------
309 //---------------------------------------------------------------------------
310 extern "C" int APIENTRY
311 DllMain(HINSTANCE hInstance
, DWORD dwReason
, LPVOID lpReserved
)
315 case DLL_PROCESS_ATTACH
:
316 // Extension DLL one-time initialization
317 g_hmodThisDll
= hInstance
;
320 case DLL_PROCESS_DETACH
:
331 if (g_cRefThisDll
== 0)
334 InterlockedIncrement((LPLONG
)&g_cRefThisDll
);
341 if (InterlockedDecrement((LPLONG
)&g_cRefThisDll
) == 0)
344 InterlockedDecrement((LPLONG
)&g_cRefThisDll
);
348 //---------------------------------------------------------------------------
350 //---------------------------------------------------------------------------
352 STDAPI
DllCanUnloadNow(void)
354 return (g_cRefThisDll
== 0 ? S_OK
: S_FALSE
);
357 STDAPI
DllGetClassObject(REFCLSID rclsid
, REFIID riid
, LPVOID
*ppvOut
)
361 if (IsEqualIID(rclsid
, CLSID_ShellExtension
))
363 CShellExtClassFactory
*pcf
= new CShellExtClassFactory
;
365 return pcf
->QueryInterface(riid
, ppvOut
);
368 return CLASS_E_CLASSNOTAVAILABLE
;
371 CShellExtClassFactory::CShellExtClassFactory()
378 CShellExtClassFactory::~CShellExtClassFactory()
383 STDMETHODIMP
CShellExtClassFactory::QueryInterface(REFIID riid
,
388 // Any interface on this object is the object pointer
390 if (IsEqualIID(riid
, IID_IUnknown
) || IsEqualIID(riid
, IID_IClassFactory
))
392 *ppv
= (LPCLASSFACTORY
)this;
399 return E_NOINTERFACE
;
402 STDMETHODIMP_(ULONG
) CShellExtClassFactory::AddRef()
404 return InterlockedIncrement((LPLONG
)&m_cRef
);
407 STDMETHODIMP_(ULONG
) CShellExtClassFactory::Release()
409 if (InterlockedDecrement((LPLONG
)&m_cRef
))
417 STDMETHODIMP
CShellExtClassFactory::CreateInstance(LPUNKNOWN pUnkOuter
,
423 // Shell extensions typically don't support aggregation (inheritance)
426 return CLASS_E_NOAGGREGATION
;
428 // Create the main shell extension object. The shell will then call
429 // QueryInterface with IID_IShellExtInit--this is how shell extensions are
432 LPCSHELLEXT pShellExt
= new CShellExt(); //Create the CShellExt object
434 if (NULL
== pShellExt
)
435 return E_OUTOFMEMORY
;
437 return pShellExt
->QueryInterface(riid
, ppvObj
);
441 STDMETHODIMP
CShellExtClassFactory::LockServer(BOOL fLock
)
446 // *********************** CShellExt *************************
447 CShellExt::CShellExt()
455 CShellExt::~CShellExt()
458 m_pDataObj
->Release();
463 STDMETHODIMP
CShellExt::QueryInterface(REFIID riid
, LPVOID FAR
*ppv
)
467 if (IsEqualIID(riid
, IID_IShellExtInit
) || IsEqualIID(riid
, IID_IUnknown
))
469 *ppv
= (LPSHELLEXTINIT
)this;
471 else if (IsEqualIID(riid
, IID_IContextMenu
))
473 *ppv
= (LPCONTEXTMENU
)this;
483 return E_NOINTERFACE
;
486 STDMETHODIMP_(ULONG
) CShellExt::AddRef()
488 return InterlockedIncrement((LPLONG
)&m_cRef
);
491 STDMETHODIMP_(ULONG
) CShellExt::Release()
494 if (InterlockedDecrement((LPLONG
)&m_cRef
))
504 // FUNCTION: CShellExt::Initialize(LPCITEMIDLIST, LPDATAOBJECT, HKEY)
506 // PURPOSE: Called by the shell when initializing a context menu or property
510 // pIDFolder - Specifies the parent folder
511 // pDataObj - Spefifies the set of items selected in that folder.
512 // hRegKey - Specifies the type of the focused item in the selection.
516 // NOERROR in all cases.
518 // COMMENTS: Note that at the time this function is called, we don't know
519 // (or care) what type of shell extension is being initialized.
520 // It could be a context menu or a property sheet.
523 STDMETHODIMP
CShellExt::Initialize(LPCITEMIDLIST pIDFolder
,
524 LPDATAOBJECT pDataObj
,
527 // Initialize can be called more than once
529 m_pDataObj
->Release();
531 // duplicate the object pointer and registry handle
535 m_pDataObj
= pDataObj
;
544 // FUNCTION: CShellExt::QueryContextMenu(HMENU, UINT, UINT, UINT, UINT)
546 // PURPOSE: Called by the shell just before the context menu is displayed.
547 // This is where you add your specific menu items.
550 // hMenu - Handle to the context menu
551 // indexMenu - Index of where to begin inserting menu items
552 // idCmdFirst - Lowest value for new menu ID's
553 // idCmtLast - Highest value for new menu ID's
554 // uFlags - Specifies the context of the menu event
562 STDMETHODIMP
CShellExt::QueryContextMenu(HMENU hMenu
,
568 UINT idCmd
= idCmdFirst
;
570 hres
= m_pDataObj
->GetData(&fmte
, &medium
);
572 cbFiles
= DragQueryFile((HDROP
)medium
.hGlobal
, (UINT
)-1, 0, 0);
574 // InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL);
576 // Initialize m_cntOfHWnd to 0
578 // Retrieve all the vim instances
579 EnumWindows(EnumWindowsProc
, (LPARAM
)this);
585 MF_STRING
|MF_BYPOSITION
,
587 _("Edit with &multiple Vims"));
591 MF_STRING
|MF_BYPOSITION
,
593 _("Edit with single &Vim"));
597 // Can edit up to 4 files in diff mode
600 MF_STRING
|MF_BYPOSITION
,
603 m_edit_existing_off
= 3;
606 m_edit_existing_off
= 2;
613 MF_STRING
|MF_BYPOSITION
,
615 _("Edit with &Vim"));
616 m_edit_existing_off
= 1;
619 // Now display all the vim instances
620 for (int i
= 0; i
< m_cntOfHWnd
; i
++)
625 // Obtain window title, continue if can not
626 if (GetWindowText(m_hWnd
[i
], title
, BUFSIZE
- 1) == 0)
628 // Truncate the title before the path, keep the file name
629 char *pos
= strchr(title
, '(');
632 if (pos
> title
&& pos
[-1] == ' ')
637 strncpy(temp
, _("Edit with existing Vim - "), BUFSIZE
- 1);
638 strncat(temp
, title
, BUFSIZE
- 1);
641 MF_STRING
|MF_BYPOSITION
,
645 // InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL);
647 // Must return number of menu items we added.
648 return ResultFromShort(idCmd
-idCmdFirst
);
652 // FUNCTION: CShellExt::InvokeCommand(LPCMINVOKECOMMANDINFO)
654 // PURPOSE: Called by the shell after the user has selected on of the
655 // menu items that was added in QueryContextMenu().
658 // lpcmi - Pointer to an CMINVOKECOMMANDINFO structure
666 STDMETHODIMP
CShellExt::InvokeCommand(LPCMINVOKECOMMANDINFO lpcmi
)
668 HRESULT hr
= E_INVALIDARG
;
670 // If HIWORD(lpcmi->lpVerb) then we have been called programmatically
671 // and lpVerb is a command that should be invoked. Otherwise, the shell
672 // has called us, and LOWORD(lpcmi->lpVerb) is the menu ID the user has
673 // selected. Actually, it's (menu ID - idCmdFirst) from QueryContextMenu().
674 if (!HIWORD(lpcmi
->lpVerb
))
676 UINT idCmd
= LOWORD(lpcmi
->lpVerb
);
678 if (idCmd
>= m_edit_existing_off
)
680 // Existing with vim instance
681 hr
= PushToWindow(lpcmi
->hwnd
,
686 idCmd
- m_edit_existing_off
);
693 hr
= InvokeGvim(lpcmi
->hwnd
,
700 hr
= InvokeSingleGvim(lpcmi
->hwnd
,
708 hr
= InvokeSingleGvim(lpcmi
->hwnd
,
721 STDMETHODIMP
CShellExt::PushToWindow(HWND hParent
,
722 LPCSTR pszWorkingDir
,
728 HWND hWnd
= m_hWnd
[idHWnd
];
730 // Show and bring vim instance to foreground
731 if (IsIconic(hWnd
) != 0)
732 ShowWindow(hWnd
, SW_RESTORE
);
734 ShowWindow(hWnd
, SW_SHOW
);
735 SetForegroundWindow(hWnd
);
737 // Post the selected files to the vim instance
738 PostMessage(hWnd
, WM_DROPFILES
, (WPARAM
)medium
.hGlobal
, 0);
743 STDMETHODIMP
CShellExt::GetCommandString(UINT_PTR idCmd
,
749 if (uFlags
== GCS_HELPTEXT
&& cchMax
> 35)
750 lstrcpy(pszName
, _("Edits the selected file(s) with Vim"));
755 BOOL CALLBACK
CShellExt::EnumWindowsProc(HWND hWnd
, LPARAM lParam
)
759 // First do a bunch of check
760 // No invisible window
761 if (!IsWindowVisible(hWnd
)) return TRUE
;
762 // No child window ???
763 // if (GetParent(hWnd)) return TRUE;
764 // Class name should be Vim, if failed to get class name, return
765 if (GetClassName(hWnd
, temp
, sizeof(temp
)) == 0)
767 // Compare class name to that of vim, if not, return
768 if (_strnicmp(temp
, "vim", sizeof("vim")) != 0)
770 // First check if the number of vim instance exceeds MAX_HWND
771 CShellExt
*cs
= (CShellExt
*) lParam
;
772 if (cs
->m_cntOfHWnd
>= MAX_HWND
) return TRUE
;
773 // Now we get the vim window, put it into some kind of array
774 cs
->m_hWnd
[cs
->m_cntOfHWnd
] = hWnd
;
777 return TRUE
; // continue enumeration (otherwise this would be false)
781 // This symbol is not defined in older versions of the SDK or Visual C++.
783 #ifndef VER_PLATFORM_WIN32_WINDOWS
784 # define VER_PLATFORM_WIN32_WINDOWS 1
787 static DWORD g_PlatformId
;
790 // Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
791 // VER_PLATFORM_WIN32_WINDOWS (Win95).
796 static int done
= FALSE
;
802 ovi
.dwOSVersionInfoSize
= sizeof(ovi
);
805 g_PlatformId
= ovi
.dwPlatformId
;
810 # ifndef __BORLANDC__
812 searchpath(char *name
)
814 static char widename
[2 * BUFSIZE
];
815 static char location
[2 * BUFSIZE
+ 2];
817 // There appears to be a bug in FindExecutableA() on Windows NT.
818 // Use FindExecutableW() instead...
820 if (g_PlatformId
== VER_PLATFORM_WIN32_NT
)
822 MultiByteToWideChar(CP_ACP
, 0, (LPCTSTR
)name
, -1,
823 (LPWSTR
)widename
, BUFSIZE
);
824 if (FindExecutableW((LPCWSTR
)widename
, (LPCWSTR
)"",
825 (LPWSTR
)location
) > (HINSTANCE
)32)
827 WideCharToMultiByte(CP_ACP
, 0, (LPWSTR
)location
, -1,
828 (LPSTR
)widename
, 2 * BUFSIZE
, NULL
, NULL
);
834 if (FindExecutableA((LPCTSTR
)name
, (LPCTSTR
)"",
835 (LPTSTR
)location
) > (HINSTANCE
)32)
843 STDMETHODIMP
CShellExt::InvokeGvim(HWND hParent
,
844 LPCSTR pszWorkingDir
,
849 char m_szFileUserClickedOn
[BUFSIZE
];
850 char cmdStr
[BUFSIZE
];
853 for (i
= 0; i
< cbFiles
; i
++)
855 DragQueryFile((HDROP
)medium
.hGlobal
,
857 m_szFileUserClickedOn
,
858 sizeof(m_szFileUserClickedOn
));
860 getGvimName(cmdStr
, 0);
861 strcat(cmdStr
, " \"");
863 if ((strlen(cmdStr
) + strlen(m_szFileUserClickedOn
) + 2) < BUFSIZE
)
865 strcat(cmdStr
, m_szFileUserClickedOn
);
866 strcat(cmdStr
, "\"");
869 PROCESS_INFORMATION pi
;
871 ZeroMemory(&si
, sizeof(si
));
874 // Start the child process.
875 if (!CreateProcess(NULL
, // No module name (use command line).
876 cmdStr
, // Command line.
877 NULL
, // Process handle not inheritable.
878 NULL
, // Thread handle not inheritable.
879 FALSE
, // Set handle inheritance to FALSE.
880 0, // No creation flags.
881 NULL
, // Use parent's environment block.
882 NULL
, // Use parent's starting directory.
883 &si
, // Pointer to STARTUPINFO structure.
884 &pi
) // Pointer to PROCESS_INFORMATION structure.
889 _("Error creating process: Check if gvim is in your path!"),
890 _("gvimext.dll error"),
895 CloseHandle( pi
.hProcess
);
896 CloseHandle( pi
.hThread
);
903 _("Path length too long!"),
904 _("gvimext.dll error"),
913 STDMETHODIMP
CShellExt::InvokeSingleGvim(HWND hParent
,
914 LPCSTR pszWorkingDir
,
920 char m_szFileUserClickedOn
[BUFSIZE
];
927 cmdStr
= (char *)malloc(cmdlen
);
928 getGvimName(cmdStr
, 0);
930 strcat(cmdStr
, " -d");
931 for (i
= 0; i
< cbFiles
; i
++)
933 DragQueryFile((HDROP
)medium
.hGlobal
,
935 m_szFileUserClickedOn
,
936 sizeof(m_szFileUserClickedOn
));
938 len
= strlen(cmdStr
) + strlen(m_szFileUserClickedOn
) + 4;
941 cmdlen
= len
+ BUFSIZE
;
942 cmdStr
= (char *)realloc(cmdStr
, cmdlen
);
944 strcat(cmdStr
, " \"");
945 strcat(cmdStr
, m_szFileUserClickedOn
);
946 strcat(cmdStr
, "\"");
950 PROCESS_INFORMATION pi
;
952 ZeroMemory(&si
, sizeof(si
));
955 // Start the child process.
956 if (!CreateProcess(NULL
, // No module name (use command line).
957 cmdStr
, // Command line.
958 NULL
, // Process handle not inheritable.
959 NULL
, // Thread handle not inheritable.
960 FALSE
, // Set handle inheritance to FALSE.
961 0, // No creation flags.
962 NULL
, // Use parent's environment block.
963 NULL
, // Use parent's starting directory.
964 &si
, // Pointer to STARTUPINFO structure.
965 &pi
) // Pointer to PROCESS_INFORMATION structure.
970 _("Error creating process: Check if gvim is in your path!"),
971 _("gvimext.dll error"),
976 CloseHandle(pi
.hProcess
);
977 CloseHandle(pi
.hThread
);