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
)
100 * Get runtime path from the registry if entry exists.
102 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE
, "Software\\Vim\\Gvim", 0,
103 KEY_READ
, &hkey
) == ERROR_SUCCESS
)
105 DWORD dwLen
= MAX_PATH
;
106 LONG result
= RegQueryValueEx(hkey
, "runtime", 0, NULL
, (BYTE
*)buf
,
110 if (result
== ERROR_SUCCESS
)
112 /* Add directory separater if needs */
113 if (dwLen
> 1 && !strchr("\\/", buf
[dwLen
- 2]))
115 buf
[dwLen
- 1] = '\\';
118 return; /* success to obtain runtime entry */
125 // When no path found, use the search path to expand it.
126 if (strchr(buf
, '/') == NULL
&& strchr(buf
, '\\') == NULL
)
127 strcpy(buf
, searchpath(buf
));
129 // remove "gvim.exe" from the end
130 for (idx
= (int)strlen(buf
) - 1; idx
>= 0; idx
--)
131 if (buf
[idx
] == '\\' || buf
[idx
] == '/')
140 // GETTEXT: translated messages and menu entries
145 # define _(x) (*dyn_libintl_gettext)(x)
146 # define VIMPACKAGE "vim"
148 # define GETTEXT_DLL "libintl.dll"
152 static char *null_libintl_gettext(const char *);
153 static char *null_libintl_textdomain(const char *);
154 static char *null_libintl_bindtextdomain(const char *, const char *);
155 static int dyn_libintl_init(char *dir
);
156 static void dyn_libintl_end(void);
158 static HINSTANCE hLibintlDLL
= 0;
159 static char *(*dyn_libintl_gettext
)(const char *) = null_libintl_gettext
;
160 static char *(*dyn_libintl_textdomain
)(const char *) = null_libintl_textdomain
;
161 static char *(*dyn_libintl_bindtextdomain
)(const char *, const char *)
162 = null_libintl_bindtextdomain
;
165 // Attempt to load libintl.dll. If it doesn't work, use dummy functions.
166 // "dir" is the directory where the libintl.dll might be.
167 // Return 1 for success, 0 for failure.
170 dyn_libintl_init(char *dir
)
179 {(char *)"gettext", (FARPROC
*)&dyn_libintl_gettext
},
180 {(char *)"textdomain", (FARPROC
*)&dyn_libintl_textdomain
},
181 {(char *)"bindtextdomain", (FARPROC
*)&dyn_libintl_bindtextdomain
},
185 // No need to initialize twice.
189 // Load gettext library, first try the Vim runtime directory, then search
191 strcat(dir
, GETTEXT_DLL
);
192 hLibintlDLL
= LoadLibrary(dir
);
195 hLibintlDLL
= LoadLibrary(GETTEXT_DLL
);
200 // Get the addresses of the functions we need.
201 for (i
= 0; libintl_entry
[i
].name
!= NULL
202 && libintl_entry
[i
].ptr
!= NULL
; ++i
)
204 if ((*libintl_entry
[i
].ptr
= GetProcAddress(hLibintlDLL
,
205 libintl_entry
[i
].name
)) == NULL
)
215 dyn_libintl_end(void)
218 FreeLibrary(hLibintlDLL
);
220 dyn_libintl_gettext
= null_libintl_gettext
;
221 dyn_libintl_textdomain
= null_libintl_textdomain
;
222 dyn_libintl_bindtextdomain
= null_libintl_bindtextdomain
;
226 null_libintl_gettext(const char *msgid
)
228 return (char *)msgid
;
232 null_libintl_bindtextdomain(const char * /* domainname */, const char * /* dirname */)
238 null_libintl_textdomain(const char* /* domainname */)
244 // Setup for translating strings.
247 dyn_gettext_load(void)
249 char szBuff
[BUFSIZE
];
250 char szLang
[BUFSIZE
];
255 strcpy(szLang
, "LANG=");
257 // First try getting the language from the registry, this can be
258 // used to overrule the system language.
259 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE
, "Software\\Vim\\Gvim", 0,
260 KEY_READ
, &keyhandle
) == ERROR_SUCCESS
)
263 if (RegQueryValueEx(keyhandle
, "lang", 0, NULL
, (BYTE
*)szBuff
, &len
)
267 strcat(szLang
, szBuff
);
270 RegCloseKey(keyhandle
);
273 if (!gotlang
&& getenv("LANG") == NULL
)
275 // Get the language from the system.
276 // Could use LOCALE_SISO639LANGNAME, but it's not in Win95.
277 // LOCALE_SABBREVLANGNAME gives us three letters, like "enu", we use
278 // only the first two.
279 len
= GetLocaleInfo(LOCALE_USER_DEFAULT
, LOCALE_SABBREVLANGNAME
,
280 (LPTSTR
)szBuff
, BUFSIZE
);
281 if (len
>= 2 && _strnicmp(szBuff
, "en", 2) != 0)
283 // There are a few exceptions (probably more)
284 if (_strnicmp(szBuff
, "cht", 3) == 0
285 || _strnicmp(szBuff
, "zht", 3) == 0)
286 strcpy(szBuff
, "zh_TW");
287 else if (_strnicmp(szBuff
, "chs", 3) == 0
288 || _strnicmp(szBuff
, "zhc", 3) == 0)
289 strcpy(szBuff
, "zh_CN");
290 else if (_strnicmp(szBuff
, "jp", 2) == 0)
291 strcpy(szBuff
, "ja");
293 szBuff
[2] = 0; // truncate to two-letter code
294 strcat(szLang
, szBuff
);
301 // Try to locate the runtime files. The path is used to find libintl.dll
302 // and the vim.mo files.
303 getRuntimeDir(szBuff
);
306 len
= (DWORD
)strlen(szBuff
);
307 if (dyn_libintl_init(szBuff
))
309 strcpy(szBuff
+ len
, "lang");
311 (*dyn_libintl_bindtextdomain
)(VIMPACKAGE
, szBuff
);
312 (*dyn_libintl_textdomain
)(VIMPACKAGE
);
318 dyn_gettext_free(void)
322 #endif // FEAT_GETTEXT
327 UINT g_cRefThisDll
= 0; // Reference count of this DLL.
328 HINSTANCE g_hmodThisDll
= NULL
; // Handle to this DLL itself.
331 //---------------------------------------------------------------------------
333 //---------------------------------------------------------------------------
334 extern "C" int APIENTRY
335 DllMain(HINSTANCE hInstance
, DWORD dwReason
, LPVOID
/* lpReserved */)
339 case DLL_PROCESS_ATTACH
:
340 // Extension DLL one-time initialization
341 g_hmodThisDll
= hInstance
;
344 case DLL_PROCESS_DETACH
:
355 if (g_cRefThisDll
== 0)
358 InterlockedIncrement((LPLONG
)&g_cRefThisDll
);
365 if (InterlockedDecrement((LPLONG
)&g_cRefThisDll
) == 0)
368 InterlockedDecrement((LPLONG
)&g_cRefThisDll
);
372 //---------------------------------------------------------------------------
374 //---------------------------------------------------------------------------
376 STDAPI
DllCanUnloadNow(void)
378 return (g_cRefThisDll
== 0 ? S_OK
: S_FALSE
);
381 STDAPI
DllGetClassObject(REFCLSID rclsid
, REFIID riid
, LPVOID
*ppvOut
)
385 if (IsEqualIID(rclsid
, CLSID_ShellExtension
))
387 CShellExtClassFactory
*pcf
= new CShellExtClassFactory
;
389 return pcf
->QueryInterface(riid
, ppvOut
);
392 return CLASS_E_CLASSNOTAVAILABLE
;
395 CShellExtClassFactory::CShellExtClassFactory()
402 CShellExtClassFactory::~CShellExtClassFactory()
407 STDMETHODIMP
CShellExtClassFactory::QueryInterface(REFIID riid
,
412 // Any interface on this object is the object pointer
414 if (IsEqualIID(riid
, IID_IUnknown
) || IsEqualIID(riid
, IID_IClassFactory
))
416 *ppv
= (LPCLASSFACTORY
)this;
423 return E_NOINTERFACE
;
426 STDMETHODIMP_(ULONG
) CShellExtClassFactory::AddRef()
428 return InterlockedIncrement((LPLONG
)&m_cRef
);
431 STDMETHODIMP_(ULONG
) CShellExtClassFactory::Release()
433 if (InterlockedDecrement((LPLONG
)&m_cRef
))
441 STDMETHODIMP
CShellExtClassFactory::CreateInstance(LPUNKNOWN pUnkOuter
,
447 // Shell extensions typically don't support aggregation (inheritance)
450 return CLASS_E_NOAGGREGATION
;
452 // Create the main shell extension object. The shell will then call
453 // QueryInterface with IID_IShellExtInit--this is how shell extensions are
456 LPCSHELLEXT pShellExt
= new CShellExt(); //Create the CShellExt object
458 if (NULL
== pShellExt
)
459 return E_OUTOFMEMORY
;
461 return pShellExt
->QueryInterface(riid
, ppvObj
);
465 STDMETHODIMP
CShellExtClassFactory::LockServer(BOOL
/* fLock */)
470 // *********************** CShellExt *************************
471 CShellExt::CShellExt()
479 CShellExt::~CShellExt()
482 m_pDataObj
->Release();
487 STDMETHODIMP
CShellExt::QueryInterface(REFIID riid
, LPVOID FAR
*ppv
)
491 if (IsEqualIID(riid
, IID_IShellExtInit
) || IsEqualIID(riid
, IID_IUnknown
))
493 *ppv
= (LPSHELLEXTINIT
)this;
495 else if (IsEqualIID(riid
, IID_IContextMenu
))
497 *ppv
= (LPCONTEXTMENU
)this;
507 return E_NOINTERFACE
;
510 STDMETHODIMP_(ULONG
) CShellExt::AddRef()
512 return InterlockedIncrement((LPLONG
)&m_cRef
);
515 STDMETHODIMP_(ULONG
) CShellExt::Release()
518 if (InterlockedDecrement((LPLONG
)&m_cRef
))
528 // FUNCTION: CShellExt::Initialize(LPCITEMIDLIST, LPDATAOBJECT, HKEY)
530 // PURPOSE: Called by the shell when initializing a context menu or property
534 // pIDFolder - Specifies the parent folder
535 // pDataObj - Spefifies the set of items selected in that folder.
536 // hRegKey - Specifies the type of the focused item in the selection.
540 // NOERROR in all cases.
542 // COMMENTS: Note that at the time this function is called, we don't know
543 // (or care) what type of shell extension is being initialized.
544 // It could be a context menu or a property sheet.
547 STDMETHODIMP
CShellExt::Initialize(LPCITEMIDLIST
/* pIDFolder */,
548 LPDATAOBJECT pDataObj
,
551 // Initialize can be called more than once
553 m_pDataObj
->Release();
555 // duplicate the object pointer and registry handle
559 m_pDataObj
= pDataObj
;
568 // FUNCTION: CShellExt::QueryContextMenu(HMENU, UINT, UINT, UINT, UINT)
570 // PURPOSE: Called by the shell just before the context menu is displayed.
571 // This is where you add your specific menu items.
574 // hMenu - Handle to the context menu
575 // indexMenu - Index of where to begin inserting menu items
576 // idCmdFirst - Lowest value for new menu ID's
577 // idCmtLast - Highest value for new menu ID's
578 // uFlags - Specifies the context of the menu event
586 STDMETHODIMP
CShellExt::QueryContextMenu(HMENU hMenu
,
589 UINT
/* idCmdLast */,
592 UINT idCmd
= idCmdFirst
;
594 hres
= m_pDataObj
->GetData(&fmte
, &medium
);
596 cbFiles
= DragQueryFile((HDROP
)medium
.hGlobal
, (UINT
)-1, 0, 0);
598 // InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL);
600 // Initialize m_cntOfHWnd to 0
602 // Retrieve all the vim instances
603 EnumWindows(EnumWindowsProc
, (LPARAM
)this);
609 MF_STRING
|MF_BYPOSITION
,
611 _("Edit with &multiple Vims"));
615 MF_STRING
|MF_BYPOSITION
,
617 _("Edit with single &Vim"));
621 // Can edit up to 4 files in diff mode
624 MF_STRING
|MF_BYPOSITION
,
627 m_edit_existing_off
= 3;
630 m_edit_existing_off
= 2;
637 MF_STRING
|MF_BYPOSITION
,
639 _("Edit with &Vim"));
640 m_edit_existing_off
= 1;
643 // Now display all the vim instances
644 for (int i
= 0; i
< m_cntOfHWnd
; i
++)
649 // Obtain window title, continue if can not
650 if (GetWindowText(m_hWnd
[i
], title
, BUFSIZE
- 1) == 0)
652 // Truncate the title before the path, keep the file name
653 char *pos
= strchr(title
, '(');
656 if (pos
> title
&& pos
[-1] == ' ')
661 strncpy(temp
, _("Edit with existing Vim - "), BUFSIZE
- 1);
662 temp
[BUFSIZE
- 1] = '\0';
663 strncat(temp
, title
, BUFSIZE
- 1 - strlen(temp
));
664 temp
[BUFSIZE
- 1] = '\0';
667 MF_STRING
|MF_BYPOSITION
,
671 // InsertMenu(hMenu, indexMenu++, MF_SEPARATOR|MF_BYPOSITION, 0, NULL);
673 // Must return number of menu items we added.
674 return ResultFromShort(idCmd
-idCmdFirst
);
678 // FUNCTION: CShellExt::InvokeCommand(LPCMINVOKECOMMANDINFO)
680 // PURPOSE: Called by the shell after the user has selected on of the
681 // menu items that was added in QueryContextMenu().
684 // lpcmi - Pointer to an CMINVOKECOMMANDINFO structure
692 STDMETHODIMP
CShellExt::InvokeCommand(LPCMINVOKECOMMANDINFO lpcmi
)
694 HRESULT hr
= E_INVALIDARG
;
696 // If HIWORD(lpcmi->lpVerb) then we have been called programmatically
697 // and lpVerb is a command that should be invoked. Otherwise, the shell
698 // has called us, and LOWORD(lpcmi->lpVerb) is the menu ID the user has
699 // selected. Actually, it's (menu ID - idCmdFirst) from QueryContextMenu().
700 if (!HIWORD(lpcmi
->lpVerb
))
702 UINT idCmd
= LOWORD(lpcmi
->lpVerb
);
704 if (idCmd
>= m_edit_existing_off
)
706 // Existing with vim instance
707 hr
= PushToWindow(lpcmi
->hwnd
,
712 idCmd
- m_edit_existing_off
);
719 hr
= InvokeGvim(lpcmi
->hwnd
,
726 hr
= InvokeSingleGvim(lpcmi
->hwnd
,
734 hr
= InvokeSingleGvim(lpcmi
->hwnd
,
747 STDMETHODIMP
CShellExt::PushToWindow(HWND
/* hParent */,
748 LPCSTR
/* pszWorkingDir */,
750 LPCSTR
/* pszParam */,
754 HWND hWnd
= m_hWnd
[idHWnd
];
756 // Show and bring vim instance to foreground
757 if (IsIconic(hWnd
) != 0)
758 ShowWindow(hWnd
, SW_RESTORE
);
760 ShowWindow(hWnd
, SW_SHOW
);
761 SetForegroundWindow(hWnd
);
763 // Post the selected files to the vim instance
764 PostMessage(hWnd
, WM_DROPFILES
, (WPARAM
)medium
.hGlobal
, 0);
769 STDMETHODIMP
CShellExt::GetCommandString(UINT_PTR
/* idCmd */,
771 UINT FAR
* /* reserved */,
775 if (uFlags
== GCS_HELPTEXT
&& cchMax
> 35)
776 lstrcpy(pszName
, _("Edits the selected file(s) with Vim"));
781 BOOL CALLBACK
CShellExt::EnumWindowsProc(HWND hWnd
, LPARAM lParam
)
785 // First do a bunch of check
786 // No invisible window
787 if (!IsWindowVisible(hWnd
)) return TRUE
;
788 // No child window ???
789 // if (GetParent(hWnd)) return TRUE;
790 // Class name should be Vim, if failed to get class name, return
791 if (GetClassName(hWnd
, temp
, sizeof(temp
)) == 0)
793 // Compare class name to that of vim, if not, return
794 if (_strnicmp(temp
, "vim", sizeof("vim")) != 0)
796 // First check if the number of vim instance exceeds MAX_HWND
797 CShellExt
*cs
= (CShellExt
*) lParam
;
798 if (cs
->m_cntOfHWnd
>= MAX_HWND
) return TRUE
;
799 // Now we get the vim window, put it into some kind of array
800 cs
->m_hWnd
[cs
->m_cntOfHWnd
] = hWnd
;
803 return TRUE
; // continue enumeration (otherwise this would be false)
807 // This symbol is not defined in older versions of the SDK or Visual C++.
809 #ifndef VER_PLATFORM_WIN32_WINDOWS
810 # define VER_PLATFORM_WIN32_WINDOWS 1
813 static DWORD g_PlatformId
;
816 // Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
817 // VER_PLATFORM_WIN32_WINDOWS (Win95).
822 static int done
= FALSE
;
828 ovi
.dwOSVersionInfoSize
= sizeof(ovi
);
831 g_PlatformId
= ovi
.dwPlatformId
;
836 # ifndef __BORLANDC__
838 searchpath(char *name
)
840 static char widename
[2 * BUFSIZE
];
841 static char location
[2 * BUFSIZE
+ 2];
843 // There appears to be a bug in FindExecutableA() on Windows NT.
844 // Use FindExecutableW() instead...
846 if (g_PlatformId
== VER_PLATFORM_WIN32_NT
)
848 MultiByteToWideChar(CP_ACP
, 0, (LPCTSTR
)name
, -1,
849 (LPWSTR
)widename
, BUFSIZE
);
850 if (FindExecutableW((LPCWSTR
)widename
, (LPCWSTR
)"",
851 (LPWSTR
)location
) > (HINSTANCE
)32)
853 WideCharToMultiByte(CP_ACP
, 0, (LPWSTR
)location
, -1,
854 (LPSTR
)widename
, 2 * BUFSIZE
, NULL
, NULL
);
860 if (FindExecutableA((LPCTSTR
)name
, (LPCTSTR
)"",
861 (LPTSTR
)location
) > (HINSTANCE
)32)
869 STDMETHODIMP
CShellExt::InvokeGvim(HWND hParent
,
870 LPCSTR
/* pszWorkingDir */,
872 LPCSTR
/* pszParam */,
875 char m_szFileUserClickedOn
[BUFSIZE
];
876 char cmdStr
[BUFSIZE
];
879 for (i
= 0; i
< cbFiles
; i
++)
881 DragQueryFile((HDROP
)medium
.hGlobal
,
883 m_szFileUserClickedOn
,
884 sizeof(m_szFileUserClickedOn
));
886 getGvimName(cmdStr
, 0);
887 strcat(cmdStr
, " \"");
889 if ((strlen(cmdStr
) + strlen(m_szFileUserClickedOn
) + 2) < BUFSIZE
)
891 strcat(cmdStr
, m_szFileUserClickedOn
);
892 strcat(cmdStr
, "\"");
895 PROCESS_INFORMATION pi
;
897 ZeroMemory(&si
, sizeof(si
));
900 // Start the child process.
901 if (!CreateProcess(NULL
, // No module name (use command line).
902 cmdStr
, // Command line.
903 NULL
, // Process handle not inheritable.
904 NULL
, // Thread handle not inheritable.
905 FALSE
, // Set handle inheritance to FALSE.
906 0, // No creation flags.
907 NULL
, // Use parent's environment block.
908 NULL
, // Use parent's starting directory.
909 &si
, // Pointer to STARTUPINFO structure.
910 &pi
) // Pointer to PROCESS_INFORMATION structure.
915 _("Error creating process: Check if gvim is in your path!"),
916 _("gvimext.dll error"),
921 CloseHandle( pi
.hProcess
);
922 CloseHandle( pi
.hThread
);
929 _("Path length too long!"),
930 _("gvimext.dll error"),
939 STDMETHODIMP
CShellExt::InvokeSingleGvim(HWND hParent
,
940 LPCSTR
/* pszWorkingDir */,
942 LPCSTR
/* pszParam */,
946 char m_szFileUserClickedOn
[BUFSIZE
];
953 cmdStr
= (char *)malloc(cmdlen
);
954 getGvimName(cmdStr
, 0);
956 strcat(cmdStr
, " -d");
957 for (i
= 0; i
< cbFiles
; i
++)
959 DragQueryFile((HDROP
)medium
.hGlobal
,
961 m_szFileUserClickedOn
,
962 sizeof(m_szFileUserClickedOn
));
964 len
= strlen(cmdStr
) + strlen(m_szFileUserClickedOn
) + 4;
967 cmdlen
= len
+ BUFSIZE
;
968 cmdStr
= (char *)realloc(cmdStr
, cmdlen
);
970 strcat(cmdStr
, " \"");
971 strcat(cmdStr
, m_szFileUserClickedOn
);
972 strcat(cmdStr
, "\"");
976 PROCESS_INFORMATION pi
;
978 ZeroMemory(&si
, sizeof(si
));
981 // Start the child process.
982 if (!CreateProcess(NULL
, // No module name (use command line).
983 cmdStr
, // Command line.
984 NULL
, // Process handle not inheritable.
985 NULL
, // Thread handle not inheritable.
986 FALSE
, // Set handle inheritance to FALSE.
987 0, // No creation flags.
988 NULL
, // Use parent's environment block.
989 NULL
, // Use parent's starting directory.
990 &si
, // Pointer to STARTUPINFO structure.
991 &pi
) // Pointer to PROCESS_INFORMATION structure.
996 _("Error creating process: Check if gvim is in your path!"),
997 _("gvimext.dll error"),
1002 CloseHandle(pi
.hProcess
);
1003 CloseHandle(pi
.hThread
);