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 getGvimNameW(wchar_t *nameW)
93 name = (char *)malloc(BUFSIZE);
95 mbstowcs(nameW, name, BUFSIZE);
100 // Get the Vim runtime directory into buf[BUFSIZE].
101 // The result is empty when it failed.
102 // When it works, the path ends in a slash or backslash.
105 getRuntimeDir(char *buf)
112 // When no path found, use the search path to expand it.
113 if (strchr(buf, '/') == NULL && strchr(buf, '\\') == NULL)
114 strcpy(buf, searchpath(buf));
116 // remove "gvim.exe" from the end
117 for (idx = (int)strlen(buf) - 1; idx >= 0; idx--)
118 if (buf[idx] == '\\' || buf[idx] == '/')
127 // GETTEXT: translated messages and menu entries
132 # define _(x) (*dyn_libintl_gettext)(x)
133 # define VIMPACKAGE "vim"
135 # define GETTEXT_DLL "libintl.dll"
139 static char *null_libintl_gettext(const char *);
140 static char *null_libintl_textdomain(const char *);
141 static char *null_libintl_bindtextdomain(const char *, const char *);
142 static int dyn_libintl_init(char *dir);
143 static void dyn_libintl_end(void);
145 static wchar_t *oldenv = NULL;
146 static HINSTANCE hLibintlDLL = 0;
147 static char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
148 static char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
149 static char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
150 = null_libintl_bindtextdomain;
153 // Attempt to load libintl.dll. If it doesn't work, use dummy functions.
154 // "dir" is the directory where the libintl.dll might be.
155 // Return 1 for success, 0 for failure.
158 dyn_libintl_init(char *dir)
167 {(char *)"gettext", (FARPROC*)&dyn_libintl_gettext},
168 {(char *)"textdomain", (FARPROC*)&dyn_libintl_textdomain},
169 {(char *)"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
173 // No need to initialize twice.
177 // Load gettext library, first try the Vim runtime directory, then search
179 strcat(dir, GETTEXT_DLL);
180 hLibintlDLL = LoadLibrary(dir);
183 hLibintlDLL = LoadLibrary(GETTEXT_DLL);
188 // Get the addresses of the functions we need.
189 for (i = 0; libintl_entry[i].name != NULL
190 && libintl_entry[i].ptr != NULL; ++i)
192 if ((*libintl_entry[i].ptr = GetProcAddress(hLibintlDLL,
193 libintl_entry[i].name)) == NULL)
203 dyn_libintl_end(void)
206 FreeLibrary(hLibintlDLL);
208 dyn_libintl_gettext = null_libintl_gettext;
209 dyn_libintl_textdomain = null_libintl_textdomain;
210 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
214 null_libintl_gettext(const char *msgid)
216 return (char *)msgid;
220 null_libintl_bindtextdomain(const char * /* domainname */, const char * /* dirname */)
226 null_libintl_textdomain(const char* /* domainname */)
232 // Setup for translating strings.
235 dyn_gettext_load(void)
237 char szBuff[BUFSIZE];
238 char szLang[BUFSIZE];
243 strcpy(szLang, "LANG=");
245 // First try getting the language from the registry, this can be
246 // used to overrule the system language.
247 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Vim\\Gvim", 0,
248 KEY_READ, &keyhandle) == ERROR_SUCCESS)
251 if (RegQueryValueEx(keyhandle, "lang", 0, NULL, (BYTE*)szBuff, &len)
255 strcat(szLang, szBuff);
258 RegCloseKey(keyhandle);
261 if (!gotlang && getenv("LANG") == NULL)
263 // Get the language from the system.
264 // Could use LOCALE_SISO639LANGNAME, but it's not in Win95.
265 // LOCALE_SABBREVLANGNAME gives us three letters, like "enu", we use
266 // only the first two.
267 len = GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SABBREVLANGNAME,
268 (LPTSTR)szBuff, BUFSIZE);
269 if (len >= 2 && _strnicmp(szBuff, "en", 2) != 0)
271 // There are a few exceptions (probably more)
272 if (_strnicmp(szBuff, "cht", 3) == 0
273 || _strnicmp(szBuff, "zht", 3) == 0)
274 strcpy(szBuff, "zh_TW");
275 else if (_strnicmp(szBuff, "chs", 3) == 0
276 || _strnicmp(szBuff, "zhc", 3) == 0)
277 strcpy(szBuff, "zh_CN");
278 else if (_strnicmp(szBuff, "jp", 2) == 0)
279 strcpy(szBuff, "ja");
281 szBuff[2] = 0; // truncate to two-letter code
282 strcat(szLang, szBuff);
289 // Try to locate the runtime files. The path is used to find libintl.dll
290 // and the vim.mo files.
291 getRuntimeDir(szBuff);
294 len = (DWORD)strlen(szBuff);
295 if (dyn_libintl_init(szBuff))
297 strcpy(szBuff + len, "lang");
299 (*dyn_libintl_bindtextdomain)(VIMPACKAGE, szBuff);
300 (*dyn_libintl_textdomain)(VIMPACKAGE);
306 dyn_gettext_free(void)
310 #endif // FEAT_GETTEXT
315 UINT g_cRefThisDll = 0; // Reference count of this DLL.
316 HINSTANCE g_hmodThisDll = NULL; // Handle to this DLL itself.
319 //---------------------------------------------------------------------------
321 //---------------------------------------------------------------------------
322 extern "C" int APIENTRY
323 DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /* lpReserved */)
327 case DLL_PROCESS_ATTACH:
328 // Extension DLL one-time initialization
329 g_hmodThisDll = hInstance;
332 case DLL_PROCESS_DETACH:
343 if (g_cRefThisDll == 0) {
345 oldenv = GetEnvironmentStringsW();
348 InterlockedIncrement((LPLONG)&g_cRefThisDll);
355 if (InterlockedDecrement((LPLONG)&g_cRefThisDll) == 0) {
357 if (oldenv != NULL) {
358 FreeEnvironmentStringsW(oldenv);
363 InterlockedDecrement((LPLONG)&g_cRefThisDll);
367 //---------------------------------------------------------------------------
369 //---------------------------------------------------------------------------
371 STDAPI DllCanUnloadNow(void)
373 return (g_cRefThisDll == 0 ? S_OK : S_FALSE);
376 STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppvOut)
380 if (IsEqualIID(rclsid, CLSID_ShellExtension))
382 CShellExtClassFactory *pcf = new CShellExtClassFactory;
384 return pcf->QueryInterface(riid, ppvOut);
387 return CLASS_E_CLASSNOTAVAILABLE;
390 CShellExtClassFactory::CShellExtClassFactory()
397 CShellExtClassFactory::~CShellExtClassFactory()
402 STDMETHODIMP CShellExtClassFactory::QueryInterface(REFIID riid,
407 // Any interface on this object is the object pointer
409 if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IClassFactory))
411 *ppv = (LPCLASSFACTORY)this;
418 return E_NOINTERFACE;
421 STDMETHODIMP_(ULONG) CShellExtClassFactory::AddRef()
423 return InterlockedIncrement((LPLONG)&m_cRef);
426 STDMETHODIMP_(ULONG) CShellExtClassFactory::Release()
428 if (InterlockedDecrement((LPLONG)&m_cRef))
436 STDMETHODIMP CShellExtClassFactory::CreateInstance(LPUNKNOWN pUnkOuter,
442 // Shell extensions typically don't support aggregation (inheritance)
445 return CLASS_E_NOAGGREGATION;
447 // Create the main shell extension object. The shell will then call
448 // QueryInterface with IID_IShellExtInit--this is how shell extensions are
451 LPCSHELLEXT pShellExt = new CShellExt(); //Create the CShellExt object
453 if (NULL == pShellExt)
454 return E_OUTOFMEMORY;
456 return pShellExt->QueryInterface(riid, ppvObj);
460 STDMETHODIMP CShellExtClassFactory::LockServer(BOOL /* fLock */)
465 // *********************** CShellExt *************************
466 CShellExt::CShellExt()
474 CShellExt::~CShellExt()
477 m_pDataObj->Release();
482 STDMETHODIMP CShellExt::QueryInterface(REFIID riid, LPVOID FAR *ppv)
486 if (IsEqualIID(riid, IID_IShellExtInit) || IsEqualIID(riid, IID_IUnknown))
488 *ppv = (LPSHELLEXTINIT)this;
490 else if (IsEqualIID(riid, IID_IContextMenu))
492 *ppv = (LPCONTEXTMENU)this;
502 return E_NOINTERFACE;
505 STDMETHODIMP_(ULONG) CShellExt::AddRef()
507 return InterlockedIncrement((LPLONG)&m_cRef);
510 STDMETHODIMP_(ULONG) CShellExt::Release()
513 if (InterlockedDecrement((LPLONG)&m_cRef))
523 // FUNCTION: CShellExt::Initialize(LPCITEMIDLIST, LPDATAOBJECT, HKEY)
525 // PURPOSE: Called by the shell when initializing a context menu or property
529 // pIDFolder - Specifies the parent folder
530 // pDataObj - Spefifies the set of items selected in that folder.
531 // hRegKey - Specifies the type of the focused item in the selection.
535 // NOERROR in all cases.
537 // COMMENTS: Note that at the time this function is called, we don't know
538 // (or care) what type of shell extension is being initialized.
539 // It could be a context menu or a property sheet.
542 STDMETHODIMP CShellExt::Initialize(LPCITEMIDLIST /* pIDFolder */,
543 LPDATAOBJECT pDataObj,
546 // Initialize can be called more than once
548 m_pDataObj->Release();
550 // duplicate the object pointer and registry handle
554 m_pDataObj = pDataObj;
563 // FUNCTION: CShellExt::QueryContextMenu(HMENU, UINT, UINT, UINT, UINT)
565 // PURPOSE: Called by the shell just before the context menu is displayed.
566 // This is where you add your specific menu items.
569 // hMenu - Handle to the context menu
570 // indexMenu - Index of where to begin inserting menu items
571 // idCmdFirst - Lowest value for new menu ID's
572 // idCmtLast - Highest value for new menu ID's
573 // uFlags - Specifies the context of the menu event
581 STDMETHODIMP CShellExt::QueryContextMenu(HMENU hMenu,
584 UINT /* idCmdLast */,
587 UINT idCmd = idCmdFirst;
589 hres = m_pDataObj->GetData(&fmte, &medium);
591 cbFiles = DragQueryFile((HDROP)medium.hGlobal, (UINT)-1, 0, 0);
593 // InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL);
595 // Initialize m_cntOfHWnd to 0
599 bool showExisting = true;
601 // Check whether "Edit with existing Vim" entries are disabled.
602 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Vim\\Gvim", 0,
603 KEY_READ, &keyhandle) == ERROR_SUCCESS)
605 if (RegQueryValueEx(keyhandle, "DisableEditWithExisting", 0, NULL,
606 NULL, NULL) == ERROR_SUCCESS)
607 showExisting = false;
608 RegCloseKey(keyhandle);
611 // Retrieve all the vim instances, unless disabled.
613 EnumWindows(EnumWindowsProc, (LPARAM)this);
619 MF_STRING|MF_BYPOSITION,
621 _("Edit with &multiple Vims"));
625 MF_STRING|MF_BYPOSITION,
627 _("Edit with single &Vim"));
631 // Can edit up to 4 files in diff mode
634 MF_STRING|MF_BYPOSITION,
637 m_edit_existing_off = 3;
640 m_edit_existing_off = 2;
647 MF_STRING|MF_BYPOSITION,
649 _("Edit with &Vim"));
650 m_edit_existing_off = 1;
653 // Now display all the vim instances
654 for (int i = 0; i < m_cntOfHWnd; i++)
659 // Obtain window title, continue if can not
660 if (GetWindowText(m_hWnd[i], title, BUFSIZE - 1) == 0)
662 // Truncate the title before the path, keep the file name
663 char *pos = strchr(title, '(');
666 if (pos > title && pos[-1] == ' ')
671 strncpy(temp, _("Edit with existing Vim - "), BUFSIZE - 1);
672 temp[BUFSIZE - 1] = '\0';
673 strncat(temp, title, BUFSIZE - 1 - strlen(temp));
674 temp[BUFSIZE - 1] = '\0';
677 MF_STRING|MF_BYPOSITION,
681 // InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL);
683 // Must return number of menu items we added.
684 return ResultFromShort(idCmd-idCmdFirst);
688 // FUNCTION: CShellExt::InvokeCommand(LPCMINVOKECOMMANDINFO)
690 // PURPOSE: Called by the shell after the user has selected on of the
691 // menu items that was added in QueryContextMenu().
694 // lpcmi - Pointer to an CMINVOKECOMMANDINFO structure
702 STDMETHODIMP CShellExt::InvokeCommand(LPCMINVOKECOMMANDINFO lpcmi)
704 HRESULT hr = E_INVALIDARG;
706 // If HIWORD(lpcmi->lpVerb) then we have been called programmatically
707 // and lpVerb is a command that should be invoked. Otherwise, the shell
708 // has called us, and LOWORD(lpcmi->lpVerb) is the menu ID the user has
709 // selected. Actually, it's (menu ID - idCmdFirst) from QueryContextMenu().
710 if (!HIWORD(lpcmi->lpVerb))
712 UINT idCmd = LOWORD(lpcmi->lpVerb);
714 if (idCmd >= m_edit_existing_off)
716 // Existing with vim instance
717 hr = PushToWindow(lpcmi->hwnd,
722 idCmd - m_edit_existing_off);
729 hr = InvokeGvim(lpcmi->hwnd,
736 hr = InvokeSingleGvim(lpcmi->hwnd,
744 hr = InvokeSingleGvim(lpcmi->hwnd,
757 STDMETHODIMP CShellExt::PushToWindow(HWND /* hParent */,
758 LPCSTR /* pszWorkingDir */,
760 LPCSTR /* pszParam */,
764 HWND hWnd = m_hWnd[idHWnd];
766 // Show and bring vim instance to foreground
767 if (IsIconic(hWnd) != 0)
768 ShowWindow(hWnd, SW_RESTORE);
770 ShowWindow(hWnd, SW_SHOW);
771 SetForegroundWindow(hWnd);
773 // Post the selected files to the vim instance
774 PostMessage(hWnd, WM_DROPFILES, (WPARAM)medium.hGlobal, 0);
779 STDMETHODIMP CShellExt::GetCommandString(UINT_PTR /* idCmd */,
781 UINT FAR * /* reserved */,
785 if (uFlags == GCS_HELPTEXT && cchMax > 35)
786 lstrcpy(pszName, _("Edits the selected file(s) with Vim"));
791 BOOL CALLBACK CShellExt::EnumWindowsProc(HWND hWnd, LPARAM lParam)
795 // First do a bunch of check
796 // No invisible window
797 if (!IsWindowVisible(hWnd)) return TRUE;
798 // No child window ???
799 // if (GetParent(hWnd)) return TRUE;
800 // Class name should be Vim, if failed to get class name, return
801 if (GetClassName(hWnd, temp, sizeof(temp)) == 0)
803 // Compare class name to that of vim, if not, return
804 if (_strnicmp(temp, "vim", sizeof("vim")) != 0)
806 // First check if the number of vim instance exceeds MAX_HWND
807 CShellExt *cs = (CShellExt*) lParam;
808 if (cs->m_cntOfHWnd >= MAX_HWND) return TRUE;
809 // Now we get the vim window, put it into some kind of array
810 cs->m_hWnd[cs->m_cntOfHWnd] = hWnd;
813 return TRUE; // continue enumeration (otherwise this would be false)
817 // This symbol is not defined in older versions of the SDK or Visual C++.
819 #ifndef VER_PLATFORM_WIN32_WINDOWS
820 # define VER_PLATFORM_WIN32_WINDOWS 1
823 static DWORD g_PlatformId;
826 // Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
827 // VER_PLATFORM_WIN32_WINDOWS (Win95).
832 static int done = FALSE;
838 ovi.dwOSVersionInfoSize = sizeof(ovi);
841 g_PlatformId = ovi.dwPlatformId;
846 # ifndef __BORLANDC__
848 searchpath(char *name)
850 static char widename[2 * BUFSIZE];
851 static char location[2 * BUFSIZE + 2];
853 // There appears to be a bug in FindExecutableA() on Windows NT.
854 // Use FindExecutableW() instead...
856 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
858 MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)name, -1,
859 (LPWSTR)widename, BUFSIZE);
860 if (FindExecutableW((LPCWSTR)widename, (LPCWSTR)"",
861 (LPWSTR)location) > (HINSTANCE)32)
863 WideCharToMultiByte(CP_ACP, 0, (LPWSTR)location, -1,
864 (LPSTR)widename, 2 * BUFSIZE, NULL, NULL);
870 if (FindExecutableA((LPCTSTR)name, (LPCTSTR)"",
871 (LPTSTR)location) > (HINSTANCE)32)
879 STDMETHODIMP CShellExt::InvokeGvim(HWND hParent,
880 LPCSTR /* pszWorkingDir */,
882 LPCSTR /* pszParam */,
885 wchar_t m_szFileUserClickedOn[BUFSIZE];
886 wchar_t cmdStrW[BUFSIZE];
889 for (i = 0; i < cbFiles; i++)
891 DragQueryFileW((HDROP)medium.hGlobal,
893 m_szFileUserClickedOn,
894 sizeof(m_szFileUserClickedOn));
896 getGvimNameW(cmdStrW);
897 wcscat(cmdStrW, L" \"");
899 if ((wcslen(cmdStrW) + wcslen(m_szFileUserClickedOn) + 2) < BUFSIZE)
901 wcscat(cmdStrW, m_szFileUserClickedOn);
902 wcscat(cmdStrW, L"\"");
905 PROCESS_INFORMATION pi;
907 ZeroMemory(&si, sizeof(si));
910 // Start the child process.
911 if (!CreateProcessW(NULL, // No module name (use command line).
912 cmdStrW, // Command line.
913 NULL, // Process handle not inheritable.
914 NULL, // Thread handle not inheritable.
915 FALSE, // Set handle inheritance to FALSE.
916 oldenv == NULL ? 0 : CREATE_UNICODE_ENVIRONMENT,
917 oldenv, // Use unmodified environment block.
918 NULL, // Use parent's starting directory.
919 &si, // Pointer to STARTUPINFO structure.
920 &pi) // Pointer to PROCESS_INFORMATION structure.
925 _("Error creating process: Check if gvim is in your path!"),
926 _("gvimext.dll error"),
931 CloseHandle( pi.hProcess );
932 CloseHandle( pi.hThread );
939 _("Path length too long!"),
940 _("gvimext.dll error"),
949 STDMETHODIMP CShellExt::InvokeSingleGvim(HWND hParent,
950 LPCSTR /* pszWorkingDir */,
952 LPCSTR /* pszParam */,
956 wchar_t m_szFileUserClickedOn[BUFSIZE];
963 cmdStrW = (wchar_t *) malloc(cmdlen * sizeof(wchar_t));
964 getGvimNameW(cmdStrW);
967 wcscat(cmdStrW, L" -d");
968 for (i = 0; i < cbFiles; i++)
970 DragQueryFileW((HDROP)medium.hGlobal,
972 m_szFileUserClickedOn,
973 sizeof(m_szFileUserClickedOn));
975 len = wcslen(cmdStrW) + wcslen(m_szFileUserClickedOn) + 4;
978 cmdlen = len + BUFSIZE;
979 cmdStrW = (wchar_t *)realloc(cmdStrW, cmdlen * sizeof(wchar_t));
981 wcscat(cmdStrW, L" \"");
982 wcscat(cmdStrW, m_szFileUserClickedOn);
983 wcscat(cmdStrW, L"\"");
987 PROCESS_INFORMATION pi;
989 ZeroMemory(&si, sizeof(si));
992 // Start the child process.
993 if (!CreateProcessW(NULL, // No module name (use command line).
994 cmdStrW, // Command line.
995 NULL, // Process handle not inheritable.
996 NULL, // Thread handle not inheritable.
997 FALSE, // Set handle inheritance to FALSE.
998 oldenv == NULL ? 0 : CREATE_UNICODE_ENVIRONMENT,
999 oldenv, // Use unmodified environment block.
1000 NULL, // Use parent's starting directory.
1001 &si, // Pointer to STARTUPINFO structure.
1002 &pi) // Pointer to PROCESS_INFORMATION structure.
1007 _("Error creating process: Check if gvim is in your path!"),
1008 _("gvimext.dll error"),
1013 CloseHandle(pi.hProcess);
1014 CloseHandle(pi.hThread);