code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * GUI support by Robert Webb * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * Windows GUI. * * GUI support for Microsoft Windows. Win32 initially; maybe Win16 later * * George V. Reilly <george@reilly.org> wrote the original Win32 GUI. * Robert Webb reworked it to use the existing GUI stuff and added menu, * scrollbars, etc. * * Note: Clipboard stuff, for cutting and pasting text to other windows, is in * os_win32.c. (It can also be done from the terminal version). * * TODO: Some of the function signatures ought to be updated for Win64; * e.g., replace LONG with LONG_PTR, etc. */ #include "vim.h" /* * These are new in Windows ME/XP, only defined in recent compilers. */ #ifndef HANDLE_WM_XBUTTONUP # define HANDLE_WM_XBUTTONUP(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), (int)(short)LOWORD(lParam), (int)(short)HIWORD(lParam), (UINT)(wParam)), 0L) #endif #ifndef HANDLE_WM_XBUTTONDOWN # define HANDLE_WM_XBUTTONDOWN(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), FALSE, (int)(short)LOWORD(lParam), (int)(short)HIWORD(lParam), (UINT)(wParam)), 0L) #endif #ifndef HANDLE_WM_XBUTTONDBLCLK # define HANDLE_WM_XBUTTONDBLCLK(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), TRUE, (int)(short)LOWORD(lParam), (int)(short)HIWORD(lParam), (UINT)(wParam)), 0L) #endif /* * Include the common stuff for MS-Windows GUI. */ #include "gui_w48.c" #ifdef FEAT_XPM_W32 # include "xpm_w32.h" #endif #ifdef PROTO # define WINAPI #endif #ifdef __MINGW32__ /* * Add a lot of missing defines. * They are not always missing, we need the #ifndef's. */ # ifndef _cdecl # define _cdecl # endif # ifndef IsMinimized # define IsMinimized(hwnd) IsIconic(hwnd) # endif # ifndef IsMaximized # define IsMaximized(hwnd) IsZoomed(hwnd) # endif # ifndef SelectFont # define SelectFont(hdc, hfont) ((HFONT)SelectObject((hdc), (HGDIOBJ)(HFONT)(hfont))) # endif # ifndef GetStockBrush # define GetStockBrush(i) ((HBRUSH)GetStockObject(i)) # endif # ifndef DeleteBrush # define DeleteBrush(hbr) DeleteObject((HGDIOBJ)(HBRUSH)(hbr)) # endif # ifndef HANDLE_WM_RBUTTONDBLCLK # define HANDLE_WM_RBUTTONDBLCLK(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), TRUE, (int)(short)LOWORD(lParam), (int)(short)HIWORD(lParam), (UINT)(wParam)), 0L) # endif # ifndef HANDLE_WM_MBUTTONUP # define HANDLE_WM_MBUTTONUP(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), (int)(short)LOWORD(lParam), (int)(short)HIWORD(lParam), (UINT)(wParam)), 0L) # endif # ifndef HANDLE_WM_MBUTTONDBLCLK # define HANDLE_WM_MBUTTONDBLCLK(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), TRUE, (int)(short)LOWORD(lParam), (int)(short)HIWORD(lParam), (UINT)(wParam)), 0L) # endif # ifndef HANDLE_WM_LBUTTONDBLCLK # define HANDLE_WM_LBUTTONDBLCLK(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), TRUE, (int)(short)LOWORD(lParam), (int)(short)HIWORD(lParam), (UINT)(wParam)), 0L) # endif # ifndef HANDLE_WM_RBUTTONDOWN # define HANDLE_WM_RBUTTONDOWN(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), FALSE, (int)(short)LOWORD(lParam), (int)(short)HIWORD(lParam), (UINT)(wParam)), 0L) # endif # ifndef HANDLE_WM_MOUSEMOVE # define HANDLE_WM_MOUSEMOVE(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), (int)(short)LOWORD(lParam), (int)(short)HIWORD(lParam), (UINT)(wParam)), 0L) # endif # ifndef HANDLE_WM_RBUTTONUP # define HANDLE_WM_RBUTTONUP(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), (int)(short)LOWORD(lParam), (int)(short)HIWORD(lParam), (UINT)(wParam)), 0L) # endif # ifndef HANDLE_WM_MBUTTONDOWN # define HANDLE_WM_MBUTTONDOWN(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), FALSE, (int)(short)LOWORD(lParam), (int)(short)HIWORD(lParam), (UINT)(wParam)), 0L) # endif # ifndef HANDLE_WM_LBUTTONUP # define HANDLE_WM_LBUTTONUP(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), (int)(short)LOWORD(lParam), (int)(short)HIWORD(lParam), (UINT)(wParam)), 0L) # endif # ifndef HANDLE_WM_LBUTTONDOWN # define HANDLE_WM_LBUTTONDOWN(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), FALSE, (int)(short)LOWORD(lParam), (int)(short)HIWORD(lParam), (UINT)(wParam)), 0L) # endif # ifndef HANDLE_WM_SYSCHAR # define HANDLE_WM_SYSCHAR(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), (TCHAR)(wParam), (int)(short)LOWORD(lParam)), 0L) # endif # ifndef HANDLE_WM_ACTIVATEAPP # define HANDLE_WM_ACTIVATEAPP(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), (BOOL)(wParam), (DWORD)(lParam)), 0L) # endif # ifndef HANDLE_WM_WINDOWPOSCHANGING # define HANDLE_WM_WINDOWPOSCHANGING(hwnd, wParam, lParam, fn) \ (LRESULT)(DWORD)(BOOL)(fn)((hwnd), (LPWINDOWPOS)(lParam)) # endif # ifndef HANDLE_WM_VSCROLL # define HANDLE_WM_VSCROLL(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), (HWND)(lParam), (UINT)(LOWORD(wParam)), (int)(short)HIWORD(wParam)), 0L) # endif # ifndef HANDLE_WM_SETFOCUS # define HANDLE_WM_SETFOCUS(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), (HWND)(wParam)), 0L) # endif # ifndef HANDLE_WM_KILLFOCUS # define HANDLE_WM_KILLFOCUS(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), (HWND)(wParam)), 0L) # endif # ifndef HANDLE_WM_HSCROLL # define HANDLE_WM_HSCROLL(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), (HWND)(lParam), (UINT)(LOWORD(wParam)), (int)(short)HIWORD(wParam)), 0L) # endif # ifndef HANDLE_WM_DROPFILES # define HANDLE_WM_DROPFILES(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), (HDROP)(wParam)), 0L) # endif # ifndef HANDLE_WM_CHAR # define HANDLE_WM_CHAR(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), (TCHAR)(wParam), (int)(short)LOWORD(lParam)), 0L) # endif # ifndef HANDLE_WM_SYSDEADCHAR # define HANDLE_WM_SYSDEADCHAR(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), (TCHAR)(wParam), (int)(short)LOWORD(lParam)), 0L) # endif # ifndef HANDLE_WM_DEADCHAR # define HANDLE_WM_DEADCHAR(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), (TCHAR)(wParam), (int)(short)LOWORD(lParam)), 0L) # endif #endif /* __MINGW32__ */ /* Some parameters for tearoff menus. All in pixels. */ #define TEAROFF_PADDING_X 2 #define TEAROFF_BUTTON_PAD_X 8 #define TEAROFF_MIN_WIDTH 200 #define TEAROFF_SUBMENU_LABEL ">>" #define TEAROFF_COLUMN_PADDING 3 // # spaces to pad column with. /* For the Intellimouse: */ #ifndef WM_MOUSEWHEEL #define WM_MOUSEWHEEL 0x20a #endif #ifdef FEAT_BEVAL # define ID_BEVAL_TOOLTIP 200 # define BEVAL_TEXT_LEN MAXPATHL #if (defined(_MSC_VER) && _MSC_VER < 1300) || !defined(MAXULONG_PTR) /* Work around old versions of basetsd.h which wrongly declares * UINT_PTR as unsigned long. */ # undef UINT_PTR # define UINT_PTR UINT #endif static void make_tooltip __ARGS((BalloonEval *beval, char *text, POINT pt)); static void delete_tooltip __ARGS((BalloonEval *beval)); static VOID CALLBACK BevalTimerProc __ARGS((HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)); static BalloonEval *cur_beval = NULL; static UINT_PTR BevalTimerId = 0; static DWORD LastActivity = 0; /* * excerpts from headers since this may not be presented * in the extremely old compilers */ #include <pshpack1.h> typedef struct _DllVersionInfo { DWORD cbSize; DWORD dwMajorVersion; DWORD dwMinorVersion; DWORD dwBuildNumber; DWORD dwPlatformID; } DLLVERSIONINFO; #include <poppack.h> typedef struct tagTOOLINFOA_NEW { UINT cbSize; UINT uFlags; HWND hwnd; UINT_PTR uId; RECT rect; HINSTANCE hinst; LPSTR lpszText; LPARAM lParam; } TOOLINFO_NEW; typedef struct tagNMTTDISPINFO_NEW { NMHDR hdr; LPSTR lpszText; char szText[80]; HINSTANCE hinst; UINT uFlags; LPARAM lParam; } NMTTDISPINFO_NEW; typedef HRESULT (WINAPI* DLLGETVERSIONPROC)(DLLVERSIONINFO *); #ifndef TTM_SETMAXTIPWIDTH # define TTM_SETMAXTIPWIDTH (WM_USER+24) #endif #ifndef TTF_DI_SETITEM # define TTF_DI_SETITEM 0x8000 #endif #ifndef TTN_GETDISPINFO # define TTN_GETDISPINFO (TTN_FIRST - 0) #endif #endif /* defined(FEAT_BEVAL) */ #if defined(FEAT_TOOLBAR) || defined(FEAT_GUI_TABLINE) /* Older MSVC compilers don't have LPNMTTDISPINFO[AW] thus we need to define * it here if LPNMTTDISPINFO isn't defined. * MingW doesn't define LPNMTTDISPINFO but typedefs it. Thus we need to check * _MSC_VER. */ # if !defined(LPNMTTDISPINFO) && defined(_MSC_VER) typedef struct tagNMTTDISPINFOA { NMHDR hdr; LPSTR lpszText; char szText[80]; HINSTANCE hinst; UINT uFlags; LPARAM lParam; } NMTTDISPINFOA, *LPNMTTDISPINFOA; # define LPNMTTDISPINFO LPNMTTDISPINFOA # ifdef FEAT_MBYTE typedef struct tagNMTTDISPINFOW { NMHDR hdr; LPWSTR lpszText; WCHAR szText[80]; HINSTANCE hinst; UINT uFlags; LPARAM lParam; } NMTTDISPINFOW, *LPNMTTDISPINFOW; # endif # endif #endif #ifndef TTN_GETDISPINFOW # define TTN_GETDISPINFOW (TTN_FIRST - 10) #endif /* Local variables: */ #ifdef FEAT_MENU static UINT s_menu_id = 100; #endif /* * Use the system font for dialogs and tear-off menus. Remove this line to * use DLG_FONT_NAME. */ #define USE_SYSMENU_FONT #define VIM_NAME "vim" #define VIM_CLASS "Vim" #define VIM_CLASSW L"Vim" /* Initial size for the dialog template. For gui_mch_dialog() it's fixed, * thus there should be room for every dialog. For tearoffs it's made bigger * when needed. */ #define DLG_ALLOC_SIZE 16 * 1024 /* * stuff for dialogs, menus, tearoffs etc. */ static LRESULT APIENTRY dialog_callback(HWND, UINT, WPARAM, LPARAM); static LRESULT APIENTRY tearoff_callback(HWND, UINT, WPARAM, LPARAM); static PWORD add_dialog_element( PWORD p, DWORD lStyle, WORD x, WORD y, WORD w, WORD h, WORD Id, WORD clss, const char *caption); static LPWORD lpwAlign(LPWORD); static int nCopyAnsiToWideChar(LPWORD, LPSTR); static void gui_mch_tearoff(char_u *title, vimmenu_T *menu, int initX, int initY); static void get_dialog_font_metrics(void); static int dialog_default_button = -1; /* Intellimouse support */ static int mouse_scroll_lines = 0; static UINT msh_msgmousewheel = 0; static int s_usenewlook; /* emulate W95/NT4 non-bold dialogs */ #ifdef FEAT_TOOLBAR static void initialise_toolbar(void); static int get_toolbar_bitmap(vimmenu_T *menu); #endif #ifdef FEAT_GUI_TABLINE static void initialise_tabline(void); #endif #ifdef FEAT_MBYTE_IME static LRESULT _OnImeComposition(HWND hwnd, WPARAM dbcs, LPARAM param); static char_u *GetResultStr(HWND hwnd, int GCS, int *lenp); #endif #if defined(FEAT_MBYTE_IME) && defined(DYNAMIC_IME) # ifdef NOIME typedef struct tagCOMPOSITIONFORM { DWORD dwStyle; POINT ptCurrentPos; RECT rcArea; } COMPOSITIONFORM, *PCOMPOSITIONFORM, NEAR *NPCOMPOSITIONFORM, FAR *LPCOMPOSITIONFORM; typedef HANDLE HIMC; # endif static HINSTANCE hLibImm = NULL; static LONG (WINAPI *pImmGetCompositionStringA)(HIMC, DWORD, LPVOID, DWORD); static LONG (WINAPI *pImmGetCompositionStringW)(HIMC, DWORD, LPVOID, DWORD); static HIMC (WINAPI *pImmGetContext)(HWND); static HIMC (WINAPI *pImmAssociateContext)(HWND, HIMC); static BOOL (WINAPI *pImmReleaseContext)(HWND, HIMC); static BOOL (WINAPI *pImmGetOpenStatus)(HIMC); static BOOL (WINAPI *pImmSetOpenStatus)(HIMC, BOOL); static BOOL (WINAPI *pImmGetCompositionFont)(HIMC, LPLOGFONTA); static BOOL (WINAPI *pImmSetCompositionFont)(HIMC, LPLOGFONTA); static BOOL (WINAPI *pImmSetCompositionWindow)(HIMC, LPCOMPOSITIONFORM); static BOOL (WINAPI *pImmGetConversionStatus)(HIMC, LPDWORD, LPDWORD); static BOOL (WINAPI *pImmSetConversionStatus)(HIMC, DWORD, DWORD); static void dyn_imm_load(void); #else # define pImmGetCompositionStringA ImmGetCompositionStringA # define pImmGetCompositionStringW ImmGetCompositionStringW # define pImmGetContext ImmGetContext # define pImmAssociateContext ImmAssociateContext # define pImmReleaseContext ImmReleaseContext # define pImmGetOpenStatus ImmGetOpenStatus # define pImmSetOpenStatus ImmSetOpenStatus # define pImmGetCompositionFont ImmGetCompositionFontA # define pImmSetCompositionFont ImmSetCompositionFontA # define pImmSetCompositionWindow ImmSetCompositionWindow # define pImmGetConversionStatus ImmGetConversionStatus # define pImmSetConversionStatus ImmSetConversionStatus #endif #ifndef ETO_IGNORELANGUAGE # define ETO_IGNORELANGUAGE 0x1000 #endif /* multi monitor support */ typedef struct _MONITORINFOstruct { DWORD cbSize; RECT rcMonitor; RECT rcWork; DWORD dwFlags; } _MONITORINFO; typedef HANDLE _HMONITOR; typedef _HMONITOR (WINAPI *TMonitorFromWindow)(HWND, DWORD); typedef BOOL (WINAPI *TGetMonitorInfo)(_HMONITOR, _MONITORINFO *); static TMonitorFromWindow pMonitorFromWindow = NULL; static TGetMonitorInfo pGetMonitorInfo = NULL; static HANDLE user32_lib = NULL; #ifdef FEAT_NETBEANS_INTG int WSInitialized = FALSE; /* WinSock is initialized */ #endif /* * Return TRUE when running under Windows NT 3.x or Win32s, both of which have * less fancy GUI APIs. */ static int is_winnt_3(void) { return ((os_version.dwPlatformId == VER_PLATFORM_WIN32_NT && os_version.dwMajorVersion == 3) || (os_version.dwPlatformId == VER_PLATFORM_WIN32s)); } /* * Return TRUE when running under Win32s. */ int gui_is_win32s(void) { return (os_version.dwPlatformId == VER_PLATFORM_WIN32s); } #ifdef FEAT_MENU /* * Figure out how high the menu bar is at the moment. */ static int gui_mswin_get_menu_height( int fix_window) /* If TRUE, resize window if menu height changed */ { static int old_menu_height = -1; RECT rc1, rc2; int num; int menu_height; if (gui.menu_is_active) num = GetMenuItemCount(s_menuBar); else num = 0; if (num == 0) menu_height = 0; else { if (is_winnt_3()) /* for NT 3.xx */ { if (gui.starting) menu_height = GetSystemMetrics(SM_CYMENU); else { RECT r1, r2; int frameht = GetSystemMetrics(SM_CYFRAME); int capht = GetSystemMetrics(SM_CYCAPTION); /* get window rect of s_hwnd * get client rect of s_hwnd * get cap height * subtract from window rect, the sum of client height, * (if not maximized)frame thickness, and caption height. */ GetWindowRect(s_hwnd, &r1); GetClientRect(s_hwnd, &r2); menu_height = r1.bottom - r1.top - (r2.bottom - r2.top + 2 * frameht * (!IsZoomed(s_hwnd)) + capht); } } else /* win95 and variants (NT 4.0, I guess) */ { /* * In case 'lines' is set in _vimrc/_gvimrc window width doesn't * seem to have been set yet, so menu wraps in default window * width which is very narrow. Instead just return height of a * single menu item. Will still be wrong when the menu really * should wrap over more than one line. */ GetMenuItemRect(s_hwnd, s_menuBar, 0, &rc1); if (gui.starting) menu_height = rc1.bottom - rc1.top + 1; else { GetMenuItemRect(s_hwnd, s_menuBar, num - 1, &rc2); menu_height = rc2.bottom - rc1.top + 1; } } } if (fix_window && menu_height != old_menu_height) { old_menu_height = menu_height; gui_set_shellsize(FALSE, FALSE, RESIZE_VERT); } return menu_height; } #endif /*FEAT_MENU*/ /* * Setup for the Intellimouse */ static void init_mouse_wheel(void) { #ifndef SPI_GETWHEELSCROLLLINES # define SPI_GETWHEELSCROLLLINES 104 #endif #ifndef SPI_SETWHEELSCROLLLINES # define SPI_SETWHEELSCROLLLINES 105 #endif #define VMOUSEZ_CLASSNAME "MouseZ" /* hidden wheel window class */ #define VMOUSEZ_TITLE "Magellan MSWHEEL" /* hidden wheel window title */ #define VMSH_MOUSEWHEEL "MSWHEEL_ROLLMSG" #define VMSH_SCROLL_LINES "MSH_SCROLL_LINES_MSG" HWND hdl_mswheel; UINT msh_msgscrolllines; msh_msgmousewheel = 0; mouse_scroll_lines = 3; /* reasonable default */ if ((os_version.dwPlatformId == VER_PLATFORM_WIN32_NT && os_version.dwMajorVersion >= 4) || (os_version.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS && ((os_version.dwMajorVersion == 4 && os_version.dwMinorVersion >= 10) || os_version.dwMajorVersion >= 5))) { /* if NT 4.0+ (or Win98) get scroll lines directly from system */ SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &mouse_scroll_lines, 0); } else if (os_version.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS || (os_version.dwPlatformId == VER_PLATFORM_WIN32_NT && os_version.dwMajorVersion < 4)) { /* * If Win95 or NT 3.51, * try to find the hidden point32 window. */ hdl_mswheel = FindWindow(VMOUSEZ_CLASSNAME, VMOUSEZ_TITLE); if (hdl_mswheel) { msh_msgscrolllines = RegisterWindowMessage(VMSH_SCROLL_LINES); if (msh_msgscrolllines) { mouse_scroll_lines = (int)SendMessage(hdl_mswheel, msh_msgscrolllines, 0, 0); msh_msgmousewheel = RegisterWindowMessage(VMSH_MOUSEWHEEL); } } } } /* Intellimouse wheel handler */ static void _OnMouseWheel( HWND hwnd, short zDelta) { /* Treat a mouse wheel event as if it were a scroll request */ int i; int size; HWND hwndCtl; if (curwin->w_scrollbars[SBAR_RIGHT].id != 0) { hwndCtl = curwin->w_scrollbars[SBAR_RIGHT].id; size = curwin->w_scrollbars[SBAR_RIGHT].size; } else if (curwin->w_scrollbars[SBAR_LEFT].id != 0) { hwndCtl = curwin->w_scrollbars[SBAR_LEFT].id; size = curwin->w_scrollbars[SBAR_LEFT].size; } else return; size = curwin->w_height; if (mouse_scroll_lines == 0) init_mouse_wheel(); if (mouse_scroll_lines > 0 && mouse_scroll_lines < (size > 2 ? size - 2 : 1)) { for (i = mouse_scroll_lines; i > 0; --i) _OnScroll(hwnd, hwndCtl, zDelta >= 0 ? SB_LINEUP : SB_LINEDOWN, 0); } else _OnScroll(hwnd, hwndCtl, zDelta >= 0 ? SB_PAGEUP : SB_PAGEDOWN, 0); } #ifdef USE_SYSMENU_FONT /* * Get Menu Font. * Return OK or FAIL. */ static int gui_w32_get_menu_font(LOGFONT *lf) { NONCLIENTMETRICS nm; nm.cbSize = sizeof(NONCLIENTMETRICS); if (!SystemParametersInfo( SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &nm, 0)) return FAIL; *lf = nm.lfMenuFont; return OK; } #endif #if defined(FEAT_GUI_TABLINE) && defined(USE_SYSMENU_FONT) /* * Set the GUI tabline font to the system menu font */ static void set_tabline_font(void) { LOGFONT lfSysmenu; HFONT font; HWND hwnd; HDC hdc; HFONT hfntOld; TEXTMETRIC tm; if (gui_w32_get_menu_font(&lfSysmenu) != OK) return; font = CreateFontIndirect(&lfSysmenu); SendMessage(s_tabhwnd, WM_SETFONT, (WPARAM)font, TRUE); /* * Compute the height of the font used for the tab text */ hwnd = GetDesktopWindow(); hdc = GetWindowDC(hwnd); hfntOld = SelectFont(hdc, font); GetTextMetrics(hdc, &tm); SelectFont(hdc, hfntOld); ReleaseDC(hwnd, hdc); /* * The space used by the tab border and the space between the tab label * and the tab border is included as 7. */ gui.tabline_height = tm.tmHeight + tm.tmInternalLeading + 7; } #endif /* * Invoked when a setting was changed. */ static LRESULT CALLBACK _OnSettingChange(UINT n) { if (n == SPI_SETWHEELSCROLLLINES) SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &mouse_scroll_lines, 0); #if defined(FEAT_GUI_TABLINE) && defined(USE_SYSMENU_FONT) if (n == SPI_SETNONCLIENTMETRICS) set_tabline_font(); #endif return 0; } #ifdef FEAT_NETBEANS_INTG static void _OnWindowPosChanged( HWND hwnd, const LPWINDOWPOS lpwpos) { static int x = 0, y = 0, cx = 0, cy = 0; if (WSInitialized && (lpwpos->x != x || lpwpos->y != y || lpwpos->cx != cx || lpwpos->cy != cy)) { x = lpwpos->x; y = lpwpos->y; cx = lpwpos->cx; cy = lpwpos->cy; netbeans_frame_moved(x, y); } /* Allow to send WM_SIZE and WM_MOVE */ FORWARD_WM_WINDOWPOSCHANGED(hwnd, lpwpos, MyWindowProc); } #endif static int _DuringSizing( UINT fwSide, LPRECT lprc) { int w, h; int valid_w, valid_h; int w_offset, h_offset; w = lprc->right - lprc->left; h = lprc->bottom - lprc->top; gui_mswin_get_valid_dimensions(w, h, &valid_w, &valid_h); w_offset = w - valid_w; h_offset = h - valid_h; if (fwSide == WMSZ_LEFT || fwSide == WMSZ_TOPLEFT || fwSide == WMSZ_BOTTOMLEFT) lprc->left += w_offset; else if (fwSide == WMSZ_RIGHT || fwSide == WMSZ_TOPRIGHT || fwSide == WMSZ_BOTTOMRIGHT) lprc->right -= w_offset; if (fwSide == WMSZ_TOP || fwSide == WMSZ_TOPLEFT || fwSide == WMSZ_TOPRIGHT) lprc->top += h_offset; else if (fwSide == WMSZ_BOTTOM || fwSide == WMSZ_BOTTOMLEFT || fwSide == WMSZ_BOTTOMRIGHT) lprc->bottom -= h_offset; return TRUE; } static LRESULT CALLBACK _WndProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { /* TRACE("WndProc: hwnd = %08x, msg = %x, wParam = %x, lParam = %x\n", hwnd, uMsg, wParam, lParam); */ HandleMouseHide(uMsg, lParam); s_uMsg = uMsg; s_wParam = wParam; s_lParam = lParam; switch (uMsg) { HANDLE_MSG(hwnd, WM_DEADCHAR, _OnDeadChar); HANDLE_MSG(hwnd, WM_SYSDEADCHAR, _OnDeadChar); /* HANDLE_MSG(hwnd, WM_ACTIVATE, _OnActivate); */ HANDLE_MSG(hwnd, WM_CLOSE, _OnClose); /* HANDLE_MSG(hwnd, WM_COMMAND, _OnCommand); */ HANDLE_MSG(hwnd, WM_DESTROY, _OnDestroy); HANDLE_MSG(hwnd, WM_DROPFILES, _OnDropFiles); HANDLE_MSG(hwnd, WM_HSCROLL, _OnScroll); HANDLE_MSG(hwnd, WM_KILLFOCUS, _OnKillFocus); #ifdef FEAT_MENU HANDLE_MSG(hwnd, WM_COMMAND, _OnMenu); #endif /* HANDLE_MSG(hwnd, WM_MOVE, _OnMove); */ /* HANDLE_MSG(hwnd, WM_NCACTIVATE, _OnNCActivate); */ HANDLE_MSG(hwnd, WM_SETFOCUS, _OnSetFocus); HANDLE_MSG(hwnd, WM_SIZE, _OnSize); /* HANDLE_MSG(hwnd, WM_SYSCOMMAND, _OnSysCommand); */ /* HANDLE_MSG(hwnd, WM_SYSKEYDOWN, _OnAltKey); */ HANDLE_MSG(hwnd, WM_VSCROLL, _OnScroll); // HANDLE_MSG(hwnd, WM_WINDOWPOSCHANGING, _OnWindowPosChanging); HANDLE_MSG(hwnd, WM_ACTIVATEAPP, _OnActivateApp); #ifdef FEAT_NETBEANS_INTG HANDLE_MSG(hwnd, WM_WINDOWPOSCHANGED, _OnWindowPosChanged); #endif #ifdef FEAT_GUI_TABLINE case WM_RBUTTONUP: { if (gui_mch_showing_tabline()) { POINT pt; RECT rect; /* * If the cursor is on the tabline, display the tab menu */ GetCursorPos((LPPOINT)&pt); GetWindowRect(s_textArea, &rect); if (pt.y < rect.top) { show_tabline_popup_menu(); return 0L; } } return MyWindowProc(hwnd, uMsg, wParam, lParam); } case WM_LBUTTONDBLCLK: { /* * If the user double clicked the tabline, create a new tab */ if (gui_mch_showing_tabline()) { POINT pt; RECT rect; GetCursorPos((LPPOINT)&pt); GetWindowRect(s_textArea, &rect); if (pt.y < rect.top) send_tabline_menu_event(0, TABLINE_MENU_NEW); } return MyWindowProc(hwnd, uMsg, wParam, lParam); } #endif case WM_QUERYENDSESSION: /* System wants to go down. */ gui_shell_closed(); /* Will exit when no changed buffers. */ return FALSE; /* Do NOT allow system to go down. */ case WM_ENDSESSION: if (wParam) /* system only really goes down when wParam is TRUE */ { _OnEndSession(); return 0L; } break; case WM_CHAR: /* Don't use HANDLE_MSG() for WM_CHAR, it truncates wParam to a single * byte while we want the UTF-16 character value. */ _OnChar(hwnd, (UINT)wParam, (int)(short)LOWORD(lParam)); return 0L; case WM_SYSCHAR: /* * if 'winaltkeys' is "no", or it's "menu" and it's not a menu * shortcut key, handle like a typed ALT key, otherwise call Windows * ALT key handling. */ #ifdef FEAT_MENU if ( !gui.menu_is_active || p_wak[0] == 'n' || (p_wak[0] == 'm' && !gui_is_menu_shortcut((int)wParam)) ) #endif { _OnSysChar(hwnd, (UINT)wParam, (int)(short)LOWORD(lParam)); return 0L; } #ifdef FEAT_MENU else return MyWindowProc(hwnd, uMsg, wParam, lParam); #endif case WM_SYSKEYUP: #ifdef FEAT_MENU /* This used to be done only when menu is active: ALT key is used for * that. But that caused problems when menu is disabled and using * Alt-Tab-Esc: get into a strange state where no mouse-moved events * are received, mouse pointer remains hidden. */ return MyWindowProc(hwnd, uMsg, wParam, lParam); #else return 0L; #endif case WM_SIZING: /* HANDLE_MSG doesn't seem to handle this one */ return _DuringSizing((UINT)wParam, (LPRECT)lParam); case WM_MOUSEWHEEL: _OnMouseWheel(hwnd, HIWORD(wParam)); return 0L; /* Notification for change in SystemParametersInfo() */ case WM_SETTINGCHANGE: return _OnSettingChange((UINT)wParam); #if defined(FEAT_TOOLBAR) || defined(FEAT_GUI_TABLINE) case WM_NOTIFY: switch (((LPNMHDR) lParam)->code) { # ifdef FEAT_MBYTE case TTN_GETDISPINFOW: # endif case TTN_GETDISPINFO: { LPNMHDR hdr = (LPNMHDR)lParam; char_u *str = NULL; static void *tt_text = NULL; vim_free(tt_text); tt_text = NULL; # ifdef FEAT_GUI_TABLINE if (gui_mch_showing_tabline() && hdr->hwndFrom == TabCtrl_GetToolTips(s_tabhwnd)) { POINT pt; /* * Mouse is over the GUI tabline. Display the * tooltip for the tab under the cursor * * Get the cursor position within the tab control */ GetCursorPos(&pt); if (ScreenToClient(s_tabhwnd, &pt) != 0) { TCHITTESTINFO htinfo; int idx; /* * Get the tab under the cursor */ htinfo.pt.x = pt.x; htinfo.pt.y = pt.y; idx = TabCtrl_HitTest(s_tabhwnd, &htinfo); if (idx != -1) { tabpage_T *tp; tp = find_tabpage(idx + 1); if (tp != NULL) { get_tabline_label(tp, TRUE); str = NameBuff; } } } } # endif # ifdef FEAT_TOOLBAR # ifdef FEAT_GUI_TABLINE else # endif { UINT idButton; vimmenu_T *pMenu; idButton = (UINT) hdr->idFrom; pMenu = gui_mswin_find_menu(root_menu, idButton); if (pMenu) str = pMenu->strings[MENU_INDEX_TIP]; } # endif if (str != NULL) { # ifdef FEAT_MBYTE if (hdr->code == TTN_GETDISPINFOW) { LPNMTTDISPINFOW lpdi = (LPNMTTDISPINFOW)lParam; /* Set the maximum width, this also enables using * \n for line break. */ SendMessage(lpdi->hdr.hwndFrom, TTM_SETMAXTIPWIDTH, 0, 500); tt_text = enc_to_utf16(str, NULL); lpdi->lpszText = tt_text; /* can't show tooltip if failed */ } else # endif { LPNMTTDISPINFO lpdi = (LPNMTTDISPINFO)lParam; /* Set the maximum width, this also enables using * \n for line break. */ SendMessage(lpdi->hdr.hwndFrom, TTM_SETMAXTIPWIDTH, 0, 500); if (STRLEN(str) < sizeof(lpdi->szText) || ((tt_text = vim_strsave(str)) == NULL)) vim_strncpy(lpdi->szText, str, sizeof(lpdi->szText) - 1); else lpdi->lpszText = tt_text; } } } break; # ifdef FEAT_GUI_TABLINE case TCN_SELCHANGE: if (gui_mch_showing_tabline() && ((LPNMHDR)lParam)->hwndFrom == s_tabhwnd) { send_tabline_event(TabCtrl_GetCurSel(s_tabhwnd) + 1); return 0L; } break; case NM_RCLICK: if (gui_mch_showing_tabline() && ((LPNMHDR)lParam)->hwndFrom == s_tabhwnd) { show_tabline_popup_menu(); return 0L; } break; # endif default: # ifdef FEAT_GUI_TABLINE if (gui_mch_showing_tabline() && ((LPNMHDR)lParam)->hwndFrom == s_tabhwnd) return MyWindowProc(hwnd, uMsg, wParam, lParam); # endif break; } break; #endif #if defined(MENUHINTS) && defined(FEAT_MENU) case WM_MENUSELECT: if (((UINT) HIWORD(wParam) & (0xffff ^ (MF_MOUSESELECT + MF_BITMAP + MF_POPUP))) == MF_HILITE && (State & CMDLINE) == 0) { UINT idButton; vimmenu_T *pMenu; static int did_menu_tip = FALSE; if (did_menu_tip) { msg_clr_cmdline(); setcursor(); out_flush(); did_menu_tip = FALSE; } idButton = (UINT)LOWORD(wParam); pMenu = gui_mswin_find_menu(root_menu, idButton); if (pMenu != NULL && pMenu->strings[MENU_INDEX_TIP] != 0 && GetMenuState(s_menuBar, pMenu->id, MF_BYCOMMAND) != -1) { ++msg_hist_off; msg(pMenu->strings[MENU_INDEX_TIP]); --msg_hist_off; setcursor(); out_flush(); did_menu_tip = TRUE; } return 0L; } break; #endif case WM_NCHITTEST: { LRESULT result; int x, y; int xPos = GET_X_LPARAM(lParam); result = MyWindowProc(hwnd, uMsg, wParam, lParam); if (result == HTCLIENT) { #ifdef FEAT_GUI_TABLINE if (gui_mch_showing_tabline()) { int yPos = GET_Y_LPARAM(lParam); RECT rct; /* If the cursor is on the GUI tabline, don't process this * event */ GetWindowRect(s_textArea, &rct); if (yPos < rct.top) return result; } #endif gui_mch_get_winpos(&x, &y); xPos -= x; if (xPos < 48) /* <VN> TODO should use system metric? */ return HTBOTTOMLEFT; else return HTBOTTOMRIGHT; } else return result; } /* break; notreached */ #ifdef FEAT_MBYTE_IME case WM_IME_NOTIFY: if (!_OnImeNotify(hwnd, (DWORD)wParam, (DWORD)lParam)) return MyWindowProc(hwnd, uMsg, wParam, lParam); return 1L; case WM_IME_COMPOSITION: if (!_OnImeComposition(hwnd, wParam, lParam)) return MyWindowProc(hwnd, uMsg, wParam, lParam); return 1L; #endif default: if (uMsg == msh_msgmousewheel && msh_msgmousewheel != 0) { /* handle MSH_MOUSEWHEEL messages for Intellimouse */ _OnMouseWheel(hwnd, HIWORD(wParam)); return 0L; } #ifdef MSWIN_FIND_REPLACE else if (uMsg == s_findrep_msg && s_findrep_msg != 0) { _OnFindRepl(); } #endif return MyWindowProc(hwnd, uMsg, wParam, lParam); } return DefWindowProc(hwnd, uMsg, wParam, lParam); } /* * End of call-back routines */ /* parent window, if specified with -P */ HWND vim_parent_hwnd = NULL; static BOOL CALLBACK FindWindowTitle(HWND hwnd, LPARAM lParam) { char buf[2048]; char *title = (char *)lParam; if (GetWindowText(hwnd, buf, sizeof(buf))) { if (strstr(buf, title) != NULL) { /* Found it. Store the window ref. and quit searching if MDI * works. */ vim_parent_hwnd = FindWindowEx(hwnd, NULL, "MDIClient", NULL); if (vim_parent_hwnd != NULL) return FALSE; } } return TRUE; /* continue searching */ } /* * Invoked for '-P "title"' argument: search for parent application to open * our window in. */ void gui_mch_set_parent(char *title) { EnumWindows(FindWindowTitle, (LPARAM)title); if (vim_parent_hwnd == NULL) { EMSG2(_("E671: Cannot find window title \"%s\""), title); mch_exit(2); } } #ifndef FEAT_OLE static void ole_error(char *arg) { char buf[IOSIZE]; /* Can't use EMSG() here, we have not finished initialisation yet. */ vim_snprintf(buf, IOSIZE, _("E243: Argument not supported: \"-%s\"; Use the OLE version."), arg); mch_errmsg(buf); } #endif /* * Parse the GUI related command-line arguments. Any arguments used are * deleted from argv, and *argc is decremented accordingly. This is called * when vim is started, whether or not the GUI has been started. */ void gui_mch_prepare(int *argc, char **argv) { int silent = FALSE; int idx; /* Check for special OLE command line parameters */ if ((*argc == 2 || *argc == 3) && (argv[1][0] == '-' || argv[1][0] == '/')) { /* Check for a "-silent" argument first. */ if (*argc == 3 && STRICMP(argv[1] + 1, "silent") == 0 && (argv[2][0] == '-' || argv[2][0] == '/')) { silent = TRUE; idx = 2; } else idx = 1; /* Register Vim as an OLE Automation server */ if (STRICMP(argv[idx] + 1, "register") == 0) { #ifdef FEAT_OLE RegisterMe(silent); mch_exit(0); #else if (!silent) ole_error("register"); mch_exit(2); #endif } /* Unregister Vim as an OLE Automation server */ if (STRICMP(argv[idx] + 1, "unregister") == 0) { #ifdef FEAT_OLE UnregisterMe(!silent); mch_exit(0); #else if (!silent) ole_error("unregister"); mch_exit(2); #endif } /* Ignore an -embedding argument. It is only relevant if the * application wants to treat the case when it is started manually * differently from the case where it is started via automation (and * we don't). */ if (STRICMP(argv[idx] + 1, "embedding") == 0) { #ifdef FEAT_OLE *argc = 1; #else ole_error("embedding"); mch_exit(2); #endif } } #ifdef FEAT_OLE { int bDoRestart = FALSE; InitOLE(&bDoRestart); /* automatically exit after registering */ if (bDoRestart) mch_exit(0); } #endif #ifdef FEAT_NETBEANS_INTG { /* stolen from gui_x11.x */ int arg; for (arg = 1; arg < *argc; arg++) if (strncmp("-nb", argv[arg], 3) == 0) { netbeansArg = argv[arg]; mch_memmove(&argv[arg], &argv[arg + 1], (--*argc - arg) * sizeof(char *)); argv[*argc] = NULL; break; /* enough? */ } } #endif /* get the OS version info */ os_version.dwOSVersionInfoSize = sizeof(os_version); GetVersionEx(&os_version); /* this call works on Win32s, Win95 and WinNT */ /* try and load the user32.dll library and get the entry points for * multi-monitor-support. */ if ((user32_lib = vimLoadLib("User32.dll")) != NULL) { pMonitorFromWindow = (TMonitorFromWindow)GetProcAddress(user32_lib, "MonitorFromWindow"); /* there are ...A and ...W version of GetMonitorInfo - looking at * winuser.h, they have exactly the same declaration. */ pGetMonitorInfo = (TGetMonitorInfo)GetProcAddress(user32_lib, "GetMonitorInfoA"); } #ifdef FEAT_MBYTE /* If the OS is Windows NT, use wide functions; * this enables common dialogs input unicode from IME. */ if (os_version.dwPlatformId == VER_PLATFORM_WIN32_NT) { pDispatchMessage = DispatchMessageW; pGetMessage = GetMessageW; pIsDialogMessage = IsDialogMessageW; pPeekMessage = PeekMessageW; } else { pDispatchMessage = DispatchMessageA; pGetMessage = GetMessageA; pIsDialogMessage = IsDialogMessageA; pPeekMessage = PeekMessageA; } #endif } /* * Initialise the GUI. Create all the windows, set up all the call-backs * etc. */ int gui_mch_init(void) { const char szVimWndClass[] = VIM_CLASS; const char szTextAreaClass[] = "VimTextArea"; WNDCLASS wndclass; #ifdef FEAT_MBYTE const WCHAR szVimWndClassW[] = VIM_CLASSW; const WCHAR szTextAreaClassW[] = L"VimTextArea"; WNDCLASSW wndclassw; #endif #ifdef GLOBAL_IME ATOM atom; #endif /* Return here if the window was already opened (happens when * gui_mch_dialog() is called early). */ if (s_hwnd != NULL) goto theend; /* * Load the tearoff bitmap */ #ifdef FEAT_TEAROFF s_htearbitmap = LoadBitmap(s_hinst, "IDB_TEAROFF"); #endif gui.scrollbar_width = GetSystemMetrics(SM_CXVSCROLL); gui.scrollbar_height = GetSystemMetrics(SM_CYHSCROLL); #ifdef FEAT_MENU gui.menu_height = 0; /* Windows takes care of this */ #endif gui.border_width = 0; s_brush = CreateSolidBrush(GetSysColor(COLOR_BTNFACE)); #ifdef FEAT_MBYTE /* First try using the wide version, so that we can use any title. * Otherwise only characters in the active codepage will work. */ if (GetClassInfoW(s_hinst, szVimWndClassW, &wndclassw) == 0) { wndclassw.style = CS_DBLCLKS; wndclassw.lpfnWndProc = _WndProc; wndclassw.cbClsExtra = 0; wndclassw.cbWndExtra = 0; wndclassw.hInstance = s_hinst; wndclassw.hIcon = LoadIcon(wndclassw.hInstance, "IDR_VIM"); wndclassw.hCursor = LoadCursor(NULL, IDC_ARROW); wndclassw.hbrBackground = s_brush; wndclassw.lpszMenuName = NULL; wndclassw.lpszClassName = szVimWndClassW; if (( #ifdef GLOBAL_IME atom = #endif RegisterClassW(&wndclassw)) == 0) { if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) return FAIL; /* Must be Windows 98, fall back to non-wide function. */ } else wide_WindowProc = TRUE; } if (!wide_WindowProc) #endif if (GetClassInfo(s_hinst, szVimWndClass, &wndclass) == 0) { wndclass.style = CS_DBLCLKS; wndclass.lpfnWndProc = _WndProc; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = s_hinst; wndclass.hIcon = LoadIcon(wndclass.hInstance, "IDR_VIM"); wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hbrBackground = s_brush; wndclass.lpszMenuName = NULL; wndclass.lpszClassName = szVimWndClass; if (( #ifdef GLOBAL_IME atom = #endif RegisterClass(&wndclass)) == 0) return FAIL; } if (vim_parent_hwnd != NULL) { #ifdef HAVE_TRY_EXCEPT __try { #endif /* Open inside the specified parent window. * TODO: last argument should point to a CLIENTCREATESTRUCT * structure. */ s_hwnd = CreateWindowEx( WS_EX_MDICHILD, szVimWndClass, "Vim MSWindows GUI", WS_OVERLAPPEDWINDOW | WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | 0xC000, gui_win_x == -1 ? CW_USEDEFAULT : gui_win_x, gui_win_y == -1 ? CW_USEDEFAULT : gui_win_y, 100, /* Any value will do */ 100, /* Any value will do */ vim_parent_hwnd, NULL, s_hinst, NULL); #ifdef HAVE_TRY_EXCEPT } __except(EXCEPTION_EXECUTE_HANDLER) { /* NOP */ } #endif if (s_hwnd == NULL) { EMSG(_("E672: Unable to open window inside MDI application")); mch_exit(2); } } else { /* If the provided windowid is not valid reset it to zero, so that it * is ignored and we open our own window. */ if (IsWindow((HWND)win_socket_id) <= 0) win_socket_id = 0; /* Create a window. If win_socket_id is not zero without border and * titlebar, it will be reparented below. */ s_hwnd = CreateWindow( szVimWndClass, "Vim MSWindows GUI", (win_socket_id == 0 ? WS_OVERLAPPEDWINDOW : WS_POPUP) | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, gui_win_x == -1 ? CW_USEDEFAULT : gui_win_x, gui_win_y == -1 ? CW_USEDEFAULT : gui_win_y, 100, /* Any value will do */ 100, /* Any value will do */ NULL, NULL, s_hinst, NULL); if (s_hwnd != NULL && win_socket_id != 0) { SetParent(s_hwnd, (HWND)win_socket_id); ShowWindow(s_hwnd, SW_SHOWMAXIMIZED); } } if (s_hwnd == NULL) return FAIL; #ifdef GLOBAL_IME global_ime_init(atom, s_hwnd); #endif #if defined(FEAT_MBYTE_IME) && defined(DYNAMIC_IME) dyn_imm_load(); #endif /* Create the text area window */ #ifdef FEAT_MBYTE if (wide_WindowProc) { if (GetClassInfoW(s_hinst, szTextAreaClassW, &wndclassw) == 0) { wndclassw.style = CS_OWNDC; wndclassw.lpfnWndProc = _TextAreaWndProc; wndclassw.cbClsExtra = 0; wndclassw.cbWndExtra = 0; wndclassw.hInstance = s_hinst; wndclassw.hIcon = NULL; wndclassw.hCursor = LoadCursor(NULL, IDC_ARROW); wndclassw.hbrBackground = NULL; wndclassw.lpszMenuName = NULL; wndclassw.lpszClassName = szTextAreaClassW; if (RegisterClassW(&wndclassw) == 0) return FAIL; } } else #endif if (GetClassInfo(s_hinst, szTextAreaClass, &wndclass) == 0) { wndclass.style = CS_OWNDC; wndclass.lpfnWndProc = _TextAreaWndProc; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = s_hinst; wndclass.hIcon = NULL; wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hbrBackground = NULL; wndclass.lpszMenuName = NULL; wndclass.lpszClassName = szTextAreaClass; if (RegisterClass(&wndclass) == 0) return FAIL; } s_textArea = CreateWindowEx( WS_EX_CLIENTEDGE, szTextAreaClass, "Vim text area", WS_CHILD | WS_VISIBLE, 0, 0, 100, /* Any value will do for now */ 100, /* Any value will do for now */ s_hwnd, NULL, s_hinst, NULL); if (s_textArea == NULL) return FAIL; #ifdef FEAT_MENU s_menuBar = CreateMenu(); #endif s_hdc = GetDC(s_textArea); #ifdef MSWIN16_FASTTEXT SetBkMode(s_hdc, OPAQUE); #endif #ifdef FEAT_WINDOWS DragAcceptFiles(s_hwnd, TRUE); #endif /* Do we need to bother with this? */ /* m_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT); */ /* Get background/foreground colors from the system */ gui_mch_def_colors(); /* Get the colors from the "Normal" group (set in syntax.c or in a vimrc * file) */ set_normal_colors(); /* * Check that none of the colors are the same as the background color. * Then store the current values as the defaults. */ gui_check_colors(); gui.def_norm_pixel = gui.norm_pixel; gui.def_back_pixel = gui.back_pixel; /* Get the colors for the highlight groups (gui_check_colors() might have * changed them) */ highlight_gui_started(); /* * Start out by adding the configured border width into the border offset */ gui.border_offset = gui.border_width + 2; /*CLIENT EDGE*/ /* * Set up for Intellimouse processing */ init_mouse_wheel(); /* * compute a couple of metrics used for the dialogs */ get_dialog_font_metrics(); #ifdef FEAT_TOOLBAR /* * Create the toolbar */ initialise_toolbar(); #endif #ifdef FEAT_GUI_TABLINE /* * Create the tabline */ initialise_tabline(); #endif #ifdef MSWIN_FIND_REPLACE /* * Initialise the dialog box stuff */ s_findrep_msg = RegisterWindowMessage(FINDMSGSTRING); /* Initialise the struct */ s_findrep_struct.lStructSize = sizeof(s_findrep_struct); s_findrep_struct.lpstrFindWhat = alloc(MSWIN_FR_BUFSIZE); s_findrep_struct.lpstrFindWhat[0] = NUL; s_findrep_struct.lpstrReplaceWith = alloc(MSWIN_FR_BUFSIZE); s_findrep_struct.lpstrReplaceWith[0] = NUL; s_findrep_struct.wFindWhatLen = MSWIN_FR_BUFSIZE; s_findrep_struct.wReplaceWithLen = MSWIN_FR_BUFSIZE; # if defined(FEAT_MBYTE) && defined(WIN3264) s_findrep_struct_w.lStructSize = sizeof(s_findrep_struct_w); s_findrep_struct_w.lpstrFindWhat = (LPWSTR)alloc(MSWIN_FR_BUFSIZE * sizeof(WCHAR)); s_findrep_struct_w.lpstrFindWhat[0] = NUL; s_findrep_struct_w.lpstrReplaceWith = (LPWSTR)alloc(MSWIN_FR_BUFSIZE * sizeof(WCHAR)); s_findrep_struct_w.lpstrReplaceWith[0] = NUL; s_findrep_struct_w.wFindWhatLen = MSWIN_FR_BUFSIZE; s_findrep_struct_w.wReplaceWithLen = MSWIN_FR_BUFSIZE; # endif #endif #ifdef FEAT_EVAL # if _MSC_VER < 1400 /* HandleToLong() only exists in compilers that can do 64 bit builds */ # define HandleToLong(h) ((long)(h)) # endif /* set the v:windowid variable */ set_vim_var_nr(VV_WINDOWID, HandleToLong(s_hwnd)); #endif theend: /* Display any pending error messages */ display_errors(); return OK; } /* * Get the size of the screen, taking position on multiple monitors into * account (if supported). */ static void get_work_area(RECT *spi_rect) { _HMONITOR mon; _MONITORINFO moninfo; /* use these functions only if available */ if (pMonitorFromWindow != NULL && pGetMonitorInfo != NULL) { /* work out which monitor the window is on, and get *it's* work area */ mon = pMonitorFromWindow(s_hwnd, 1 /*MONITOR_DEFAULTTOPRIMARY*/); if (mon != NULL) { moninfo.cbSize = sizeof(_MONITORINFO); if (pGetMonitorInfo(mon, &moninfo)) { *spi_rect = moninfo.rcWork; return; } } } /* this is the old method... */ SystemParametersInfo(SPI_GETWORKAREA, 0, spi_rect, 0); } /* * Set the size of the window to the given width and height in pixels. */ /*ARGSUSED*/ void gui_mch_set_shellsize(int width, int height, int min_width, int min_height, int base_width, int base_height, int direction) { RECT workarea_rect; int win_width, win_height; WINDOWPLACEMENT wndpl; /* Try to keep window completely on screen. */ /* Get position of the screen work area. This is the part that is not * used by the taskbar or appbars. */ get_work_area(&workarea_rect); /* Get current posision of our window. Note that the .left and .top are * relative to the work area. */ wndpl.length = sizeof(WINDOWPLACEMENT); GetWindowPlacement(s_hwnd, &wndpl); /* Resizing a maximized window looks very strange, unzoom it first. * But don't do it when still starting up, it may have been requested in * the shortcut. */ if (wndpl.showCmd == SW_SHOWMAXIMIZED && starting == 0) { ShowWindow(s_hwnd, SW_SHOWNORMAL); /* Need to get the settings of the normal window. */ GetWindowPlacement(s_hwnd, &wndpl); } /* compute the size of the outside of the window */ win_width = width + GetSystemMetrics(SM_CXFRAME) * 2; win_height = height + GetSystemMetrics(SM_CYFRAME) * 2 + GetSystemMetrics(SM_CYCAPTION) #ifdef FEAT_MENU + gui_mswin_get_menu_height(FALSE) #endif ; /* The following should take care of keeping Vim on the same monitor, no * matter if the secondary monitor is left or right of the primary * monitor. */ wndpl.rcNormalPosition.right = wndpl.rcNormalPosition.left + win_width; wndpl.rcNormalPosition.bottom = wndpl.rcNormalPosition.top + win_height; /* If the window is going off the screen, move it on to the screen. */ if ((direction & RESIZE_HOR) && wndpl.rcNormalPosition.right > workarea_rect.right) OffsetRect(&wndpl.rcNormalPosition, workarea_rect.right - wndpl.rcNormalPosition.right, 0); if ((direction & RESIZE_HOR) && wndpl.rcNormalPosition.left < workarea_rect.left) OffsetRect(&wndpl.rcNormalPosition, workarea_rect.left - wndpl.rcNormalPosition.left, 0); if ((direction & RESIZE_VERT) && wndpl.rcNormalPosition.bottom > workarea_rect.bottom) OffsetRect(&wndpl.rcNormalPosition, 0, workarea_rect.bottom - wndpl.rcNormalPosition.bottom); if ((direction & RESIZE_VERT) && wndpl.rcNormalPosition.top < workarea_rect.top) OffsetRect(&wndpl.rcNormalPosition, 0, workarea_rect.top - wndpl.rcNormalPosition.top); /* set window position - we should use SetWindowPlacement rather than * SetWindowPos as the MSDN docs say the coord systems returned by * these two are not compatible. */ SetWindowPlacement(s_hwnd, &wndpl); SetActiveWindow(s_hwnd); SetFocus(s_hwnd); #ifdef FEAT_MENU /* Menu may wrap differently now */ gui_mswin_get_menu_height(!gui.starting); #endif } void gui_mch_set_scrollbar_thumb( scrollbar_T *sb, long val, long size, long max) { SCROLLINFO info; sb->scroll_shift = 0; while (max > 32767) { max = (max + 1) >> 1; val >>= 1; size >>= 1; ++sb->scroll_shift; } if (sb->scroll_shift > 0) ++size; info.cbSize = sizeof(info); info.fMask = SIF_POS | SIF_RANGE | SIF_PAGE; info.nPos = val; info.nMin = 0; info.nMax = max; info.nPage = size; SetScrollInfo(sb->id, SB_CTL, &info, TRUE); } /* * Set the current text font. */ void gui_mch_set_font(GuiFont font) { gui.currFont = font; } /* * Set the current text foreground color. */ void gui_mch_set_fg_color(guicolor_T color) { gui.currFgColor = color; } /* * Set the current text background color. */ void gui_mch_set_bg_color(guicolor_T color) { gui.currBgColor = color; } /* * Set the current text special color. */ void gui_mch_set_sp_color(guicolor_T color) { gui.currSpColor = color; } #if defined(FEAT_MBYTE) && defined(FEAT_MBYTE_IME) /* * Multi-byte handling, originally by Sung-Hoon Baek. * First static functions (no prototypes generated). */ #ifdef _MSC_VER # include <ime.h> /* Apparently not needed for Cygwin, MingW or Borland. */ #endif #include <imm.h> /* * handle WM_IME_NOTIFY message */ /*ARGSUSED*/ static LRESULT _OnImeNotify(HWND hWnd, DWORD dwCommand, DWORD dwData) { LRESULT lResult = 0; HIMC hImc; if (!pImmGetContext || (hImc = pImmGetContext(hWnd)) == (HIMC)0) return lResult; switch (dwCommand) { case IMN_SETOPENSTATUS: if (pImmGetOpenStatus(hImc)) { pImmSetCompositionFont(hImc, &norm_logfont); im_set_position(gui.row, gui.col); /* Disable langmap */ State &= ~LANGMAP; if (State & INSERT) { #if defined(FEAT_WINDOWS) && defined(FEAT_KEYMAP) /* Unshown 'keymap' in status lines */ if (curbuf->b_p_iminsert == B_IMODE_LMAP) { /* Save cursor position */ int old_row = gui.row; int old_col = gui.col; // This must be called here before // status_redraw_curbuf(), otherwise the mode // message may appear in the wrong position. showmode(); status_redraw_curbuf(); update_screen(0); /* Restore cursor position */ gui.row = old_row; gui.col = old_col; } #endif } } gui_update_cursor(TRUE, FALSE); lResult = 0; break; } pImmReleaseContext(hWnd, hImc); return lResult; } /*ARGSUSED*/ static LRESULT _OnImeComposition(HWND hwnd, WPARAM dbcs, LPARAM param) { char_u *ret; int len; if ((param & GCS_RESULTSTR) == 0) /* Composition unfinished. */ return 0; ret = GetResultStr(hwnd, GCS_RESULTSTR, &len); if (ret != NULL) { add_to_input_buf_csi(ret, len); vim_free(ret); return 1; } return 0; } /* * get the current composition string, in UCS-2; *lenp is the number of * *lenp is the number of Unicode characters. */ static short_u * GetCompositionString_inUCS2(HIMC hIMC, DWORD GCS, int *lenp) { LONG ret; LPWSTR wbuf = NULL; char_u *buf; if (!pImmGetContext) return NULL; /* no imm32.dll */ /* Try Unicode; this'll always work on NT regardless of codepage. */ ret = pImmGetCompositionStringW(hIMC, GCS, NULL, 0); if (ret == 0) return NULL; /* empty */ if (ret > 0) { /* Allocate the requested buffer plus space for the NUL character. */ wbuf = (LPWSTR)alloc(ret + sizeof(WCHAR)); if (wbuf != NULL) { pImmGetCompositionStringW(hIMC, GCS, wbuf, ret); *lenp = ret / sizeof(WCHAR); } return (short_u *)wbuf; } /* ret < 0; we got an error, so try the ANSI version. This'll work * on 9x/ME, but only if the codepage happens to be set to whatever * we're inputting. */ ret = pImmGetCompositionStringA(hIMC, GCS, NULL, 0); if (ret <= 0) return NULL; /* empty or error */ buf = alloc(ret); if (buf == NULL) return NULL; pImmGetCompositionStringA(hIMC, GCS, buf, ret); /* convert from codepage to UCS-2 */ MultiByteToWideChar_alloc(GetACP(), 0, buf, ret, &wbuf, lenp); vim_free(buf); return (short_u *)wbuf; } /* * void GetResultStr() * * This handles WM_IME_COMPOSITION with GCS_RESULTSTR flag on. * get complete composition string */ static char_u * GetResultStr(HWND hwnd, int GCS, int *lenp) { HIMC hIMC; /* Input context handle. */ short_u *buf = NULL; char_u *convbuf = NULL; if (!pImmGetContext || (hIMC = pImmGetContext(hwnd)) == (HIMC)0) return NULL; /* Reads in the composition string. */ buf = GetCompositionString_inUCS2(hIMC, GCS, lenp); if (buf == NULL) return NULL; convbuf = utf16_to_enc(buf, lenp); pImmReleaseContext(hwnd, hIMC); vim_free(buf); return convbuf; } #endif /* For global functions we need prototypes. */ #if (defined(FEAT_MBYTE) && defined(FEAT_MBYTE_IME)) || defined(PROTO) /* * set font to IM. */ void im_set_font(LOGFONT *lf) { HIMC hImc; if (pImmGetContext && (hImc = pImmGetContext(s_hwnd)) != (HIMC)0) { pImmSetCompositionFont(hImc, lf); pImmReleaseContext(s_hwnd, hImc); } } /* * Notify cursor position to IM. */ void im_set_position(int row, int col) { HIMC hImc; if (pImmGetContext && (hImc = pImmGetContext(s_hwnd)) != (HIMC)0) { COMPOSITIONFORM cfs; cfs.dwStyle = CFS_POINT; cfs.ptCurrentPos.x = FILL_X(col); cfs.ptCurrentPos.y = FILL_Y(row); MapWindowPoints(s_textArea, s_hwnd, &cfs.ptCurrentPos, 1); pImmSetCompositionWindow(hImc, &cfs); pImmReleaseContext(s_hwnd, hImc); } } /* * Set IM status on ("active" is TRUE) or off ("active" is FALSE). */ void im_set_active(int active) { HIMC hImc; static HIMC hImcOld = (HIMC)0; if (pImmGetContext) /* if NULL imm32.dll wasn't loaded (yet) */ { if (p_imdisable) { if (hImcOld == (HIMC)0) { hImcOld = pImmGetContext(s_hwnd); if (hImcOld) pImmAssociateContext(s_hwnd, (HIMC)0); } active = FALSE; } else if (hImcOld != (HIMC)0) { pImmAssociateContext(s_hwnd, hImcOld); hImcOld = (HIMC)0; } hImc = pImmGetContext(s_hwnd); if (hImc) { /* * for Korean ime */ HKL hKL = GetKeyboardLayout(0); if (LOWORD(hKL) == MAKELANGID(LANG_KOREAN, SUBLANG_KOREAN)) { static DWORD dwConversionSaved = 0, dwSentenceSaved = 0; static BOOL bSaved = FALSE; if (active) { /* if we have a saved conversion status, restore it */ if (bSaved) pImmSetConversionStatus(hImc, dwConversionSaved, dwSentenceSaved); bSaved = FALSE; } else { /* save conversion status and disable korean */ if (pImmGetConversionStatus(hImc, &dwConversionSaved, &dwSentenceSaved)) { bSaved = TRUE; pImmSetConversionStatus(hImc, dwConversionSaved & ~(IME_CMODE_NATIVE | IME_CMODE_FULLSHAPE), dwSentenceSaved); } } } pImmSetOpenStatus(hImc, active); pImmReleaseContext(s_hwnd, hImc); } } } /* * Get IM status. When IM is on, return not 0. Else return 0. */ int im_get_status() { int status = 0; HIMC hImc; if (pImmGetContext && (hImc = pImmGetContext(s_hwnd)) != (HIMC)0) { status = pImmGetOpenStatus(hImc) ? 1 : 0; pImmReleaseContext(s_hwnd, hImc); } return status; } #endif /* FEAT_MBYTE && FEAT_MBYTE_IME */ #if defined(FEAT_MBYTE) && !defined(FEAT_MBYTE_IME) && defined(GLOBAL_IME) /* Win32 with GLOBAL IME */ /* * Notify cursor position to IM. */ void im_set_position(int row, int col) { /* Win32 with GLOBAL IME */ POINT p; p.x = FILL_X(col); p.y = FILL_Y(row); MapWindowPoints(s_textArea, s_hwnd, &p, 1); global_ime_set_position(&p); } /* * Set IM status on ("active" is TRUE) or off ("active" is FALSE). */ void im_set_active(int active) { global_ime_set_status(active); } /* * Get IM status. When IM is on, return not 0. Else return 0. */ int im_get_status() { return global_ime_get_status(); } #endif #ifdef FEAT_MBYTE /* * Convert latin9 text "text[len]" to ucs-2 in "unicodebuf". */ static void latin9_to_ucs(char_u *text, int len, WCHAR *unicodebuf) { int c; while (--len >= 0) { c = *text++; switch (c) { case 0xa4: c = 0x20ac; break; /* euro */ case 0xa6: c = 0x0160; break; /* S hat */ case 0xa8: c = 0x0161; break; /* S -hat */ case 0xb4: c = 0x017d; break; /* Z hat */ case 0xb8: c = 0x017e; break; /* Z -hat */ case 0xbc: c = 0x0152; break; /* OE */ case 0xbd: c = 0x0153; break; /* oe */ case 0xbe: c = 0x0178; break; /* Y */ } *unicodebuf++ = c; } } #endif #ifdef FEAT_RIGHTLEFT /* * What is this for? In the case where you are using Win98 or Win2K or later, * and you are using a Hebrew font (or Arabic!), Windows does you a favor and * reverses the string sent to the TextOut... family. This sucks, because we * go to a lot of effort to do the right thing, and there doesn't seem to be a * way to tell Windblows not to do this! * * The short of it is that this 'RevOut' only gets called if you are running * one of the new, "improved" MS OSes, and only if you are running in * 'rightleft' mode. It makes display take *slightly* longer, but not * noticeably so. */ static void RevOut( HDC s_hdc, int col, int row, UINT foptions, CONST RECT *pcliprect, LPCTSTR text, UINT len, CONST INT *padding) { int ix; static int special = -1; if (special == -1) { /* Check windows version: special treatment is needed if it is NT 5 or * Win98 or higher. */ if ((os_version.dwPlatformId == VER_PLATFORM_WIN32_NT && os_version.dwMajorVersion >= 5) || (os_version.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS && (os_version.dwMajorVersion > 4 || (os_version.dwMajorVersion == 4 && os_version.dwMinorVersion > 0)))) special = 1; else special = 0; } if (special) for (ix = 0; ix < (int)len; ++ix) ExtTextOut(s_hdc, col + TEXT_X(ix), row, foptions, pcliprect, text + ix, 1, padding); else ExtTextOut(s_hdc, col, row, foptions, pcliprect, text, len, padding); } #endif void gui_mch_draw_string( int row, int col, char_u *text, int len, int flags) { static int *padding = NULL; static int pad_size = 0; int i; const RECT *pcliprect = NULL; UINT foptions = 0; #ifdef FEAT_MBYTE static WCHAR *unicodebuf = NULL; static int *unicodepdy = NULL; static int unibuflen = 0; int n = 0; #endif HPEN hpen, old_pen; int y; #ifndef MSWIN16_FASTTEXT /* * Italic and bold text seems to have an extra row of pixels at the bottom * (below where the bottom of the character should be). If we draw the * characters with a solid background, the top row of pixels in the * character below will be overwritten. We can fix this by filling in the * background ourselves, to the correct character proportions, and then * writing the character in transparent mode. Still have a problem when * the character is "_", which gets written on to the character below. * New fix: set gui.char_ascent to -1. This shifts all characters up one * pixel in their slots, which fixes the problem with the bottom row of * pixels. We still need this code because otherwise the top row of pixels * becomes a problem. - webb. */ static HBRUSH hbr_cache[2] = {NULL, NULL}; static guicolor_T brush_color[2] = {INVALCOLOR, INVALCOLOR}; static int brush_lru = 0; HBRUSH hbr; RECT rc; if (!(flags & DRAW_TRANSP)) { /* * Clear background first. * Note: FillRect() excludes right and bottom of rectangle. */ rc.left = FILL_X(col); rc.top = FILL_Y(row); #ifdef FEAT_MBYTE if (has_mbyte) { /* Compute the length in display cells. */ rc.right = FILL_X(col + mb_string2cells(text, len)); } else #endif rc.right = FILL_X(col + len); rc.bottom = FILL_Y(row + 1); /* Cache the created brush, that saves a lot of time. We need two: * one for cursor background and one for the normal background. */ if (gui.currBgColor == brush_color[0]) { hbr = hbr_cache[0]; brush_lru = 1; } else if (gui.currBgColor == brush_color[1]) { hbr = hbr_cache[1]; brush_lru = 0; } else { if (hbr_cache[brush_lru] != NULL) DeleteBrush(hbr_cache[brush_lru]); hbr_cache[brush_lru] = CreateSolidBrush(gui.currBgColor); brush_color[brush_lru] = gui.currBgColor; hbr = hbr_cache[brush_lru]; brush_lru = !brush_lru; } FillRect(s_hdc, &rc, hbr); SetBkMode(s_hdc, TRANSPARENT); /* * When drawing block cursor, prevent inverted character spilling * over character cell (can happen with bold/italic) */ if (flags & DRAW_CURSOR) { pcliprect = &rc; foptions = ETO_CLIPPED; } } #else /* * The alternative would be to write the characters in opaque mode, but * when the text is not exactly the same proportions as normal text, too * big or too little a rectangle gets drawn for the background. */ SetBkMode(s_hdc, OPAQUE); SetBkColor(s_hdc, gui.currBgColor); #endif SetTextColor(s_hdc, gui.currFgColor); SelectFont(s_hdc, gui.currFont); if (pad_size != Columns || padding == NULL || padding[0] != gui.char_width) { vim_free(padding); pad_size = Columns; /* Don't give an out-of-memory message here, it would call us * recursively. */ padding = (int *)lalloc(pad_size * sizeof(int), FALSE); if (padding != NULL) for (i = 0; i < pad_size; i++) padding[i] = gui.char_width; } /* On NT, tell the font renderer not to "help" us with Hebrew and Arabic * text. This doesn't work in 9x, so we have to deal with it manually on * those systems. */ if (os_version.dwPlatformId == VER_PLATFORM_WIN32_NT) foptions |= ETO_IGNORELANGUAGE; /* * We have to provide the padding argument because italic and bold versions * of fixed-width fonts are often one pixel or so wider than their normal * versions. * No check for DRAW_BOLD, Windows will have done it already. */ #ifdef FEAT_MBYTE /* Check if there are any UTF-8 characters. If not, use normal text * output to speed up output. */ if (enc_utf8) for (n = 0; n < len; ++n) if (text[n] >= 0x80) break; /* Check if the Unicode buffer exists and is big enough. Create it * with the same length as the multi-byte string, the number of wide * characters is always equal or smaller. */ if ((enc_utf8 || (enc_codepage > 0 && (int)GetACP() != enc_codepage) || enc_latin9) && (unicodebuf == NULL || len > unibuflen)) { vim_free(unicodebuf); unicodebuf = (WCHAR *)lalloc(len * sizeof(WCHAR), FALSE); vim_free(unicodepdy); unicodepdy = (int *)lalloc(len * sizeof(int), FALSE); unibuflen = len; } if (enc_utf8 && n < len && unicodebuf != NULL) { /* Output UTF-8 characters. Caller has already separated * composing characters. */ int i; int wlen; /* string length in words */ int clen; /* string length in characters */ int cells; /* cell width of string up to composing char */ int cw; /* width of current cell */ int c; wlen = 0; clen = 0; cells = 0; for (i = 0; i < len; ) { c = utf_ptr2char(text + i); if (c >= 0x10000) { /* Turn into UTF-16 encoding. */ unicodebuf[wlen++] = ((c - 0x10000) >> 10) + 0xD800; unicodebuf[wlen++] = ((c - 0x10000) & 0x3ff) + 0xDC00; } else { unicodebuf[wlen++] = c; } cw = utf_char2cells(c); if (cw > 2) /* don't use 4 for unprintable char */ cw = 1; if (unicodepdy != NULL) { /* Use unicodepdy to make characters fit as we expect, even * when the font uses different widths (e.g., bold character * is wider). */ unicodepdy[clen] = cw * gui.char_width; } cells += cw; i += utfc_ptr2len_len(text + i, len - i); ++clen; } ExtTextOutW(s_hdc, TEXT_X(col), TEXT_Y(row), foptions, pcliprect, unicodebuf, wlen, unicodepdy); len = cells; /* used for underlining */ } else if ((enc_codepage > 0 && (int)GetACP() != enc_codepage) || enc_latin9) { /* If we want to display codepage data, and the current CP is not the * ANSI one, we need to go via Unicode. */ if (unicodebuf != NULL) { if (enc_latin9) latin9_to_ucs(text, len, unicodebuf); else len = MultiByteToWideChar(enc_codepage, MB_PRECOMPOSED, (char *)text, len, (LPWSTR)unicodebuf, unibuflen); if (len != 0) { /* Use unicodepdy to make characters fit as we expect, even * when the font uses different widths (e.g., bold character * is wider). */ if (unicodepdy != NULL) { int i; int cw; for (i = 0; i < len; ++i) { cw = utf_char2cells(unicodebuf[i]); if (cw > 2) cw = 1; unicodepdy[i] = cw * gui.char_width; } } ExtTextOutW(s_hdc, TEXT_X(col), TEXT_Y(row), foptions, pcliprect, unicodebuf, len, unicodepdy); } } } else #endif { #ifdef FEAT_RIGHTLEFT /* If we can't use ETO_IGNORELANGUAGE, we can't tell Windows not to * mess up RL text, so we have to draw it character-by-character. * Only do this if RL is on, since it's slow. */ if (curwin->w_p_rl && !(foptions & ETO_IGNORELANGUAGE)) RevOut(s_hdc, TEXT_X(col), TEXT_Y(row), foptions, pcliprect, (char *)text, len, padding); else #endif ExtTextOut(s_hdc, TEXT_X(col), TEXT_Y(row), foptions, pcliprect, (char *)text, len, padding); } /* Underline */ if (flags & DRAW_UNDERL) { hpen = CreatePen(PS_SOLID, 1, gui.currFgColor); old_pen = SelectObject(s_hdc, hpen); /* When p_linespace is 0, overwrite the bottom row of pixels. * Otherwise put the line just below the character. */ y = FILL_Y(row + 1) - 1; #ifndef MSWIN16_FASTTEXT if (p_linespace > 1) y -= p_linespace - 1; #endif MoveToEx(s_hdc, FILL_X(col), y, NULL); /* Note: LineTo() excludes the last pixel in the line. */ LineTo(s_hdc, FILL_X(col + len), y); DeleteObject(SelectObject(s_hdc, old_pen)); } /* Undercurl */ if (flags & DRAW_UNDERC) { int x; int offset; static const int val[8] = {1, 0, 0, 0, 1, 2, 2, 2 }; y = FILL_Y(row + 1) - 1; for (x = FILL_X(col); x < FILL_X(col + len); ++x) { offset = val[x % 8]; SetPixel(s_hdc, x, y - offset, gui.currSpColor); } } } /* * Output routines. */ /* Flush any output to the screen */ void gui_mch_flush(void) { # if defined(__BORLANDC__) /* * The GdiFlush declaration (in Borland C 5.01 <wingdi.h>) is not a * prototype declaration. * The compiler complains if __stdcall is not used in both declarations. */ BOOL __stdcall GdiFlush(void); # endif GdiFlush(); } static void clear_rect(RECT *rcp) { HBRUSH hbr; hbr = CreateSolidBrush(gui.back_pixel); FillRect(s_hdc, rcp, hbr); DeleteBrush(hbr); } void gui_mch_get_screen_dimensions(int *screen_w, int *screen_h) { RECT workarea_rect; get_work_area(&workarea_rect); *screen_w = workarea_rect.right - workarea_rect.left - GetSystemMetrics(SM_CXFRAME) * 2; /* FIXME: dirty trick: Because the gui_get_base_height() doesn't include * the menubar for MSwin, we subtract it from the screen height, so that * the window size can be made to fit on the screen. */ *screen_h = workarea_rect.bottom - workarea_rect.top - GetSystemMetrics(SM_CYFRAME) * 2 - GetSystemMetrics(SM_CYCAPTION) #ifdef FEAT_MENU - gui_mswin_get_menu_height(FALSE) #endif ; } #if defined(FEAT_MENU) || defined(PROTO) /* * Add a sub menu to the menu bar. */ void gui_mch_add_menu( vimmenu_T *menu, int pos) { vimmenu_T *parent = menu->parent; menu->submenu_id = CreatePopupMenu(); menu->id = s_menu_id++; if (menu_is_menubar(menu->name)) { if (is_winnt_3()) { InsertMenu((parent == NULL) ? s_menuBar : parent->submenu_id, (UINT)pos, MF_POPUP | MF_STRING | MF_BYPOSITION, (long_u)menu->submenu_id, (LPCTSTR) menu->name); } else { #ifdef FEAT_MBYTE WCHAR *wn = NULL; int n; if (enc_codepage >= 0 && (int)GetACP() != enc_codepage) { /* 'encoding' differs from active codepage: convert menu name * and use wide function */ wn = enc_to_utf16(menu->name, NULL); if (wn != NULL) { MENUITEMINFOW infow; infow.cbSize = sizeof(infow); infow.fMask = MIIM_DATA | MIIM_TYPE | MIIM_ID | MIIM_SUBMENU; infow.dwItemData = (long_u)menu; infow.wID = menu->id; infow.fType = MFT_STRING; infow.dwTypeData = wn; infow.cch = (UINT)wcslen(wn); infow.hSubMenu = menu->submenu_id; n = InsertMenuItemW((parent == NULL) ? s_menuBar : parent->submenu_id, (UINT)pos, TRUE, &infow); vim_free(wn); if (n == 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED) /* Failed, try using non-wide function. */ wn = NULL; } } if (wn == NULL) #endif { MENUITEMINFO info; info.cbSize = sizeof(info); info.fMask = MIIM_DATA | MIIM_TYPE | MIIM_ID | MIIM_SUBMENU; info.dwItemData = (long_u)menu; info.wID = menu->id; info.fType = MFT_STRING; info.dwTypeData = (LPTSTR)menu->name; info.cch = (UINT)STRLEN(menu->name); info.hSubMenu = menu->submenu_id; InsertMenuItem((parent == NULL) ? s_menuBar : parent->submenu_id, (UINT)pos, TRUE, &info); } } } /* Fix window size if menu may have wrapped */ if (parent == NULL) gui_mswin_get_menu_height(!gui.starting); #ifdef FEAT_TEAROFF else if (IsWindow(parent->tearoff_handle)) rebuild_tearoff(parent); #endif } void gui_mch_show_popupmenu(vimmenu_T *menu) { POINT mp; (void)GetCursorPos((LPPOINT)&mp); gui_mch_show_popupmenu_at(menu, (int)mp.x, (int)mp.y); } void gui_make_popup(char_u *path_name, int mouse_pos) { vimmenu_T *menu = gui_find_menu(path_name); if (menu != NULL) { POINT p; /* Find the position of the current cursor */ GetDCOrgEx(s_hdc, &p); if (mouse_pos) { int mx, my; gui_mch_getmouse(&mx, &my); p.x += mx; p.y += my; } else if (curwin != NULL) { p.x += TEXT_X(W_WINCOL(curwin) + curwin->w_wcol + 1); p.y += TEXT_Y(W_WINROW(curwin) + curwin->w_wrow + 1); } msg_scroll = FALSE; gui_mch_show_popupmenu_at(menu, (int)p.x, (int)p.y); } } #if defined(FEAT_TEAROFF) || defined(PROTO) /* * Given a menu descriptor, e.g. "File.New", find it in the menu hierarchy and * create it as a pseudo-"tearoff menu". */ void gui_make_tearoff(char_u *path_name) { vimmenu_T *menu = gui_find_menu(path_name); /* Found the menu, so tear it off. */ if (menu != NULL) gui_mch_tearoff(menu->dname, menu, 0xffffL, 0xffffL); } #endif /* * Add a menu item to a menu */ void gui_mch_add_menu_item( vimmenu_T *menu, int idx) { vimmenu_T *parent = menu->parent; menu->id = s_menu_id++; menu->submenu_id = NULL; #ifdef FEAT_TEAROFF if (STRNCMP(menu->name, TEAR_STRING, TEAR_LEN) == 0) { InsertMenu(parent->submenu_id, (UINT)idx, MF_BITMAP|MF_BYPOSITION, (UINT)menu->id, (LPCTSTR) s_htearbitmap); } else #endif #ifdef FEAT_TOOLBAR if (menu_is_toolbar(parent->name)) { TBBUTTON newtb; vim_memset(&newtb, 0, sizeof(newtb)); if (menu_is_separator(menu->name)) { newtb.iBitmap = 0; newtb.fsStyle = TBSTYLE_SEP; } else { newtb.iBitmap = get_toolbar_bitmap(menu); newtb.fsStyle = TBSTYLE_BUTTON; } newtb.idCommand = menu->id; newtb.fsState = TBSTATE_ENABLED; newtb.iString = 0; SendMessage(s_toolbarhwnd, TB_INSERTBUTTON, (WPARAM)idx, (LPARAM)&newtb); menu->submenu_id = (HMENU)-1; } else #endif { #ifdef FEAT_MBYTE WCHAR *wn = NULL; int n; if (enc_codepage >= 0 && (int)GetACP() != enc_codepage) { /* 'encoding' differs from active codepage: convert menu item name * and use wide function */ wn = enc_to_utf16(menu->name, NULL); if (wn != NULL) { n = InsertMenuW(parent->submenu_id, (UINT)idx, (menu_is_separator(menu->name) ? MF_SEPARATOR : MF_STRING) | MF_BYPOSITION, (UINT)menu->id, wn); vim_free(wn); if (n == 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED) /* Failed, try using non-wide function. */ wn = NULL; } } if (wn == NULL) #endif InsertMenu(parent->submenu_id, (UINT)idx, (menu_is_separator(menu->name) ? MF_SEPARATOR : MF_STRING) | MF_BYPOSITION, (UINT)menu->id, (LPCTSTR)menu->name); #ifdef FEAT_TEAROFF if (IsWindow(parent->tearoff_handle)) rebuild_tearoff(parent); #endif } } /* * Destroy the machine specific menu widget. */ void gui_mch_destroy_menu(vimmenu_T *menu) { #ifdef FEAT_TOOLBAR /* * is this a toolbar button? */ if (menu->submenu_id == (HMENU)-1) { int iButton; iButton = (int)SendMessage(s_toolbarhwnd, TB_COMMANDTOINDEX, (WPARAM)menu->id, 0); SendMessage(s_toolbarhwnd, TB_DELETEBUTTON, (WPARAM)iButton, 0); } else #endif { if (menu->parent != NULL && menu_is_popup(menu->parent->dname) && menu->parent->submenu_id != NULL) RemoveMenu(menu->parent->submenu_id, menu->id, MF_BYCOMMAND); else RemoveMenu(s_menuBar, menu->id, MF_BYCOMMAND); if (menu->submenu_id != NULL) DestroyMenu(menu->submenu_id); #ifdef FEAT_TEAROFF if (IsWindow(menu->tearoff_handle)) DestroyWindow(menu->tearoff_handle); if (menu->parent != NULL && menu->parent->children != NULL && IsWindow(menu->parent->tearoff_handle)) { /* This menu must not show up when rebuilding the tearoff window. */ menu->modes = 0; rebuild_tearoff(menu->parent); } #endif } } #ifdef FEAT_TEAROFF static void rebuild_tearoff(vimmenu_T *menu) { /*hackish*/ char_u tbuf[128]; RECT trect; RECT rct; RECT roct; int x, y; HWND thwnd = menu->tearoff_handle; GetWindowText(thwnd, tbuf, 127); if (GetWindowRect(thwnd, &trect) && GetWindowRect(s_hwnd, &rct) && GetClientRect(s_hwnd, &roct)) { x = trect.left - rct.left; y = (trect.top - rct.bottom + roct.bottom); } else { x = y = 0xffffL; } DestroyWindow(thwnd); if (menu->children != NULL) { gui_mch_tearoff(tbuf, menu, x, y); if (IsWindow(menu->tearoff_handle)) (void) SetWindowPos(menu->tearoff_handle, NULL, (int)trect.left, (int)trect.top, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); } } #endif /* FEAT_TEAROFF */ /* * Make a menu either grey or not grey. */ void gui_mch_menu_grey( vimmenu_T *menu, int grey) { #ifdef FEAT_TOOLBAR /* * is this a toolbar button? */ if (menu->submenu_id == (HMENU)-1) { SendMessage(s_toolbarhwnd, TB_ENABLEBUTTON, (WPARAM)menu->id, (LPARAM) MAKELONG((grey ? FALSE : TRUE), 0) ); } else #endif if (grey) EnableMenuItem(s_menuBar, menu->id, MF_BYCOMMAND | MF_GRAYED); else EnableMenuItem(s_menuBar, menu->id, MF_BYCOMMAND | MF_ENABLED); #ifdef FEAT_TEAROFF if ((menu->parent != NULL) && (IsWindow(menu->parent->tearoff_handle))) { WORD menuID; HWND menuHandle; /* * A tearoff button has changed state. */ if (menu->children == NULL) menuID = (WORD)(menu->id); else menuID = (WORD)((long_u)(menu->submenu_id) | (DWORD)0x8000); menuHandle = GetDlgItem(menu->parent->tearoff_handle, menuID); if (menuHandle) EnableWindow(menuHandle, !grey); } #endif } #endif /* FEAT_MENU */ /* define some macros used to make the dialogue creation more readable */ #define add_string(s) strcpy((LPSTR)p, s); (LPSTR)p += (strlen((LPSTR)p) + 1) #define add_word(x) *p++ = (x) #define add_long(x) dwp = (DWORD *)p; *dwp++ = (x); p = (WORD *)dwp #if defined(FEAT_GUI_DIALOG) || defined(PROTO) /* * stuff for dialogs */ /* * The callback routine used by all the dialogs. Very simple. First, * acknowledges the INITDIALOG message so that Windows knows to do standard * dialog stuff (Return = default, Esc = cancel....) Second, if a button is * pressed, return that button's ID - IDCANCEL (2), which is the button's * number. */ /*ARGSUSED*/ static LRESULT CALLBACK dialog_callback( HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { if (message == WM_INITDIALOG) { CenterWindow(hwnd, GetWindow(hwnd, GW_OWNER)); /* Set focus to the dialog. Set the default button, if specified. */ (void)SetFocus(hwnd); if (dialog_default_button > IDCANCEL) (void)SetFocus(GetDlgItem(hwnd, dialog_default_button)); else /* We don't have a default, set focus on another element of the * dialog window, probably the icon */ (void)SetFocus(GetDlgItem(hwnd, DLG_NONBUTTON_CONTROL)); return FALSE; } if (message == WM_COMMAND) { int button = LOWORD(wParam); /* Don't end the dialog if something was selected that was * not a button. */ if (button >= DLG_NONBUTTON_CONTROL) return TRUE; /* If the edit box exists, copy the string. */ if (s_textfield != NULL) { # if defined(FEAT_MBYTE) && defined(WIN3264) /* If the OS is Windows NT, and 'encoding' differs from active * codepage: use wide function and convert text. */ if (os_version.dwPlatformId == VER_PLATFORM_WIN32_NT && enc_codepage >= 0 && (int)GetACP() != enc_codepage) { WCHAR *wp = (WCHAR *)alloc(IOSIZE * sizeof(WCHAR)); char_u *p; GetDlgItemTextW(hwnd, DLG_NONBUTTON_CONTROL + 2, wp, IOSIZE); p = utf16_to_enc(wp, NULL); vim_strncpy(s_textfield, p, IOSIZE); vim_free(p); vim_free(wp); } else # endif GetDlgItemText(hwnd, DLG_NONBUTTON_CONTROL + 2, s_textfield, IOSIZE); } /* * Need to check for IDOK because if the user just hits Return to * accept the default value, some reason this is what we get. */ if (button == IDOK) { if (dialog_default_button > IDCANCEL) EndDialog(hwnd, dialog_default_button); } else EndDialog(hwnd, button - IDCANCEL); return TRUE; } if ((message == WM_SYSCOMMAND) && (wParam == SC_CLOSE)) { EndDialog(hwnd, 0); return TRUE; } return FALSE; } /* * Create a dialog dynamically from the parameter strings. * type = type of dialog (question, alert, etc.) * title = dialog title. may be NULL for default title. * message = text to display. Dialog sizes to accommodate it. * buttons = '\n' separated list of button captions, default first. * dfltbutton = number of default button. * * This routine returns 1 if the first button is pressed, * 2 for the second, etc. * * 0 indicates Esc was pressed. * -1 for unexpected error * * If stubbing out this fn, return 1. */ static const char_u *dlg_icons[] = /* must match names in resource file */ { "IDR_VIM", "IDR_VIM_ERROR", "IDR_VIM_ALERT", "IDR_VIM_INFO", "IDR_VIM_QUESTION" }; int gui_mch_dialog( int type, char_u *title, char_u *message, char_u *buttons, int dfltbutton, char_u *textfield, int ex_cmd) { WORD *p, *pdlgtemplate, *pnumitems; DWORD *dwp; int numButtons; int *buttonWidths, *buttonPositions; int buttonYpos; int nchar, i; DWORD lStyle; int dlgwidth = 0; int dlgheight; int editboxheight; int horizWidth = 0; int msgheight; char_u *pstart; char_u *pend; char_u *last_white; char_u *tbuffer; RECT rect; HWND hwnd; HDC hdc; HFONT font, oldFont; TEXTMETRIC fontInfo; int fontHeight; int textWidth, minButtonWidth, messageWidth; int maxDialogWidth; int maxDialogHeight; int scroll_flag = 0; int vertical; int dlgPaddingX; int dlgPaddingY; #ifdef USE_SYSMENU_FONT LOGFONT lfSysmenu; int use_lfSysmenu = FALSE; #endif garray_T ga; int l; #ifndef NO_CONSOLE /* Don't output anything in silent mode ("ex -s") */ if (silent_mode) return dfltbutton; /* return default option */ #endif if (s_hwnd == NULL) get_dialog_font_metrics(); if ((type < 0) || (type > VIM_LAST_TYPE)) type = 0; /* allocate some memory for dialog template */ /* TODO should compute this really */ pdlgtemplate = p = (PWORD)LocalAlloc(LPTR, DLG_ALLOC_SIZE + STRLEN(message) * 2); if (p == NULL) return -1; /* * make a copy of 'buttons' to fiddle with it. complier grizzles because * vim_strsave() doesn't take a const arg (why not?), so cast away the * const. */ tbuffer = vim_strsave(buttons); if (tbuffer == NULL) return -1; --dfltbutton; /* Change from one-based to zero-based */ /* Count buttons */ numButtons = 1; for (i = 0; tbuffer[i] != '\0'; i++) { if (tbuffer[i] == DLG_BUTTON_SEP) numButtons++; } if (dfltbutton >= numButtons) dfltbutton = -1; /* Allocate array to hold the width of each button */ buttonWidths = (int *)lalloc(numButtons * sizeof(int), TRUE); if (buttonWidths == NULL) return -1; /* Allocate array to hold the X position of each button */ buttonPositions = (int *)lalloc(numButtons * sizeof(int), TRUE); if (buttonPositions == NULL) return -1; /* * Calculate how big the dialog must be. */ hwnd = GetDesktopWindow(); hdc = GetWindowDC(hwnd); #ifdef USE_SYSMENU_FONT if (gui_w32_get_menu_font(&lfSysmenu) == OK) { font = CreateFontIndirect(&lfSysmenu); use_lfSysmenu = TRUE; } else #endif font = CreateFont(-DLG_FONT_POINT_SIZE, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, VARIABLE_PITCH , DLG_FONT_NAME); if (s_usenewlook) { oldFont = SelectFont(hdc, font); dlgPaddingX = DLG_PADDING_X; dlgPaddingY = DLG_PADDING_Y; } else { oldFont = SelectFont(hdc, GetStockObject(SYSTEM_FONT)); dlgPaddingX = DLG_OLD_STYLE_PADDING_X; dlgPaddingY = DLG_OLD_STYLE_PADDING_Y; } GetTextMetrics(hdc, &fontInfo); fontHeight = fontInfo.tmHeight; /* Minimum width for horizontal button */ minButtonWidth = GetTextWidth(hdc, "Cancel", 6); /* Maximum width of a dialog, if possible */ if (s_hwnd == NULL) { RECT workarea_rect; /* We don't have a window, use the desktop area. */ get_work_area(&workarea_rect); maxDialogWidth = workarea_rect.right - workarea_rect.left - 100; if (maxDialogWidth > 600) maxDialogWidth = 600; maxDialogHeight = workarea_rect.bottom - workarea_rect.top - 100; } else { /* Use our own window for the size, unless it's very small. */ GetWindowRect(s_hwnd, &rect); maxDialogWidth = rect.right - rect.left - GetSystemMetrics(SM_CXFRAME) * 2; if (maxDialogWidth < DLG_MIN_MAX_WIDTH) maxDialogWidth = DLG_MIN_MAX_WIDTH; maxDialogHeight = rect.bottom - rect.top - GetSystemMetrics(SM_CXFRAME) * 2; if (maxDialogHeight < DLG_MIN_MAX_HEIGHT) maxDialogHeight = DLG_MIN_MAX_HEIGHT; } /* Set dlgwidth to width of message. * Copy the message into "ga", changing NL to CR-NL and inserting line * breaks where needed. */ pstart = message; messageWidth = 0; msgheight = 0; ga_init2(&ga, sizeof(char), 500); do { msgheight += fontHeight; /* at least one line */ /* Need to figure out where to break the string. The system does it * at a word boundary, which would mean we can't compute the number of * wrapped lines. */ textWidth = 0; last_white = NULL; for (pend = pstart; *pend != NUL && *pend != '\n'; ) { #ifdef FEAT_MBYTE l = (*mb_ptr2len)(pend); #else l = 1; #endif if (l == 1 && vim_iswhite(*pend) && textWidth > maxDialogWidth * 3 / 4) last_white = pend; textWidth += GetTextWidth(hdc, pend, l); if (textWidth >= maxDialogWidth) { /* Line will wrap. */ messageWidth = maxDialogWidth; msgheight += fontHeight; textWidth = 0; if (last_white != NULL) { /* break the line just after a space */ ga.ga_len -= (int)(pend - (last_white + 1)); pend = last_white + 1; last_white = NULL; } ga_append(&ga, '\r'); ga_append(&ga, '\n'); continue; } while (--l >= 0) ga_append(&ga, *pend++); } if (textWidth > messageWidth) messageWidth = textWidth; ga_append(&ga, '\r'); ga_append(&ga, '\n'); pstart = pend + 1; } while (*pend != NUL); if (ga.ga_data != NULL) message = ga.ga_data; messageWidth += 10; /* roundoff space */ /* Restrict the size to a maximum. Causes a scrollbar to show up. */ if (msgheight > maxDialogHeight) { msgheight = maxDialogHeight; scroll_flag = WS_VSCROLL; messageWidth += GetSystemMetrics(SM_CXVSCROLL); } /* Add width of icon to dlgwidth, and some space */ dlgwidth = messageWidth + DLG_ICON_WIDTH + 3 * dlgPaddingX; if (msgheight < DLG_ICON_HEIGHT) msgheight = DLG_ICON_HEIGHT; /* * Check button names. A long one will make the dialog wider. * When called early (-register error message) p_go isn't initialized. */ vertical = (p_go != NULL && vim_strchr(p_go, GO_VERTICAL) != NULL); if (!vertical) { // Place buttons horizontally if they fit. horizWidth = dlgPaddingX; pstart = tbuffer; i = 0; do { pend = vim_strchr(pstart, DLG_BUTTON_SEP); if (pend == NULL) pend = pstart + STRLEN(pstart); // Last button name. textWidth = GetTextWidth(hdc, pstart, (int)(pend - pstart)); if (textWidth < minButtonWidth) textWidth = minButtonWidth; textWidth += dlgPaddingX; /* Padding within button */ buttonWidths[i] = textWidth; buttonPositions[i++] = horizWidth; horizWidth += textWidth + dlgPaddingX; /* Pad between buttons */ pstart = pend + 1; } while (*pend != NUL); if (horizWidth > maxDialogWidth) vertical = TRUE; // Too wide to fit on the screen. else if (horizWidth > dlgwidth) dlgwidth = horizWidth; } if (vertical) { // Stack buttons vertically. pstart = tbuffer; do { pend = vim_strchr(pstart, DLG_BUTTON_SEP); if (pend == NULL) pend = pstart + STRLEN(pstart); // Last button name. textWidth = GetTextWidth(hdc, pstart, (int)(pend - pstart)); textWidth += dlgPaddingX; /* Padding within button */ textWidth += DLG_VERT_PADDING_X * 2; /* Padding around button */ if (textWidth > dlgwidth) dlgwidth = textWidth; pstart = pend + 1; } while (*pend != NUL); } if (dlgwidth < DLG_MIN_WIDTH) dlgwidth = DLG_MIN_WIDTH; /* Don't allow a really thin dialog!*/ /* start to fill in the dlgtemplate information. addressing by WORDs */ if (s_usenewlook) lStyle = DS_MODALFRAME | WS_CAPTION |DS_3DLOOK| WS_VISIBLE |DS_SETFONT; else lStyle = DS_MODALFRAME | WS_CAPTION |DS_3DLOOK| WS_VISIBLE; add_long(lStyle); add_long(0); // (lExtendedStyle) pnumitems = p; /*save where the number of items must be stored*/ add_word(0); // NumberOfItems(will change later) add_word(10); // x add_word(10); // y add_word(PixelToDialogX(dlgwidth)); // cx // Dialog height. if (vertical) dlgheight = msgheight + 2 * dlgPaddingY + DLG_VERT_PADDING_Y + 2 * fontHeight * numButtons; else dlgheight = msgheight + 3 * dlgPaddingY + 2 * fontHeight; // Dialog needs to be taller if contains an edit box. editboxheight = fontHeight + dlgPaddingY + 4 * DLG_VERT_PADDING_Y; if (textfield != NULL) dlgheight += editboxheight; add_word(PixelToDialogY(dlgheight)); add_word(0); // Menu add_word(0); // Class /* copy the title of the dialog */ nchar = nCopyAnsiToWideChar(p, (title ? (LPSTR)title : (LPSTR)("Vim "VIM_VERSION_MEDIUM))); p += nchar; if (s_usenewlook) { /* do the font, since DS_3DLOOK doesn't work properly */ #ifdef USE_SYSMENU_FONT if (use_lfSysmenu) { /* point size */ *p++ = -MulDiv(lfSysmenu.lfHeight, 72, GetDeviceCaps(hdc, LOGPIXELSY)); nchar = nCopyAnsiToWideChar(p, TEXT(lfSysmenu.lfFaceName)); } else #endif { *p++ = DLG_FONT_POINT_SIZE; // point size nchar = nCopyAnsiToWideChar(p, TEXT(DLG_FONT_NAME)); } p += nchar; } buttonYpos = msgheight + 2 * dlgPaddingY; if (textfield != NULL) buttonYpos += editboxheight; pstart = tbuffer; if (!vertical) horizWidth = (dlgwidth - horizWidth) / 2; /* Now it's X offset */ for (i = 0; i < numButtons; i++) { /* get end of this button. */ for ( pend = pstart; *pend && (*pend != DLG_BUTTON_SEP); pend++) ; if (*pend) *pend = '\0'; /* * old NOTE: * setting the BS_DEFPUSHBUTTON style doesn't work because Windows sets * the focus to the first tab-able button and in so doing makes that * the default!! Grrr. Workaround: Make the default button the only * one with WS_TABSTOP style. Means user can't tab between buttons, but * he/she can use arrow keys. * * new NOTE: BS_DEFPUSHBUTTON is required to be able to select the * right button when hitting <Enter>. E.g., for the ":confirm quit" * dialog. Also needed for when the textfield is the default control. * It appears to work now (perhaps not on Win95?). */ if (vertical) { p = add_dialog_element(p, (i == dfltbutton ? BS_DEFPUSHBUTTON : BS_PUSHBUTTON) | WS_TABSTOP, PixelToDialogX(DLG_VERT_PADDING_X), PixelToDialogY(buttonYpos /* TBK */ + 2 * fontHeight * i), PixelToDialogX(dlgwidth - 2 * DLG_VERT_PADDING_X), (WORD)(PixelToDialogY(2 * fontHeight) - 1), (WORD)(IDCANCEL + 1 + i), (WORD)0x0080, pstart); } else { p = add_dialog_element(p, (i == dfltbutton ? BS_DEFPUSHBUTTON : BS_PUSHBUTTON) | WS_TABSTOP, PixelToDialogX(horizWidth + buttonPositions[i]), PixelToDialogY(buttonYpos), /* TBK */ PixelToDialogX(buttonWidths[i]), (WORD)(PixelToDialogY(2 * fontHeight) - 1), (WORD)(IDCANCEL + 1 + i), (WORD)0x0080, pstart); } pstart = pend + 1; /*next button*/ } *pnumitems += numButtons; /* Vim icon */ p = add_dialog_element(p, SS_ICON, PixelToDialogX(dlgPaddingX), PixelToDialogY(dlgPaddingY), PixelToDialogX(DLG_ICON_WIDTH), PixelToDialogY(DLG_ICON_HEIGHT), DLG_NONBUTTON_CONTROL + 0, (WORD)0x0082, dlg_icons[type]); /* Dialog message */ p = add_dialog_element(p, ES_LEFT|scroll_flag|ES_MULTILINE|ES_READONLY, PixelToDialogX(2 * dlgPaddingX + DLG_ICON_WIDTH), PixelToDialogY(dlgPaddingY), (WORD)(PixelToDialogX(messageWidth) + 1), PixelToDialogY(msgheight), DLG_NONBUTTON_CONTROL + 1, (WORD)0x0081, message); /* Edit box */ if (textfield != NULL) { p = add_dialog_element(p, ES_LEFT|ES_AUTOHSCROLL|WS_TABSTOP|WS_BORDER, PixelToDialogX(2 * dlgPaddingX), PixelToDialogY(2 * dlgPaddingY + msgheight), PixelToDialogX(dlgwidth - 4 * dlgPaddingX), PixelToDialogY(fontHeight + dlgPaddingY), DLG_NONBUTTON_CONTROL + 2, (WORD)0x0081, textfield); *pnumitems += 1; } *pnumitems += 2; SelectFont(hdc, oldFont); DeleteObject(font); ReleaseDC(hwnd, hdc); /* Let the dialog_callback() function know which button to make default * If we have an edit box, make that the default. We also need to tell * dialog_callback() if this dialog contains an edit box or not. We do * this by setting s_textfield if it does. */ if (textfield != NULL) { dialog_default_button = DLG_NONBUTTON_CONTROL + 2; s_textfield = textfield; } else { dialog_default_button = IDCANCEL + 1 + dfltbutton; s_textfield = NULL; } /* show the dialog box modally and get a return value */ nchar = (int)DialogBoxIndirect( s_hinst, (LPDLGTEMPLATE)pdlgtemplate, s_hwnd, (DLGPROC)dialog_callback); LocalFree(LocalHandle(pdlgtemplate)); vim_free(tbuffer); vim_free(buttonWidths); vim_free(buttonPositions); vim_free(ga.ga_data); /* Focus back to our window (for when MDI is used). */ (void)SetFocus(s_hwnd); return nchar; } #endif /* FEAT_GUI_DIALOG */ /* * Put a simple element (basic class) onto a dialog template in memory. * return a pointer to where the next item should be added. * * parameters: * lStyle = additional style flags * (be careful, NT3.51 & Win32s will ignore the new ones) * x,y = x & y positions IN DIALOG UNITS * w,h = width and height IN DIALOG UNITS * Id = ID used in messages * clss = class ID, e.g 0x0080 for a button, 0x0082 for a static * caption = usually text or resource name * * TODO: use the length information noted here to enable the dialog creation * routines to work out more exactly how much memory they need to alloc. */ static PWORD add_dialog_element( PWORD p, DWORD lStyle, WORD x, WORD y, WORD w, WORD h, WORD Id, WORD clss, const char *caption) { int nchar; p = lpwAlign(p); /* Align to dword boundary*/ lStyle = lStyle | WS_VISIBLE | WS_CHILD; *p++ = LOWORD(lStyle); *p++ = HIWORD(lStyle); *p++ = 0; // LOWORD (lExtendedStyle) *p++ = 0; // HIWORD (lExtendedStyle) *p++ = x; *p++ = y; *p++ = w; *p++ = h; *p++ = Id; //9 or 10 words in all *p++ = (WORD)0xffff; *p++ = clss; //2 more here nchar = nCopyAnsiToWideChar(p, (LPSTR)caption); //strlen(caption)+1 p += nchar; *p++ = 0; // advance pointer over nExtraStuff WORD - 2 more return p; //total = 15+ (strlen(caption)) words // = 30 + 2(strlen(caption) bytes reqd } /* * Helper routine. Take an input pointer, return closest pointer that is * aligned on a DWORD (4 byte) boundary. Taken from the Win32SDK samples. */ static LPWORD lpwAlign( LPWORD lpIn) { long_u ul; ul = (long_u)lpIn; ul += 3; ul >>= 2; ul <<= 2; return (LPWORD)ul; } /* * Helper routine. Takes second parameter as Ansi string, copies it to first * parameter as wide character (16-bits / char) string, and returns integer * number of wide characters (words) in string (including the trailing wide * char NULL). Partly taken from the Win32SDK samples. */ static int nCopyAnsiToWideChar( LPWORD lpWCStr, LPSTR lpAnsiIn) { int nChar = 0; #ifdef FEAT_MBYTE int len = lstrlen(lpAnsiIn) + 1; /* include NUL character */ int i; WCHAR *wn; if (enc_codepage == 0 && (int)GetACP() != enc_codepage) { /* Not a codepage, use our own conversion function. */ wn = enc_to_utf16(lpAnsiIn, NULL); if (wn != NULL) { wcscpy(lpWCStr, wn); nChar = (int)wcslen(wn) + 1; vim_free(wn); } } if (nChar == 0) /* Use Win32 conversion function. */ nChar = MultiByteToWideChar( enc_codepage > 0 ? enc_codepage : CP_ACP, MB_PRECOMPOSED, lpAnsiIn, len, lpWCStr, len); for (i = 0; i < nChar; ++i) if (lpWCStr[i] == (WORD)'\t') /* replace tabs with spaces */ lpWCStr[i] = (WORD)' '; #else do { if (*lpAnsiIn == '\t') *lpWCStr++ = (WORD)' '; else *lpWCStr++ = (WORD)*lpAnsiIn; nChar++; } while (*lpAnsiIn++); #endif return nChar; } #ifdef FEAT_TEAROFF /* * The callback function for all the modeless dialogs that make up the * "tearoff menus" Very simple - forward button presses (to fool Vim into * thinking its menus have been clicked), and go away when closed. */ static LRESULT CALLBACK tearoff_callback( HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { if (message == WM_INITDIALOG) return (TRUE); /* May show the mouse pointer again. */ HandleMouseHide(message, lParam); if (message == WM_COMMAND) { if ((WORD)(LOWORD(wParam)) & 0x8000) { POINT mp; RECT rect; if (GetCursorPos(&mp) && GetWindowRect(hwnd, &rect)) { (void)TrackPopupMenu( (HMENU)(long_u)(LOWORD(wParam) ^ 0x8000), TPM_LEFTALIGN | TPM_LEFTBUTTON, (int)rect.right - 8, (int)mp.y, (int)0, /*reserved param*/ s_hwnd, NULL); /* * NOTE: The pop-up menu can eat the mouse up event. * We deal with this in normal.c. */ } } else /* Pass on messages to the main Vim window */ PostMessage(s_hwnd, WM_COMMAND, LOWORD(wParam), 0); /* * Give main window the focus back: this is so after * choosing a tearoff button you can start typing again * straight away. */ (void)SetFocus(s_hwnd); return TRUE; } if ((message == WM_SYSCOMMAND) && (wParam == SC_CLOSE)) { DestroyWindow(hwnd); return TRUE; } /* When moved around, give main window the focus back. */ if (message == WM_EXITSIZEMOVE) (void)SetActiveWindow(s_hwnd); return FALSE; } #endif /* * Decide whether to use the "new look" (small, non-bold font) or the "old * look" (big, clanky font) for dialogs, and work out a few values for use * later accordingly. */ static void get_dialog_font_metrics(void) { HDC hdc; HFONT hfontTools = 0; DWORD dlgFontSize; SIZE size; #ifdef USE_SYSMENU_FONT LOGFONT lfSysmenu; #endif s_usenewlook = FALSE; /* * For NT3.51 and Win32s, we stick with the old look * because it matches everything else. */ if (!is_winnt_3()) { #ifdef USE_SYSMENU_FONT if (gui_w32_get_menu_font(&lfSysmenu) == OK) hfontTools = CreateFontIndirect(&lfSysmenu); else #endif hfontTools = CreateFont(-DLG_FONT_POINT_SIZE, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, VARIABLE_PITCH , DLG_FONT_NAME); if (hfontTools) { hdc = GetDC(s_hwnd); SelectObject(hdc, hfontTools); /* * GetTextMetrics() doesn't return the right value in * tmAveCharWidth, so we have to figure out the dialog base units * ourselves. */ GetTextExtentPoint(hdc, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 52, &size); ReleaseDC(s_hwnd, hdc); s_dlgfntwidth = (WORD)((size.cx / 26 + 1) / 2); s_dlgfntheight = (WORD)size.cy; s_usenewlook = TRUE; } } if (!s_usenewlook) { dlgFontSize = GetDialogBaseUnits(); /* fall back to big old system*/ s_dlgfntwidth = LOWORD(dlgFontSize); s_dlgfntheight = HIWORD(dlgFontSize); } } #if defined(FEAT_MENU) && defined(FEAT_TEAROFF) /* * Create a pseudo-"tearoff menu" based on the child * items of a given menu pointer. */ static void gui_mch_tearoff( char_u *title, vimmenu_T *menu, int initX, int initY) { WORD *p, *pdlgtemplate, *pnumitems, *ptrueheight; int template_len; int nchar, textWidth, submenuWidth; DWORD lStyle; DWORD lExtendedStyle; WORD dlgwidth; WORD menuID; vimmenu_T *pmenu; vimmenu_T *the_menu = menu; HWND hwnd; HDC hdc; HFONT font, oldFont; int col, spaceWidth, len; int columnWidths[2]; char_u *label, *text; int acLen = 0; int nameLen; int padding0, padding1, padding2 = 0; int sepPadding=0; int x; int y; #ifdef USE_SYSMENU_FONT LOGFONT lfSysmenu; int use_lfSysmenu = FALSE; #endif /* * If this menu is already torn off, move it to the mouse position. */ if (IsWindow(menu->tearoff_handle)) { POINT mp; if (GetCursorPos((LPPOINT)&mp)) { SetWindowPos(menu->tearoff_handle, NULL, mp.x, mp.y, 0, 0, SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER); } return; } /* * Create a new tearoff. */ if (*title == MNU_HIDDEN_CHAR) title++; /* Allocate memory to store the dialog template. It's made bigger when * needed. */ template_len = DLG_ALLOC_SIZE; pdlgtemplate = p = (WORD *)LocalAlloc(LPTR, template_len); if (p == NULL) return; hwnd = GetDesktopWindow(); hdc = GetWindowDC(hwnd); #ifdef USE_SYSMENU_FONT if (gui_w32_get_menu_font(&lfSysmenu) == OK) { font = CreateFontIndirect(&lfSysmenu); use_lfSysmenu = TRUE; } else #endif font = CreateFont(-DLG_FONT_POINT_SIZE, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, VARIABLE_PITCH , DLG_FONT_NAME); if (s_usenewlook) oldFont = SelectFont(hdc, font); else oldFont = SelectFont(hdc, GetStockObject(SYSTEM_FONT)); /* Calculate width of a single space. Used for padding columns to the * right width. */ spaceWidth = GetTextWidth(hdc, " ", 1); /* Figure out max width of the text column, the accelerator column and the * optional submenu column. */ submenuWidth = 0; for (col = 0; col < 2; col++) { columnWidths[col] = 0; for (pmenu = menu->children; pmenu != NULL; pmenu = pmenu->next) { /* Use "dname" here to compute the width of the visible text. */ text = (col == 0) ? pmenu->dname : pmenu->actext; if (text != NULL && *text != NUL) { textWidth = GetTextWidthEnc(hdc, text, (int)STRLEN(text)); if (textWidth > columnWidths[col]) columnWidths[col] = textWidth; } if (pmenu->children != NULL) submenuWidth = TEAROFF_COLUMN_PADDING * spaceWidth; } } if (columnWidths[1] == 0) { /* no accelerators */ if (submenuWidth != 0) columnWidths[0] += submenuWidth; else columnWidths[0] += spaceWidth; } else { /* there is an accelerator column */ columnWidths[0] += TEAROFF_COLUMN_PADDING * spaceWidth; columnWidths[1] += submenuWidth; } /* * Now find the total width of our 'menu'. */ textWidth = columnWidths[0] + columnWidths[1]; if (submenuWidth != 0) { submenuWidth = GetTextWidth(hdc, TEAROFF_SUBMENU_LABEL, (int)STRLEN(TEAROFF_SUBMENU_LABEL)); textWidth += submenuWidth; } dlgwidth = GetTextWidthEnc(hdc, title, (int)STRLEN(title)); if (textWidth > dlgwidth) dlgwidth = textWidth; dlgwidth += 2 * TEAROFF_PADDING_X + TEAROFF_BUTTON_PAD_X; /* W95 can't do thin dialogs, they look v. weird! */ if (mch_windows95() && dlgwidth < TEAROFF_MIN_WIDTH) dlgwidth = TEAROFF_MIN_WIDTH; /* start to fill in the dlgtemplate information. addressing by WORDs */ if (s_usenewlook) lStyle = DS_MODALFRAME | WS_CAPTION| WS_SYSMENU |DS_SETFONT| WS_VISIBLE; else lStyle = DS_MODALFRAME | WS_CAPTION| WS_SYSMENU | WS_VISIBLE; lExtendedStyle = WS_EX_TOOLWINDOW|WS_EX_STATICEDGE; *p++ = LOWORD(lStyle); *p++ = HIWORD(lStyle); *p++ = LOWORD(lExtendedStyle); *p++ = HIWORD(lExtendedStyle); pnumitems = p; /* save where the number of items must be stored */ *p++ = 0; // NumberOfItems(will change later) gui_mch_getmouse(&x, &y); if (initX == 0xffffL) *p++ = PixelToDialogX(x); // x else *p++ = PixelToDialogX(initX); // x if (initY == 0xffffL) *p++ = PixelToDialogY(y); // y else *p++ = PixelToDialogY(initY); // y *p++ = PixelToDialogX(dlgwidth); // cx ptrueheight = p; *p++ = 0; // dialog height: changed later anyway *p++ = 0; // Menu *p++ = 0; // Class /* copy the title of the dialog */ nchar = nCopyAnsiToWideChar(p, ((*title) ? (LPSTR)title : (LPSTR)("Vim "VIM_VERSION_MEDIUM))); p += nchar; if (s_usenewlook) { /* do the font, since DS_3DLOOK doesn't work properly */ #ifdef USE_SYSMENU_FONT if (use_lfSysmenu) { /* point size */ *p++ = -MulDiv(lfSysmenu.lfHeight, 72, GetDeviceCaps(hdc, LOGPIXELSY)); nchar = nCopyAnsiToWideChar(p, TEXT(lfSysmenu.lfFaceName)); } else #endif { *p++ = DLG_FONT_POINT_SIZE; // point size nchar = nCopyAnsiToWideChar (p, TEXT(DLG_FONT_NAME)); } p += nchar; } /* * Loop over all the items in the menu. * But skip over the tearbar. */ if (STRCMP(menu->children->name, TEAR_STRING) == 0) menu = menu->children->next; else menu = menu->children; for ( ; menu != NULL; menu = menu->next) { if (menu->modes == 0) /* this menu has just been deleted */ continue; if (menu_is_separator(menu->dname)) { sepPadding += 3; continue; } /* Check if there still is plenty of room in the template. Make it * larger when needed. */ if (((char *)p - (char *)pdlgtemplate) + 1000 > template_len) { WORD *newp; newp = (WORD *)LocalAlloc(LPTR, template_len + 4096); if (newp != NULL) { template_len += 4096; mch_memmove(newp, pdlgtemplate, (char *)p - (char *)pdlgtemplate); p = newp + (p - pdlgtemplate); pnumitems = newp + (pnumitems - pdlgtemplate); ptrueheight = newp + (ptrueheight - pdlgtemplate); LocalFree(LocalHandle(pdlgtemplate)); pdlgtemplate = newp; } } /* Figure out minimal length of this menu label. Use "name" for the * actual text, "dname" for estimating the displayed size. "name" * has "&a" for mnemonic and includes the accelerator. */ len = nameLen = (int)STRLEN(menu->name); padding0 = (columnWidths[0] - GetTextWidthEnc(hdc, menu->dname, (int)STRLEN(menu->dname))) / spaceWidth; len += padding0; if (menu->actext != NULL) { acLen = (int)STRLEN(menu->actext); len += acLen; textWidth = GetTextWidthEnc(hdc, menu->actext, acLen); } else textWidth = 0; padding1 = (columnWidths[1] - textWidth) / spaceWidth; len += padding1; if (menu->children == NULL) { padding2 = submenuWidth / spaceWidth; len += padding2; menuID = (WORD)(menu->id); } else { len += (int)STRLEN(TEAROFF_SUBMENU_LABEL); menuID = (WORD)((long_u)(menu->submenu_id) | (DWORD)0x8000); } /* Allocate menu label and fill it in */ text = label = alloc((unsigned)len + 1); if (label == NULL) break; vim_strncpy(text, menu->name, nameLen); text = vim_strchr(text, TAB); /* stop at TAB before actext */ if (text == NULL) text = label + nameLen; /* no actext, use whole name */ while (padding0-- > 0) *text++ = ' '; if (menu->actext != NULL) { STRNCPY(text, menu->actext, acLen); text += acLen; } while (padding1-- > 0) *text++ = ' '; if (menu->children != NULL) { STRCPY(text, TEAROFF_SUBMENU_LABEL); text += STRLEN(TEAROFF_SUBMENU_LABEL); } else { while (padding2-- > 0) *text++ = ' '; } *text = NUL; /* * BS_LEFT will just be ignored on Win32s/NT3.5x - on * W95/NT4 it makes the tear-off look more like a menu. */ p = add_dialog_element(p, BS_PUSHBUTTON|BS_LEFT, (WORD)PixelToDialogX(TEAROFF_PADDING_X), (WORD)(sepPadding + 1 + 13 * (*pnumitems)), (WORD)PixelToDialogX(dlgwidth - 2 * TEAROFF_PADDING_X), (WORD)12, menuID, (WORD)0x0080, label); vim_free(label); (*pnumitems)++; } *ptrueheight = (WORD)(sepPadding + 1 + 13 * (*pnumitems)); /* show modelessly */ the_menu->tearoff_handle = CreateDialogIndirect( s_hinst, (LPDLGTEMPLATE)pdlgtemplate, s_hwnd, (DLGPROC)tearoff_callback); LocalFree(LocalHandle(pdlgtemplate)); SelectFont(hdc, oldFont); DeleteObject(font); ReleaseDC(hwnd, hdc); /* * Reassert ourselves as the active window. This is so that after creating * a tearoff, the user doesn't have to click with the mouse just to start * typing again! */ (void)SetActiveWindow(s_hwnd); /* make sure the right buttons are enabled */ force_menu_update = TRUE; } #endif #if defined(FEAT_TOOLBAR) || defined(PROTO) #include "gui_w32_rc.h" /* This not defined in older SDKs */ # ifndef TBSTYLE_FLAT # define TBSTYLE_FLAT 0x0800 # endif /* * Create the toolbar, initially unpopulated. * (just like the menu, there are no defaults, it's all * set up through menu.vim) */ static void initialise_toolbar(void) { InitCommonControls(); s_toolbarhwnd = CreateToolbarEx( s_hwnd, WS_CHILD | TBSTYLE_TOOLTIPS | TBSTYLE_FLAT, 4000, //any old big number 31, //number of images in initial bitmap s_hinst, IDR_TOOLBAR1, // id of initial bitmap NULL, 0, // initial number of buttons TOOLBAR_BUTTON_WIDTH, //api guide is wrong! TOOLBAR_BUTTON_HEIGHT, TOOLBAR_BUTTON_WIDTH, TOOLBAR_BUTTON_HEIGHT, sizeof(TBBUTTON) ); gui_mch_show_toolbar(vim_strchr(p_go, GO_TOOLBAR) != NULL); } static int get_toolbar_bitmap(vimmenu_T *menu) { int i = -1; /* * Check user bitmaps first, unless builtin is specified. */ if (!is_winnt_3() && !menu->icon_builtin) { char_u fname[MAXPATHL]; HANDLE hbitmap = NULL; if (menu->iconfile != NULL) { gui_find_iconfile(menu->iconfile, fname, "bmp"); hbitmap = LoadImage( NULL, fname, IMAGE_BITMAP, TOOLBAR_BUTTON_WIDTH, TOOLBAR_BUTTON_HEIGHT, LR_LOADFROMFILE | LR_LOADMAP3DCOLORS ); } /* * If the LoadImage call failed, or the "icon=" file * didn't exist or wasn't specified, try the menu name */ if (hbitmap == NULL && (gui_find_bitmap(menu->name, fname, "bmp") == OK)) hbitmap = LoadImage( NULL, fname, IMAGE_BITMAP, TOOLBAR_BUTTON_WIDTH, TOOLBAR_BUTTON_HEIGHT, LR_LOADFROMFILE | LR_LOADMAP3DCOLORS ); if (hbitmap != NULL) { TBADDBITMAP tbAddBitmap; tbAddBitmap.hInst = NULL; tbAddBitmap.nID = (long_u)hbitmap; i = (int)SendMessage(s_toolbarhwnd, TB_ADDBITMAP, (WPARAM)1, (LPARAM)&tbAddBitmap); /* i will be set to -1 if it fails */ } } if (i == -1 && menu->iconidx >= 0 && menu->iconidx < TOOLBAR_BITMAP_COUNT) i = menu->iconidx; return i; } #endif #if defined(FEAT_GUI_TABLINE) || defined(PROTO) static void initialise_tabline(void) { InitCommonControls(); s_tabhwnd = CreateWindow(WC_TABCONTROL, "Vim tabline", WS_CHILD|TCS_FOCUSNEVER|TCS_TOOLTIPS, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, s_hwnd, NULL, s_hinst, NULL); gui.tabline_height = TABLINE_HEIGHT; # ifdef USE_SYSMENU_FONT set_tabline_font(); # endif } #endif #if defined(FEAT_OLE) || defined(FEAT_EVAL) || defined(PROTO) /* * Make the GUI window come to the foreground. */ void gui_mch_set_foreground(void) { if (IsIconic(s_hwnd)) SendMessage(s_hwnd, WM_SYSCOMMAND, SC_RESTORE, 0); SetForegroundWindow(s_hwnd); } #endif #if defined(FEAT_MBYTE_IME) && defined(DYNAMIC_IME) static void dyn_imm_load(void) { hLibImm = vimLoadLib("imm32.dll"); if (hLibImm == NULL) return; pImmGetCompositionStringA = (void *)GetProcAddress(hLibImm, "ImmGetCompositionStringA"); pImmGetCompositionStringW = (void *)GetProcAddress(hLibImm, "ImmGetCompositionStringW"); pImmGetContext = (void *)GetProcAddress(hLibImm, "ImmGetContext"); pImmAssociateContext = (void *)GetProcAddress(hLibImm, "ImmAssociateContext"); pImmReleaseContext = (void *)GetProcAddress(hLibImm, "ImmReleaseContext"); pImmGetOpenStatus = (void *)GetProcAddress(hLibImm, "ImmGetOpenStatus"); pImmSetOpenStatus = (void *)GetProcAddress(hLibImm, "ImmSetOpenStatus"); pImmGetCompositionFont = (void *)GetProcAddress(hLibImm, "ImmGetCompositionFontA"); pImmSetCompositionFont = (void *)GetProcAddress(hLibImm, "ImmSetCompositionFontA"); pImmSetCompositionWindow = (void *)GetProcAddress(hLibImm, "ImmSetCompositionWindow"); pImmGetConversionStatus = (void *)GetProcAddress(hLibImm, "ImmGetConversionStatus"); pImmSetConversionStatus = (void *)GetProcAddress(hLibImm, "ImmSetConversionStatus"); if ( pImmGetCompositionStringA == NULL || pImmGetCompositionStringW == NULL || pImmGetContext == NULL || pImmAssociateContext == NULL || pImmReleaseContext == NULL || pImmGetOpenStatus == NULL || pImmSetOpenStatus == NULL || pImmGetCompositionFont == NULL || pImmSetCompositionFont == NULL || pImmSetCompositionWindow == NULL || pImmGetConversionStatus == NULL || pImmSetConversionStatus == NULL) { FreeLibrary(hLibImm); hLibImm = NULL; pImmGetContext = NULL; return; } return; } #endif #if defined(FEAT_SIGN_ICONS) || defined(PROTO) # ifdef FEAT_XPM_W32 # define IMAGE_XPM 100 # endif typedef struct _signicon_t { HANDLE hImage; UINT uType; #ifdef FEAT_XPM_W32 HANDLE hShape; /* Mask bitmap handle */ #endif } signicon_t; void gui_mch_drawsign(row, col, typenr) int row; int col; int typenr; { signicon_t *sign; int x, y, w, h; if (!gui.in_use || (sign = (signicon_t *)sign_get_image(typenr)) == NULL) return; x = TEXT_X(col); y = TEXT_Y(row); w = gui.char_width * 2; h = gui.char_height; switch (sign->uType) { case IMAGE_BITMAP: { HDC hdcMem; HBITMAP hbmpOld; hdcMem = CreateCompatibleDC(s_hdc); hbmpOld = (HBITMAP)SelectObject(hdcMem, sign->hImage); BitBlt(s_hdc, x, y, w, h, hdcMem, 0, 0, SRCCOPY); SelectObject(hdcMem, hbmpOld); DeleteDC(hdcMem); } break; case IMAGE_ICON: case IMAGE_CURSOR: DrawIconEx(s_hdc, x, y, (HICON)sign->hImage, w, h, 0, NULL, DI_NORMAL); break; #ifdef FEAT_XPM_W32 case IMAGE_XPM: { HDC hdcMem; HBITMAP hbmpOld; hdcMem = CreateCompatibleDC(s_hdc); hbmpOld = (HBITMAP)SelectObject(hdcMem, sign->hShape); /* Make hole */ BitBlt(s_hdc, x, y, w, h, hdcMem, 0, 0, SRCAND); SelectObject(hdcMem, sign->hImage); /* Paint sign */ BitBlt(s_hdc, x, y, w, h, hdcMem, 0, 0, SRCPAINT); SelectObject(hdcMem, hbmpOld); DeleteDC(hdcMem); } break; #endif } } static void close_signicon_image(signicon_t *sign) { if (sign) switch (sign->uType) { case IMAGE_BITMAP: DeleteObject((HGDIOBJ)sign->hImage); break; case IMAGE_CURSOR: DestroyCursor((HCURSOR)sign->hImage); break; case IMAGE_ICON: DestroyIcon((HICON)sign->hImage); break; #ifdef FEAT_XPM_W32 case IMAGE_XPM: DeleteObject((HBITMAP)sign->hImage); DeleteObject((HBITMAP)sign->hShape); break; #endif } } void * gui_mch_register_sign(signfile) char_u *signfile; { signicon_t sign, *psign; char_u *ext; if (is_winnt_3()) { EMSG(_(e_signdata)); return NULL; } sign.hImage = NULL; ext = signfile + STRLEN(signfile) - 4; /* get extention */ if (ext > signfile) { int do_load = 1; if (!STRICMP(ext, ".bmp")) sign.uType = IMAGE_BITMAP; else if (!STRICMP(ext, ".ico")) sign.uType = IMAGE_ICON; else if (!STRICMP(ext, ".cur") || !STRICMP(ext, ".ani")) sign.uType = IMAGE_CURSOR; else do_load = 0; if (do_load) sign.hImage = (HANDLE)LoadImage(NULL, signfile, sign.uType, gui.char_width * 2, gui.char_height, LR_LOADFROMFILE | LR_CREATEDIBSECTION); #ifdef FEAT_XPM_W32 if (!STRICMP(ext, ".xpm")) { sign.uType = IMAGE_XPM; LoadXpmImage(signfile, (HBITMAP *)&sign.hImage, (HBITMAP *)&sign.hShape); } #endif } psign = NULL; if (sign.hImage && (psign = (signicon_t *)alloc(sizeof(signicon_t))) != NULL) *psign = sign; if (!psign) { if (sign.hImage) close_signicon_image(&sign); EMSG(_(e_signdata)); } return (void *)psign; } void gui_mch_destroy_sign(sign) void *sign; { if (sign) { close_signicon_image((signicon_t *)sign); vim_free(sign); } } #endif #if defined(FEAT_BEVAL) || defined(PROTO) /* BALLOON-EVAL IMPLEMENTATION FOR WINDOWS. * Added by Sergey Khorev <sergey.khorev@gmail.com> * * The only reused thing is gui_beval.h and get_beval_info() * from gui_beval.c (note it uses x and y of the BalloonEval struct * to get current mouse position). * * Trying to use as more Windows services as possible, and as less * IE version as possible :)). * * 1) Don't create ToolTip in gui_mch_create_beval_area, only initialize * BalloonEval struct. * 2) Enable/Disable simply create/kill BalloonEval Timer * 3) When there was enough inactivity, timer procedure posts * async request to debugger * 4) gui_mch_post_balloon (invoked from netbeans.c) creates tooltip control * and performs some actions to show it ASAP * 5) WM_NOTIFY:TTN_POP destroys created tooltip */ /* * determine whether installed Common Controls support multiline tooltips * (i.e. their version is >= 4.70 */ int multiline_balloon_available(void) { HINSTANCE hDll; static char comctl_dll[] = "comctl32.dll"; static int multiline_tip = MAYBE; if (multiline_tip != MAYBE) return multiline_tip; hDll = GetModuleHandle(comctl_dll); if (hDll != NULL) { DLLGETVERSIONPROC pGetVer; pGetVer = (DLLGETVERSIONPROC)GetProcAddress(hDll, "DllGetVersion"); if (pGetVer != NULL) { DLLVERSIONINFO dvi; HRESULT hr; ZeroMemory(&dvi, sizeof(dvi)); dvi.cbSize = sizeof(dvi); hr = (*pGetVer)(&dvi); if (SUCCEEDED(hr) && (dvi.dwMajorVersion > 4 || (dvi.dwMajorVersion == 4 && dvi.dwMinorVersion >= 70))) { multiline_tip = TRUE; return multiline_tip; } } else { /* there is chance we have ancient CommCtl 4.70 which doesn't export DllGetVersion */ DWORD dwHandle = 0; DWORD len = GetFileVersionInfoSize(comctl_dll, &dwHandle); if (len > 0) { VS_FIXEDFILEINFO *ver; UINT vlen = 0; void *data = alloc(len); if (data != NULL && GetFileVersionInfo(comctl_dll, 0, len, data) && VerQueryValue(data, "\\", (void **)&ver, &vlen) && vlen && HIWORD(ver->dwFileVersionMS) > 4 || (HIWORD(ver->dwFileVersionMS) == 4 && LOWORD(ver->dwFileVersionMS) >= 70)) { vim_free(data); multiline_tip = TRUE; return multiline_tip; } vim_free(data); } } } multiline_tip = FALSE; return multiline_tip; } static void make_tooltip(beval, text, pt) BalloonEval *beval; char *text; POINT pt; { TOOLINFO *pti; int ToolInfoSize; if (multiline_balloon_available() == TRUE) ToolInfoSize = sizeof(TOOLINFO_NEW); else ToolInfoSize = sizeof(TOOLINFO); pti = (TOOLINFO *)alloc(ToolInfoSize); if (pti == NULL) return; beval->balloon = CreateWindowEx(WS_EX_TOPMOST, TOOLTIPS_CLASS, NULL, WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, beval->target, NULL, s_hinst, NULL); SetWindowPos(beval->balloon, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); pti->cbSize = ToolInfoSize; pti->uFlags = TTF_SUBCLASS; pti->hwnd = beval->target; pti->hinst = 0; /* Don't use string resources */ pti->uId = ID_BEVAL_TOOLTIP; if (multiline_balloon_available() == TRUE) { RECT rect; TOOLINFO_NEW *ptin = (TOOLINFO_NEW *)pti; pti->lpszText = LPSTR_TEXTCALLBACK; ptin->lParam = (LPARAM)text; if (GetClientRect(s_textArea, &rect)) /* switch multiline tooltips on */ SendMessage(beval->balloon, TTM_SETMAXTIPWIDTH, 0, (LPARAM)rect.right); } else pti->lpszText = text; /* do this old way */ /* Limit ballooneval bounding rect to CursorPos neighbourhood */ pti->rect.left = pt.x - 3; pti->rect.top = pt.y - 3; pti->rect.right = pt.x + 3; pti->rect.bottom = pt.y + 3; SendMessage(beval->balloon, TTM_ADDTOOL, 0, (LPARAM)pti); /* Make tooltip appear sooner */ SendMessage(beval->balloon, TTM_SETDELAYTIME, TTDT_INITIAL, 10); /* I've performed some tests and it seems the longest possible life time * of tooltip is 30 seconds */ SendMessage(beval->balloon, TTM_SETDELAYTIME, TTDT_AUTOPOP, 30000); /* * HACK: force tooltip to appear, because it'll not appear until * first mouse move. D*mn M$ * Amazingly moving (2, 2) and then (-1, -1) the mouse doesn't move. */ mouse_event(MOUSEEVENTF_MOVE, 2, 2, 0, 0); mouse_event(MOUSEEVENTF_MOVE, (DWORD)-1, (DWORD)-1, 0, 0); vim_free(pti); } static void delete_tooltip(beval) BalloonEval *beval; { DestroyWindow(beval->balloon); } /*ARGSUSED*/ static VOID CALLBACK BevalTimerProc(hwnd, uMsg, idEvent, dwTime) HWND hwnd; UINT uMsg; UINT_PTR idEvent; DWORD dwTime; { POINT pt; RECT rect; if (cur_beval == NULL || cur_beval->showState == ShS_SHOWING || !p_beval) return; GetCursorPos(&pt); if (WindowFromPoint(pt) != s_textArea) return; ScreenToClient(s_textArea, &pt); GetClientRect(s_textArea, &rect); if (!PtInRect(&rect, pt)) return; if (LastActivity > 0 && (dwTime - LastActivity) >= (DWORD)p_bdlay && (cur_beval->showState != ShS_PENDING || abs(cur_beval->x - pt.x) > 3 || abs(cur_beval->y - pt.y) > 3)) { /* Pointer resting in one place long enough, it's time to show * the tooltip. */ cur_beval->showState = ShS_PENDING; cur_beval->x = pt.x; cur_beval->y = pt.y; // TRACE0("BevalTimerProc: sending request"); if (cur_beval->msgCB != NULL) (*cur_beval->msgCB)(cur_beval, 0); } } /*ARGSUSED*/ void gui_mch_disable_beval_area(beval) BalloonEval *beval; { // TRACE0("gui_mch_disable_beval_area {{{"); KillTimer(s_textArea, BevalTimerId); // TRACE0("gui_mch_disable_beval_area }}}"); } /*ARGSUSED*/ void gui_mch_enable_beval_area(beval) BalloonEval *beval; { // TRACE0("gui_mch_enable_beval_area |||"); if (beval == NULL) return; // TRACE0("gui_mch_enable_beval_area {{{"); BevalTimerId = SetTimer(s_textArea, 0, (UINT)(p_bdlay / 2), BevalTimerProc); // TRACE0("gui_mch_enable_beval_area }}}"); } void gui_mch_post_balloon(beval, mesg) BalloonEval *beval; char_u *mesg; { POINT pt; // TRACE0("gui_mch_post_balloon {{{"); if (beval->showState == ShS_SHOWING) return; GetCursorPos(&pt); ScreenToClient(s_textArea, &pt); if (abs(beval->x - pt.x) < 3 && abs(beval->y - pt.y) < 3) /* cursor is still here */ { gui_mch_disable_beval_area(cur_beval); beval->showState = ShS_SHOWING; make_tooltip(beval, mesg, pt); } // TRACE0("gui_mch_post_balloon }}}"); } /*ARGSUSED*/ BalloonEval * gui_mch_create_beval_area(target, mesg, mesgCB, clientData) void *target; /* ignored, always use s_textArea */ char_u *mesg; void (*mesgCB)__ARGS((BalloonEval *, int)); void *clientData; { /* partially stolen from gui_beval.c */ BalloonEval *beval; if (mesg != NULL && mesgCB != NULL) { EMSG(_("E232: Cannot create BalloonEval with both message and callback")); return NULL; } beval = (BalloonEval *)alloc(sizeof(BalloonEval)); if (beval != NULL) { beval->target = s_textArea; beval->balloon = NULL; beval->showState = ShS_NEUTRAL; beval->x = 0; beval->y = 0; beval->msg = mesg; beval->msgCB = mesgCB; beval->clientData = clientData; InitCommonControls(); cur_beval = beval; if (p_beval) gui_mch_enable_beval_area(beval); } return beval; } /*ARGSUSED*/ static void Handle_WM_Notify(HWND hwnd, LPNMHDR pnmh) { if (pnmh->idFrom != ID_BEVAL_TOOLTIP) /* it is not our tooltip */ return; if (cur_beval != NULL) { switch (pnmh->code) { case TTN_SHOW: // TRACE0("TTN_SHOW {{{"); // TRACE0("TTN_SHOW }}}"); break; case TTN_POP: /* Before tooltip disappear */ // TRACE0("TTN_POP {{{"); delete_tooltip(cur_beval); gui_mch_enable_beval_area(cur_beval); // TRACE0("TTN_POP }}}"); cur_beval->showState = ShS_NEUTRAL; break; case TTN_GETDISPINFO: { /* if you get there then we have new common controls */ NMTTDISPINFO_NEW *info = (NMTTDISPINFO_NEW *)pnmh; info->lpszText = (LPSTR)info->lParam; info->uFlags |= TTF_DI_SETITEM; } break; } } } static void TrackUserActivity(UINT uMsg) { if ((uMsg >= WM_MOUSEFIRST && uMsg <= WM_MOUSELAST) || (uMsg >= WM_KEYFIRST && uMsg <= WM_KEYLAST)) LastActivity = GetTickCount(); } void gui_mch_destroy_beval_area(beval) BalloonEval *beval; { vim_free(beval); } #endif /* FEAT_BEVAL */ #if defined(FEAT_NETBEANS_INTG) || defined(PROTO) /* * We have multiple signs to draw at the same location. Draw the * multi-sign indicator (down-arrow) instead. This is the Win32 version. */ void netbeans_draw_multisign_indicator(int row) { int i; int y; int x; if (!netbeans_active()) return; x = 0; y = TEXT_Y(row); for (i = 0; i < gui.char_height - 3; i++) SetPixel(s_hdc, x+2, y++, gui.currFgColor); SetPixel(s_hdc, x+0, y, gui.currFgColor); SetPixel(s_hdc, x+2, y, gui.currFgColor); SetPixel(s_hdc, x+4, y++, gui.currFgColor); SetPixel(s_hdc, x+1, y, gui.currFgColor); SetPixel(s_hdc, x+2, y, gui.currFgColor); SetPixel(s_hdc, x+3, y++, gui.currFgColor); SetPixel(s_hdc, x+2, y, gui.currFgColor); } /* * Initialize the Winsock dll. */ void netbeans_init_winsock() { WSADATA wsaData; int wsaerr; if (WSInitialized) return; wsaerr = WSAStartup(MAKEWORD(2, 2), &wsaData); if (wsaerr == 0) WSInitialized = TRUE; } #endif
zyz2011-vim
src/gui_w32.c
C
gpl2
122,972
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * GUI/Motif support by Robert Webb * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * Code for menus. Used for the GUI and 'wildmenu'. */ #include "vim.h" #if defined(FEAT_MENU) || defined(PROTO) #define MENUDEPTH 10 /* maximum depth of menus */ #ifdef FEAT_GUI_W32 static int add_menu_path __ARGS((char_u *, vimmenu_T *, int *, char_u *, int)); #else static int add_menu_path __ARGS((char_u *, vimmenu_T *, int *, char_u *)); #endif static int menu_nable_recurse __ARGS((vimmenu_T *menu, char_u *name, int modes, int enable)); static int remove_menu __ARGS((vimmenu_T **, char_u *, int, int silent)); static void free_menu __ARGS((vimmenu_T **menup)); static void free_menu_string __ARGS((vimmenu_T *, int)); static int show_menus __ARGS((char_u *, int)); static void show_menus_recursive __ARGS((vimmenu_T *, int, int)); static int menu_name_equal __ARGS((char_u *name, vimmenu_T *menu)); static int menu_namecmp __ARGS((char_u *name, char_u *mname)); static int get_menu_cmd_modes __ARGS((char_u *, int, int *, int *)); static char_u *popup_mode_name __ARGS((char_u *name, int idx)); static char_u *menu_text __ARGS((char_u *text, int *mnemonic, char_u **actext)); #ifdef FEAT_GUI static int get_menu_mode __ARGS((void)); static void gui_update_menus_recurse __ARGS((vimmenu_T *, int)); #endif #if defined(FEAT_GUI_W32) && defined(FEAT_TEAROFF) static void gui_create_tearoffs_recurse __ARGS((vimmenu_T *menu, const char_u *pname, int *pri_tab, int pri_idx)); static void gui_add_tearoff __ARGS((char_u *tearpath, int *pri_tab, int pri_idx)); static void gui_destroy_tearoffs_recurse __ARGS((vimmenu_T *menu)); static int s_tearoffs = FALSE; #endif static int menu_is_hidden __ARGS((char_u *name)); #if defined(FEAT_CMDL_COMPL) || (defined(FEAT_GUI_W32) && defined(FEAT_TEAROFF)) static int menu_is_tearoff __ARGS((char_u *name)); #endif #if defined(FEAT_MULTI_LANG) || defined(FEAT_TOOLBAR) static char_u *menu_skip_part __ARGS((char_u *p)); #endif #ifdef FEAT_MULTI_LANG static char_u *menutrans_lookup __ARGS((char_u *name, int len)); static void menu_unescape_name __ARGS((char_u *p)); #endif static char_u *menu_translate_tab_and_shift __ARGS((char_u *arg_start)); /* The character for each menu mode */ static char_u menu_mode_chars[] = {'n', 'v', 's', 'o', 'i', 'c', 't'}; static char_u e_notsubmenu[] = N_("E327: Part of menu-item path is not sub-menu"); static char_u e_othermode[] = N_("E328: Menu only exists in another mode"); static char_u e_nomenu[] = N_("E329: No menu \"%s\""); #ifdef FEAT_TOOLBAR static const char *toolbar_names[] = { /* 0 */ "New", "Open", "Save", "Undo", "Redo", /* 5 */ "Cut", "Copy", "Paste", "Print", "Help", /* 10 */ "Find", "SaveAll", "SaveSesn", "NewSesn", "LoadSesn", /* 15 */ "RunScript", "Replace", "WinClose", "WinMax", "WinMin", /* 20 */ "WinSplit", "Shell", "FindPrev", "FindNext", "FindHelp", /* 25 */ "Make", "TagJump", "RunCtags", "WinVSplit", "WinMaxWidth", /* 30 */ "WinMinWidth", "Exit" }; # define TOOLBAR_NAME_COUNT (sizeof(toolbar_names) / sizeof(char *)) #endif /* * Do the :menu command and relatives. */ void ex_menu(eap) exarg_T *eap; /* Ex command arguments */ { char_u *menu_path; int modes; char_u *map_to; int noremap; int silent = FALSE; int special = FALSE; int unmenu; char_u *map_buf; char_u *arg; char_u *p; int i; #if defined(FEAT_GUI) && !defined(FEAT_GUI_GTK) int old_menu_height; # if defined(FEAT_TOOLBAR) && !defined(FEAT_GUI_W32) && !defined(FEAT_GUI_W16) int old_toolbar_height; # endif #endif int pri_tab[MENUDEPTH + 1]; int enable = MAYBE; /* TRUE for "menu enable", FALSE for "menu * disable */ #ifdef FEAT_TOOLBAR char_u *icon = NULL; #endif vimmenu_T menuarg; modes = get_menu_cmd_modes(eap->cmd, eap->forceit, &noremap, &unmenu); arg = eap->arg; for (;;) { if (STRNCMP(arg, "<script>", 8) == 0) { noremap = REMAP_SCRIPT; arg = skipwhite(arg + 8); continue; } if (STRNCMP(arg, "<silent>", 8) == 0) { silent = TRUE; arg = skipwhite(arg + 8); continue; } if (STRNCMP(arg, "<special>", 9) == 0) { special = TRUE; arg = skipwhite(arg + 9); continue; } break; } /* Locate an optional "icon=filename" argument. */ if (STRNCMP(arg, "icon=", 5) == 0) { arg += 5; #ifdef FEAT_TOOLBAR icon = arg; #endif while (*arg != NUL && *arg != ' ') { if (*arg == '\\') STRMOVE(arg, arg + 1); mb_ptr_adv(arg); } if (*arg != NUL) { *arg++ = NUL; arg = skipwhite(arg); } } /* * Fill in the priority table. */ for (p = arg; *p; ++p) if (!VIM_ISDIGIT(*p) && *p != '.') break; if (vim_iswhite(*p)) { for (i = 0; i < MENUDEPTH && !vim_iswhite(*arg); ++i) { pri_tab[i] = getdigits(&arg); if (pri_tab[i] == 0) pri_tab[i] = 500; if (*arg == '.') ++arg; } arg = skipwhite(arg); } else if (eap->addr_count && eap->line2 != 0) { pri_tab[0] = eap->line2; i = 1; } else i = 0; while (i < MENUDEPTH) pri_tab[i++] = 500; pri_tab[MENUDEPTH] = -1; /* mark end of the table */ /* * Check for "disable" or "enable" argument. */ if (STRNCMP(arg, "enable", 6) == 0 && vim_iswhite(arg[6])) { enable = TRUE; arg = skipwhite(arg + 6); } else if (STRNCMP(arg, "disable", 7) == 0 && vim_iswhite(arg[7])) { enable = FALSE; arg = skipwhite(arg + 7); } /* * If there is no argument, display all menus. */ if (*arg == NUL) { show_menus(arg, modes); return; } #ifdef FEAT_TOOLBAR /* * Need to get the toolbar icon index before doing the translation. */ menuarg.iconidx = -1; menuarg.icon_builtin = FALSE; if (menu_is_toolbar(arg)) { menu_path = menu_skip_part(arg); if (*menu_path == '.') { p = menu_skip_part(++menu_path); if (STRNCMP(menu_path, "BuiltIn", 7) == 0) { if (skipdigits(menu_path + 7) == p) { menuarg.iconidx = atoi((char *)menu_path + 7); if (menuarg.iconidx >= (int)TOOLBAR_NAME_COUNT) menuarg.iconidx = -1; else menuarg.icon_builtin = TRUE; } } else { for (i = 0; i < (int)TOOLBAR_NAME_COUNT; ++i) if (STRNCMP(toolbar_names[i], menu_path, p - menu_path) == 0) { menuarg.iconidx = i; break; } } } } #endif menu_path = arg; if (*menu_path == '.') { EMSG2(_(e_invarg2), menu_path); goto theend; } map_to = menu_translate_tab_and_shift(arg); /* * If there is only a menu name, display menus with that name. */ if (*map_to == NUL && !unmenu && enable == MAYBE) { show_menus(menu_path, modes); goto theend; } else if (*map_to != NUL && (unmenu || enable != MAYBE)) { EMSG(_(e_trailing)); goto theend; } #if defined(FEAT_GUI) && !(defined(FEAT_GUI_GTK) || defined(FEAT_GUI_PHOTON)) old_menu_height = gui.menu_height; # if defined(FEAT_TOOLBAR) && !defined(FEAT_GUI_W32) && !defined(FEAT_GUI_W16) old_toolbar_height = gui.toolbar_height; # endif #endif if (enable != MAYBE) { /* * Change sensitivity of the menu. * For the PopUp menu, remove a menu for each mode separately. * Careful: menu_nable_recurse() changes menu_path. */ if (STRCMP(menu_path, "*") == 0) /* meaning: do all menus */ menu_path = (char_u *)""; if (menu_is_popup(menu_path)) { for (i = 0; i < MENU_INDEX_TIP; ++i) if (modes & (1 << i)) { p = popup_mode_name(menu_path, i); if (p != NULL) { menu_nable_recurse(root_menu, p, MENU_ALL_MODES, enable); vim_free(p); } } } menu_nable_recurse(root_menu, menu_path, modes, enable); } else if (unmenu) { /* * Delete menu(s). */ if (STRCMP(menu_path, "*") == 0) /* meaning: remove all menus */ menu_path = (char_u *)""; /* * For the PopUp menu, remove a menu for each mode separately. */ if (menu_is_popup(menu_path)) { for (i = 0; i < MENU_INDEX_TIP; ++i) if (modes & (1 << i)) { p = popup_mode_name(menu_path, i); if (p != NULL) { remove_menu(&root_menu, p, MENU_ALL_MODES, TRUE); vim_free(p); } } } /* Careful: remove_menu() changes menu_path */ remove_menu(&root_menu, menu_path, modes, FALSE); } else { /* * Add menu(s). * Replace special key codes. */ if (STRICMP(map_to, "<nop>") == 0) /* "<Nop>" means nothing */ { map_to = (char_u *)""; map_buf = NULL; } else if (modes & MENU_TIP_MODE) map_buf = NULL; /* Menu tips are plain text. */ else map_to = replace_termcodes(map_to, &map_buf, FALSE, TRUE, special); menuarg.modes = modes; #ifdef FEAT_TOOLBAR menuarg.iconfile = icon; #endif menuarg.noremap[0] = noremap; menuarg.silent[0] = silent; add_menu_path(menu_path, &menuarg, pri_tab, map_to #ifdef FEAT_GUI_W32 , TRUE #endif ); /* * For the PopUp menu, add a menu for each mode separately. */ if (menu_is_popup(menu_path)) { for (i = 0; i < MENU_INDEX_TIP; ++i) if (modes & (1 << i)) { p = popup_mode_name(menu_path, i); if (p != NULL) { /* Include all modes, to make ":amenu" work */ menuarg.modes = modes; #ifdef FEAT_TOOLBAR menuarg.iconfile = NULL; menuarg.iconidx = -1; menuarg.icon_builtin = FALSE; #endif add_menu_path(p, &menuarg, pri_tab, map_to #ifdef FEAT_GUI_W32 , TRUE #endif ); vim_free(p); } } } vim_free(map_buf); } #if defined(FEAT_GUI) && !(defined(FEAT_GUI_GTK)) /* If the menubar height changed, resize the window */ if (gui.in_use && (gui.menu_height != old_menu_height # if defined(FEAT_TOOLBAR) && !defined(FEAT_GUI_W32) && !defined(FEAT_GUI_W16) || gui.toolbar_height != old_toolbar_height # endif )) gui_set_shellsize(FALSE, FALSE, RESIZE_VERT); #endif theend: ; } /* * Add the menu with the given name to the menu hierarchy */ static int add_menu_path(menu_path, menuarg, pri_tab, call_data #ifdef FEAT_GUI_W32 , addtearoff #endif ) char_u *menu_path; vimmenu_T *menuarg; /* passes modes, iconfile, iconidx, icon_builtin, silent[0], noremap[0] */ int *pri_tab; char_u *call_data; #ifdef FEAT_GUI_W32 int addtearoff; /* may add tearoff item */ #endif { char_u *path_name; int modes = menuarg->modes; vimmenu_T **menup; vimmenu_T *menu = NULL; vimmenu_T *parent; vimmenu_T **lower_pri; char_u *p; char_u *name; char_u *dname; char_u *next_name; int i; int c; int d; #ifdef FEAT_GUI int idx; int new_idx; #endif int pri_idx = 0; int old_modes = 0; int amenu; #ifdef FEAT_MULTI_LANG char_u *en_name; char_u *map_to = NULL; #endif /* Make a copy so we can stuff around with it, since it could be const */ path_name = vim_strsave(menu_path); if (path_name == NULL) return FAIL; menup = &root_menu; parent = NULL; name = path_name; while (*name) { /* Get name of this element in the menu hierarchy, and the simplified * name (without mnemonic and accelerator text). */ next_name = menu_name_skip(name); #ifdef FEAT_MULTI_LANG map_to = menutrans_lookup(name, (int)STRLEN(name)); if (map_to != NULL) { en_name = name; name = map_to; } else en_name = NULL; #endif dname = menu_text(name, NULL, NULL); if (dname == NULL) goto erret; if (*dname == NUL) { /* Only a mnemonic or accelerator is not valid. */ EMSG(_("E792: Empty menu name")); goto erret; } /* See if it's already there */ lower_pri = menup; #ifdef FEAT_GUI idx = 0; new_idx = 0; #endif menu = *menup; while (menu != NULL) { if (menu_name_equal(name, menu) || menu_name_equal(dname, menu)) { if (*next_name == NUL && menu->children != NULL) { if (!sys_menu) EMSG(_("E330: Menu path must not lead to a sub-menu")); goto erret; } if (*next_name != NUL && menu->children == NULL #ifdef FEAT_GUI_W32 && addtearoff #endif ) { if (!sys_menu) EMSG(_(e_notsubmenu)); goto erret; } break; } menup = &menu->next; /* Count menus, to find where this one needs to be inserted. * Ignore menus that are not in the menubar (PopUp and Toolbar) */ if (parent != NULL || menu_is_menubar(menu->name)) { #ifdef FEAT_GUI ++idx; #endif if (menu->priority <= pri_tab[pri_idx]) { lower_pri = menup; #ifdef FEAT_GUI new_idx = idx; #endif } } menu = menu->next; } if (menu == NULL) { if (*next_name == NUL && parent == NULL) { EMSG(_("E331: Must not add menu items directly to menu bar")); goto erret; } if (menu_is_separator(dname) && *next_name != NUL) { EMSG(_("E332: Separator cannot be part of a menu path")); goto erret; } /* Not already there, so lets add it */ menu = (vimmenu_T *)alloc_clear((unsigned)sizeof(vimmenu_T)); if (menu == NULL) goto erret; menu->modes = modes; menu->enabled = MENU_ALL_MODES; menu->name = vim_strsave(name); /* separate mnemonic and accelerator text from actual menu name */ menu->dname = menu_text(name, &menu->mnemonic, &menu->actext); #ifdef FEAT_MULTI_LANG if (en_name != NULL) { menu->en_name = vim_strsave(en_name); menu->en_dname = menu_text(en_name, NULL, NULL); } else { menu->en_name = NULL; menu->en_dname = NULL; } #endif menu->priority = pri_tab[pri_idx]; menu->parent = parent; #ifdef FEAT_GUI_MOTIF menu->sensitive = TRUE; /* the default */ #endif #ifdef FEAT_BEVAL_TIP menu->tip = NULL; #endif #ifdef FEAT_GUI_ATHENA menu->image = None; /* X-Windows definition for NULL*/ #endif /* * Add after menu that has lower priority. */ menu->next = *lower_pri; *lower_pri = menu; old_modes = 0; #ifdef FEAT_TOOLBAR menu->iconidx = menuarg->iconidx; menu->icon_builtin = menuarg->icon_builtin; if (*next_name == NUL && menuarg->iconfile != NULL) menu->iconfile = vim_strsave(menuarg->iconfile); #endif #if defined(FEAT_GUI_W32) && defined(FEAT_TEAROFF) /* the tearoff item must be present in the modes of each item. */ if (parent != NULL && menu_is_tearoff(parent->children->dname)) parent->children->modes |= modes; #endif } else { old_modes = menu->modes; /* * If this menu option was previously only available in other * modes, then make sure it's available for this one now * Also enable a menu when it's created or changed. */ #ifdef FEAT_GUI_W32 /* If adding a tearbar (addtearoff == FALSE) don't update modes */ if (addtearoff) #endif { menu->modes |= modes; menu->enabled |= modes; } } #ifdef FEAT_GUI /* * Add the menu item when it's used in one of the modes, but not when * only a tooltip is defined. */ if ((old_modes & MENU_ALL_MODES) == 0 && (menu->modes & MENU_ALL_MODES) != 0) { if (gui.in_use) /* Otherwise it will be added when GUI starts */ { if (*next_name == NUL) { /* Real menu item, not sub-menu */ gui_mch_add_menu_item(menu, new_idx); /* Want to update menus now even if mode not changed */ force_menu_update = TRUE; } else { /* Sub-menu (not at end of path yet) */ gui_mch_add_menu(menu, new_idx); } } # if defined(FEAT_GUI_W32) & defined(FEAT_TEAROFF) /* When adding a new submenu, may add a tearoff item */ if ( addtearoff && *next_name && vim_strchr(p_go, GO_TEAROFF) != NULL && menu_is_menubar(name)) { char_u *tearpath; /* * The pointers next_name & path_name refer to a string with * \'s and ^V's stripped out. But menu_path is a "raw" * string, so we must correct for special characters. */ tearpath = alloc((unsigned int)STRLEN(menu_path) + TEAR_LEN + 2); if (tearpath != NULL) { char_u *s; int idx; STRCPY(tearpath, menu_path); idx = (int)(next_name - path_name - 1); for (s = tearpath; *s && s < tearpath + idx; mb_ptr_adv(s)) { if ((*s == '\\' || *s == Ctrl_V) && s[1]) { ++idx; ++s; } } tearpath[idx] = NUL; gui_add_tearoff(tearpath, pri_tab, pri_idx); vim_free(tearpath); } } # endif } #endif /* FEAT_GUI */ menup = &menu->children; parent = menu; name = next_name; vim_free(dname); dname = NULL; if (pri_tab[pri_idx + 1] != -1) ++pri_idx; } vim_free(path_name); /* * Only add system menu items which have not been defined yet. * First check if this was an ":amenu". */ amenu = ((modes & (MENU_NORMAL_MODE | MENU_INSERT_MODE)) == (MENU_NORMAL_MODE | MENU_INSERT_MODE)); if (sys_menu) modes &= ~old_modes; if (menu != NULL && modes) { #ifdef FEAT_GUI menu->cb = gui_menu_cb; #endif p = (call_data == NULL) ? NULL : vim_strsave(call_data); /* loop over all modes, may add more than one */ for (i = 0; i < MENU_MODES; ++i) { if (modes & (1 << i)) { /* free any old menu */ free_menu_string(menu, i); /* For "amenu", may insert an extra character. * Don't do this if adding a tearbar (addtearoff == FALSE). * Don't do this for "<Nop>". */ c = 0; d = 0; if (amenu && call_data != NULL && *call_data != NUL #ifdef FEAT_GUI_W32 && addtearoff #endif ) { switch (1 << i) { case MENU_VISUAL_MODE: case MENU_SELECT_MODE: case MENU_OP_PENDING_MODE: case MENU_CMDLINE_MODE: c = Ctrl_C; break; case MENU_INSERT_MODE: c = Ctrl_BSL; d = Ctrl_O; break; } } if (c != 0) { menu->strings[i] = alloc((unsigned)(STRLEN(call_data) + 5 )); if (menu->strings[i] != NULL) { menu->strings[i][0] = c; if (d == 0) STRCPY(menu->strings[i] + 1, call_data); else { menu->strings[i][1] = d; STRCPY(menu->strings[i] + 2, call_data); } if (c == Ctrl_C) { int len = (int)STRLEN(menu->strings[i]); /* Append CTRL-\ CTRL-G to obey 'insertmode'. */ menu->strings[i][len] = Ctrl_BSL; menu->strings[i][len + 1] = Ctrl_G; menu->strings[i][len + 2] = NUL; } } } else menu->strings[i] = p; menu->noremap[i] = menuarg->noremap[0]; menu->silent[i] = menuarg->silent[0]; } } #if defined(FEAT_TOOLBAR) && !defined(FEAT_GUI_W32) \ && (defined(FEAT_BEVAL) || defined(FEAT_GUI_GTK)) /* Need to update the menu tip. */ if (modes & MENU_TIP_MODE) gui_mch_menu_set_tip(menu); #endif } return OK; erret: vim_free(path_name); vim_free(dname); /* Delete any empty submenu we added before discovering the error. Repeat * for higher levels. */ while (parent != NULL && parent->children == NULL) { if (parent->parent == NULL) menup = &root_menu; else menup = &parent->parent->children; for ( ; *menup != NULL && *menup != parent; menup = &((*menup)->next)) ; if (*menup == NULL) /* safety check */ break; parent = parent->parent; free_menu(menup); } return FAIL; } /* * Set the (sub)menu with the given name to enabled or disabled. * Called recursively. */ static int menu_nable_recurse(menu, name, modes, enable) vimmenu_T *menu; char_u *name; int modes; int enable; { char_u *p; if (menu == NULL) return OK; /* Got to bottom of hierarchy */ /* Get name of this element in the menu hierarchy */ p = menu_name_skip(name); /* Find the menu */ while (menu != NULL) { if (*name == NUL || *name == '*' || menu_name_equal(name, menu)) { if (*p != NUL) { if (menu->children == NULL) { EMSG(_(e_notsubmenu)); return FAIL; } if (menu_nable_recurse(menu->children, p, modes, enable) == FAIL) return FAIL; } else if (enable) menu->enabled |= modes; else menu->enabled &= ~modes; /* * When name is empty, we are doing all menu items for the given * modes, so keep looping, otherwise we are just doing the named * menu item (which has been found) so break here. */ if (*name != NUL && *name != '*') break; } menu = menu->next; } if (*name != NUL && *name != '*' && menu == NULL) { EMSG2(_(e_nomenu), name); return FAIL; } #ifdef FEAT_GUI /* Want to update menus now even if mode not changed */ force_menu_update = TRUE; #endif return OK; } /* * Remove the (sub)menu with the given name from the menu hierarchy * Called recursively. */ static int remove_menu(menup, name, modes, silent) vimmenu_T **menup; char_u *name; int modes; int silent; /* don't give error messages */ { vimmenu_T *menu; vimmenu_T *child; char_u *p; if (*menup == NULL) return OK; /* Got to bottom of hierarchy */ /* Get name of this element in the menu hierarchy */ p = menu_name_skip(name); /* Find the menu */ while ((menu = *menup) != NULL) { if (*name == NUL || menu_name_equal(name, menu)) { if (*p != NUL && menu->children == NULL) { if (!silent) EMSG(_(e_notsubmenu)); return FAIL; } if ((menu->modes & modes) != 0x0) { #if defined(FEAT_GUI_W32) & defined(FEAT_TEAROFF) /* * If we are removing all entries for this menu,MENU_ALL_MODES, * Then kill any tearoff before we start */ if (*p == NUL && modes == MENU_ALL_MODES) { if (IsWindow(menu->tearoff_handle)) DestroyWindow(menu->tearoff_handle); } #endif if (remove_menu(&menu->children, p, modes, silent) == FAIL) return FAIL; } else if (*name != NUL) { if (!silent) EMSG(_(e_othermode)); return FAIL; } /* * When name is empty, we are removing all menu items for the given * modes, so keep looping, otherwise we are just removing the named * menu item (which has been found) so break here. */ if (*name != NUL) break; /* Remove the menu item for the given mode[s]. If the menu item * is no longer valid in ANY mode, delete it */ menu->modes &= ~modes; if (modes & MENU_TIP_MODE) free_menu_string(menu, MENU_INDEX_TIP); if ((menu->modes & MENU_ALL_MODES) == 0) free_menu(menup); else menup = &menu->next; } else menup = &menu->next; } if (*name != NUL) { if (menu == NULL) { if (!silent) EMSG2(_(e_nomenu), name); return FAIL; } /* Recalculate modes for menu based on the new updated children */ menu->modes &= ~modes; #if defined(FEAT_GUI_W32) & defined(FEAT_TEAROFF) if ((s_tearoffs) && (menu->children != NULL)) /* there's a tear bar.. */ child = menu->children->next; /* don't count tearoff bar */ else #endif child = menu->children; for ( ; child != NULL; child = child->next) menu->modes |= child->modes; if (modes & MENU_TIP_MODE) { free_menu_string(menu, MENU_INDEX_TIP); #if defined(FEAT_TOOLBAR) && !defined(FEAT_GUI_W32) \ && (defined(FEAT_BEVAL) || defined(FEAT_GUI_GTK)) /* Need to update the menu tip. */ if (gui.in_use) gui_mch_menu_set_tip(menu); #endif } if ((menu->modes & MENU_ALL_MODES) == 0) { /* The menu item is no longer valid in ANY mode, so delete it */ #if defined(FEAT_GUI_W32) & defined(FEAT_TEAROFF) if (s_tearoffs && menu->children != NULL) /* there's a tear bar.. */ free_menu(&menu->children); #endif *menup = menu; free_menu(menup); } } return OK; } /* * Free the given menu structure and remove it from the linked list. */ static void free_menu(menup) vimmenu_T **menup; { int i; vimmenu_T *menu; menu = *menup; #ifdef FEAT_GUI /* Free machine specific menu structures (only when already created) */ /* Also may rebuild a tearoff'ed menu */ if (gui.in_use) gui_mch_destroy_menu(menu); #endif /* Don't change *menup until after calling gui_mch_destroy_menu(). The * MacOS code needs the original structure to properly delete the menu. */ *menup = menu->next; vim_free(menu->name); vim_free(menu->dname); #ifdef FEAT_MULTI_LANG vim_free(menu->en_name); vim_free(menu->en_dname); #endif vim_free(menu->actext); #ifdef FEAT_TOOLBAR vim_free(menu->iconfile); # ifdef FEAT_GUI_MOTIF vim_free(menu->xpm_fname); # endif #endif for (i = 0; i < MENU_MODES; i++) free_menu_string(menu, i); vim_free(menu); #ifdef FEAT_GUI /* Want to update menus now even if mode not changed */ force_menu_update = TRUE; #endif } /* * Free the menu->string with the given index. */ static void free_menu_string(menu, idx) vimmenu_T *menu; int idx; { int count = 0; int i; for (i = 0; i < MENU_MODES; i++) if (menu->strings[i] == menu->strings[idx]) count++; if (count == 1) vim_free(menu->strings[idx]); menu->strings[idx] = NULL; } /* * Show the mapping associated with a menu item or hierarchy in a sub-menu. */ static int show_menus(path_name, modes) char_u *path_name; int modes; { char_u *p; char_u *name; vimmenu_T *menu; vimmenu_T *parent = NULL; menu = root_menu; name = path_name = vim_strsave(path_name); if (path_name == NULL) return FAIL; /* First, find the (sub)menu with the given name */ while (*name) { p = menu_name_skip(name); while (menu != NULL) { if (menu_name_equal(name, menu)) { /* Found menu */ if (*p != NUL && menu->children == NULL) { EMSG(_(e_notsubmenu)); vim_free(path_name); return FAIL; } else if ((menu->modes & modes) == 0x0) { EMSG(_(e_othermode)); vim_free(path_name); return FAIL; } break; } menu = menu->next; } if (menu == NULL) { EMSG2(_(e_nomenu), name); vim_free(path_name); return FAIL; } name = p; parent = menu; menu = menu->children; } vim_free(path_name); /* Now we have found the matching menu, and we list the mappings */ /* Highlight title */ MSG_PUTS_TITLE(_("\n--- Menus ---")); show_menus_recursive(parent, modes, 0); return OK; } /* * Recursively show the mappings associated with the menus under the given one */ static void show_menus_recursive(menu, modes, depth) vimmenu_T *menu; int modes; int depth; { int i; int bit; if (menu != NULL && (menu->modes & modes) == 0x0) return; if (menu != NULL) { msg_putchar('\n'); if (got_int) /* "q" hit for "--more--" */ return; for (i = 0; i < depth; i++) MSG_PUTS(" "); if (menu->priority) { msg_outnum((long)menu->priority); MSG_PUTS(" "); } /* Same highlighting as for directories!? */ msg_outtrans_attr(menu->name, hl_attr(HLF_D)); } if (menu != NULL && menu->children == NULL) { for (bit = 0; bit < MENU_MODES; bit++) if ((menu->modes & modes & (1 << bit)) != 0) { msg_putchar('\n'); if (got_int) /* "q" hit for "--more--" */ return; for (i = 0; i < depth + 2; i++) MSG_PUTS(" "); msg_putchar(menu_mode_chars[bit]); if (menu->noremap[bit] == REMAP_NONE) msg_putchar('*'); else if (menu->noremap[bit] == REMAP_SCRIPT) msg_putchar('&'); else msg_putchar(' '); if (menu->silent[bit]) msg_putchar('s'); else msg_putchar(' '); if ((menu->modes & menu->enabled & (1 << bit)) == 0) msg_putchar('-'); else msg_putchar(' '); MSG_PUTS(" "); if (*menu->strings[bit] == NUL) msg_puts_attr((char_u *)"<Nop>", hl_attr(HLF_8)); else msg_outtrans_special(menu->strings[bit], FALSE); } } else { if (menu == NULL) { menu = root_menu; depth--; } else menu = menu->children; /* recursively show all children. Skip PopUp[nvoci]. */ for (; menu != NULL && !got_int; menu = menu->next) if (!menu_is_hidden(menu->dname)) show_menus_recursive(menu, modes, depth + 1); } } #ifdef FEAT_CMDL_COMPL /* * Used when expanding menu names. */ static vimmenu_T *expand_menu = NULL; static int expand_modes = 0x0; static int expand_emenu; /* TRUE for ":emenu" command */ /* * Work out what to complete when doing command line completion of menu names. */ char_u * set_context_in_menu_cmd(xp, cmd, arg, forceit) expand_T *xp; char_u *cmd; char_u *arg; int forceit; { char_u *after_dot; char_u *p; char_u *path_name = NULL; char_u *name; int unmenu; vimmenu_T *menu; int expand_menus; xp->xp_context = EXPAND_UNSUCCESSFUL; /* Check for priority numbers, enable and disable */ for (p = arg; *p; ++p) if (!VIM_ISDIGIT(*p) && *p != '.') break; if (!vim_iswhite(*p)) { if (STRNCMP(arg, "enable", 6) == 0 && (arg[6] == NUL || vim_iswhite(arg[6]))) p = arg + 6; else if (STRNCMP(arg, "disable", 7) == 0 && (arg[7] == NUL || vim_iswhite(arg[7]))) p = arg + 7; else p = arg; } while (*p != NUL && vim_iswhite(*p)) ++p; arg = after_dot = p; for (; *p && !vim_iswhite(*p); ++p) { if ((*p == '\\' || *p == Ctrl_V) && p[1] != NUL) p++; else if (*p == '.') after_dot = p + 1; } /* ":tearoff" and ":popup" only use menus, not entries */ expand_menus = !((*cmd == 't' && cmd[1] == 'e') || *cmd == 'p'); expand_emenu = (*cmd == 'e'); if (expand_menus && vim_iswhite(*p)) return NULL; /* TODO: check for next command? */ if (*p == NUL) /* Complete the menu name */ { /* * With :unmenu, you only want to match menus for the appropriate mode. * With :menu though you might want to add a menu with the same name as * one in another mode, so match menus from other modes too. */ expand_modes = get_menu_cmd_modes(cmd, forceit, NULL, &unmenu); if (!unmenu) expand_modes = MENU_ALL_MODES; menu = root_menu; if (after_dot != arg) { path_name = alloc((unsigned)(after_dot - arg)); if (path_name == NULL) return NULL; vim_strncpy(path_name, arg, after_dot - arg - 1); } name = path_name; while (name != NULL && *name) { p = menu_name_skip(name); while (menu != NULL) { if (menu_name_equal(name, menu)) { /* Found menu */ if ((*p != NUL && menu->children == NULL) || ((menu->modes & expand_modes) == 0x0)) { /* * Menu path continues, but we have reached a leaf. * Or menu exists only in another mode. */ vim_free(path_name); return NULL; } break; } menu = menu->next; } if (menu == NULL) { /* No menu found with the name we were looking for */ vim_free(path_name); return NULL; } name = p; menu = menu->children; } vim_free(path_name); xp->xp_context = expand_menus ? EXPAND_MENUNAMES : EXPAND_MENUS; xp->xp_pattern = after_dot; expand_menu = menu; } else /* We're in the mapping part */ xp->xp_context = EXPAND_NOTHING; return NULL; } /* * Function given to ExpandGeneric() to obtain the list of (sub)menus (not * entries). */ char_u * get_menu_name(xp, idx) expand_T *xp UNUSED; int idx; { static vimmenu_T *menu = NULL; char_u *str; #ifdef FEAT_MULTI_LANG static int should_advance = FALSE; #endif if (idx == 0) /* first call: start at first item */ { menu = expand_menu; #ifdef FEAT_MULTI_LANG should_advance = FALSE; #endif } /* Skip PopUp[nvoci]. */ while (menu != NULL && (menu_is_hidden(menu->dname) || menu_is_separator(menu->dname) || menu_is_tearoff(menu->dname) || menu->children == NULL)) menu = menu->next; if (menu == NULL) /* at end of linked list */ return NULL; if (menu->modes & expand_modes) #ifdef FEAT_MULTI_LANG if (should_advance) str = menu->en_dname; else { #endif str = menu->dname; #ifdef FEAT_MULTI_LANG if (menu->en_dname == NULL) should_advance = TRUE; } #endif else str = (char_u *)""; #ifdef FEAT_MULTI_LANG if (should_advance) #endif /* Advance to next menu entry. */ menu = menu->next; #ifdef FEAT_MULTI_LANG should_advance = !should_advance; #endif return str; } /* * Function given to ExpandGeneric() to obtain the list of menus and menu * entries. */ char_u * get_menu_names(xp, idx) expand_T *xp UNUSED; int idx; { static vimmenu_T *menu = NULL; #define TBUFFER_LEN 256 static char_u tbuffer[TBUFFER_LEN]; /*hack*/ char_u *str; #ifdef FEAT_MULTI_LANG static int should_advance = FALSE; #endif if (idx == 0) /* first call: start at first item */ { menu = expand_menu; #ifdef FEAT_MULTI_LANG should_advance = FALSE; #endif } /* Skip Browse-style entries, popup menus and separators. */ while (menu != NULL && ( menu_is_hidden(menu->dname) || (expand_emenu && menu_is_separator(menu->dname)) || menu_is_tearoff(menu->dname) #ifndef FEAT_BROWSE || menu->dname[STRLEN(menu->dname) - 1] == '.' #endif )) menu = menu->next; if (menu == NULL) /* at end of linked list */ return NULL; if (menu->modes & expand_modes) { if (menu->children != NULL) { #ifdef FEAT_MULTI_LANG if (should_advance) vim_strncpy(tbuffer, menu->en_dname, TBUFFER_LEN - 2); else { #endif vim_strncpy(tbuffer, menu->dname, TBUFFER_LEN - 2); #ifdef FEAT_MULTI_LANG if (menu->en_dname == NULL) should_advance = TRUE; } #endif /* hack on menu separators: use a 'magic' char for the separator * so that '.' in names gets escaped properly */ STRCAT(tbuffer, "\001"); str = tbuffer; } else #ifdef FEAT_MULTI_LANG { if (should_advance) str = menu->en_dname; else { #endif str = menu->dname; #ifdef FEAT_MULTI_LANG if (menu->en_dname == NULL) should_advance = TRUE; } } #endif } else str = (char_u *)""; #ifdef FEAT_MULTI_LANG if (should_advance) #endif /* Advance to next menu entry. */ menu = menu->next; #ifdef FEAT_MULTI_LANG should_advance = !should_advance; #endif return str; } #endif /* FEAT_CMDL_COMPL */ /* * Skip over this element of the menu path and return the start of the next * element. Any \ and ^Vs are removed from the current element. * "name" may be modified. */ char_u * menu_name_skip(name) char_u *name; { char_u *p; for (p = name; *p && *p != '.'; mb_ptr_adv(p)) { if (*p == '\\' || *p == Ctrl_V) { STRMOVE(p, p + 1); if (*p == NUL) break; } } if (*p) *p++ = NUL; return p; } /* * Return TRUE when "name" matches with menu "menu". The name is compared in * two ways: raw menu name and menu name without '&'. ignore part after a TAB. */ static int menu_name_equal(name, menu) char_u *name; vimmenu_T *menu; { #ifdef FEAT_MULTI_LANG if (menu->en_name != NULL && (menu_namecmp(name, menu->en_name) || menu_namecmp(name, menu->en_dname))) return TRUE; #endif return menu_namecmp(name, menu->name) || menu_namecmp(name, menu->dname); } static int menu_namecmp(name, mname) char_u *name; char_u *mname; { int i; for (i = 0; name[i] != NUL && name[i] != TAB; ++i) if (name[i] != mname[i]) break; return ((name[i] == NUL || name[i] == TAB) && (mname[i] == NUL || mname[i] == TAB)); } /* * Return the modes specified by the given menu command (eg :menu! returns * MENU_CMDLINE_MODE | MENU_INSERT_MODE). * If "noremap" is not NULL, then the flag it points to is set according to * whether the command is a "nore" command. * If "unmenu" is not NULL, then the flag it points to is set according to * whether the command is an "unmenu" command. */ static int get_menu_cmd_modes(cmd, forceit, noremap, unmenu) char_u *cmd; int forceit; /* Was there a "!" after the command? */ int *noremap; int *unmenu; { int modes; switch (*cmd++) { case 'v': /* vmenu, vunmenu, vnoremenu */ modes = MENU_VISUAL_MODE | MENU_SELECT_MODE; break; case 'x': /* xmenu, xunmenu, xnoremenu */ modes = MENU_VISUAL_MODE; break; case 's': /* smenu, sunmenu, snoremenu */ modes = MENU_SELECT_MODE; break; case 'o': /* omenu */ modes = MENU_OP_PENDING_MODE; break; case 'i': /* imenu */ modes = MENU_INSERT_MODE; break; case 't': modes = MENU_TIP_MODE; /* tmenu */ break; case 'c': /* cmenu */ modes = MENU_CMDLINE_MODE; break; case 'a': /* amenu */ modes = MENU_INSERT_MODE | MENU_CMDLINE_MODE | MENU_NORMAL_MODE | MENU_VISUAL_MODE | MENU_SELECT_MODE | MENU_OP_PENDING_MODE; break; case 'n': if (*cmd != 'o') /* nmenu, not noremenu */ { modes = MENU_NORMAL_MODE; break; } /* FALLTHROUGH */ default: --cmd; if (forceit) /* menu!! */ modes = MENU_INSERT_MODE | MENU_CMDLINE_MODE; else /* menu */ modes = MENU_NORMAL_MODE | MENU_VISUAL_MODE | MENU_SELECT_MODE | MENU_OP_PENDING_MODE; } if (noremap != NULL) *noremap = (*cmd == 'n' ? REMAP_NONE : REMAP_YES); if (unmenu != NULL) *unmenu = (*cmd == 'u'); return modes; } /* * Modify a menu name starting with "PopUp" to include the mode character. * Returns the name in allocated memory (NULL for failure). */ static char_u * popup_mode_name(name, idx) char_u *name; int idx; { char_u *p; int len = (int)STRLEN(name); p = vim_strnsave(name, len + 1); if (p != NULL) { mch_memmove(p + 6, p + 5, (size_t)(len - 4)); p[5] = menu_mode_chars[idx]; } return p; } #if defined(FEAT_GUI) || defined(PROTO) /* * Return the index into the menu->strings or menu->noremap arrays for the * current state. Returns MENU_INDEX_INVALID if there is no mapping for the * given menu in the current mode. */ int get_menu_index(menu, state) vimmenu_T *menu; int state; { int idx; if ((state & INSERT)) idx = MENU_INDEX_INSERT; else if (state & CMDLINE) idx = MENU_INDEX_CMDLINE; #ifdef FEAT_VISUAL else if (VIsual_active) { if (VIsual_select) idx = MENU_INDEX_SELECT; else idx = MENU_INDEX_VISUAL; } #endif else if (state == HITRETURN || state == ASKMORE) idx = MENU_INDEX_CMDLINE; else if (finish_op) idx = MENU_INDEX_OP_PENDING; else if ((state & NORMAL)) idx = MENU_INDEX_NORMAL; else idx = MENU_INDEX_INVALID; if (idx != MENU_INDEX_INVALID && menu->strings[idx] == NULL) idx = MENU_INDEX_INVALID; return idx; } #endif /* * Duplicate the menu item text and then process to see if a mnemonic key * and/or accelerator text has been identified. * Returns a pointer to allocated memory, or NULL for failure. * If mnemonic != NULL, *mnemonic is set to the character after the first '&'. * If actext != NULL, *actext is set to the text after the first TAB. */ static char_u * menu_text(str, mnemonic, actext) char_u *str; int *mnemonic; char_u **actext; { char_u *p; char_u *text; /* Locate accelerator text, after the first TAB */ p = vim_strchr(str, TAB); if (p != NULL) { if (actext != NULL) *actext = vim_strsave(p + 1); text = vim_strnsave(str, (int)(p - str)); } else text = vim_strsave(str); /* Find mnemonic characters "&a" and reduce "&&" to "&". */ for (p = text; p != NULL; ) { p = vim_strchr(p, '&'); if (p != NULL) { if (p[1] == NUL) /* trailing "&" */ break; if (mnemonic != NULL && p[1] != '&') #if !defined(__MVS__) || defined(MOTIF390_MNEMONIC_FIXED) *mnemonic = p[1]; #else { /* * Well there is a bug in the Motif libraries on OS390 Unix. * The mnemonic keys needs to be converted to ASCII values * first. * This behavior has been seen in 2.8 and 2.9. */ char c = p[1]; __etoa_l(&c, 1); *mnemonic = c; } #endif STRMOVE(p, p + 1); p = p + 1; } } return text; } /* * Return TRUE if "name" can be a menu in the MenuBar. */ int menu_is_menubar(name) char_u *name; { return (!menu_is_popup(name) && !menu_is_toolbar(name) && *name != MNU_HIDDEN_CHAR); } /* * Return TRUE if "name" is a popup menu name. */ int menu_is_popup(name) char_u *name; { return (STRNCMP(name, "PopUp", 5) == 0); } #if (defined(FEAT_GUI_MOTIF) && (XmVersion <= 1002)) || defined(PROTO) /* * Return TRUE if "name" is part of a popup menu. */ int menu_is_child_of_popup(menu) vimmenu_T *menu; { while (menu->parent != NULL) menu = menu->parent; return menu_is_popup(menu->name); } #endif /* * Return TRUE if "name" is a toolbar menu name. */ int menu_is_toolbar(name) char_u *name; { return (STRNCMP(name, "ToolBar", 7) == 0); } /* * Return TRUE if the name is a menu separator identifier: Starts and ends * with '-' */ int menu_is_separator(name) char_u *name; { return (name[0] == '-' && name[STRLEN(name) - 1] == '-'); } /* * Return TRUE if the menu is hidden: Starts with ']' */ static int menu_is_hidden(name) char_u *name; { return (name[0] == ']') || (menu_is_popup(name) && name[5] != NUL); } #if defined(FEAT_CMDL_COMPL) \ || (defined(FEAT_GUI_W32) && defined(FEAT_TEAROFF)) /* * Return TRUE if the menu is the tearoff menu. */ static int menu_is_tearoff(name) char_u *name UNUSED; { #ifdef FEAT_GUI return (STRCMP(name, TEAR_STRING) == 0); #else return FALSE; #endif } #endif #ifdef FEAT_GUI static int get_menu_mode() { #ifdef FEAT_VISUAL if (VIsual_active) { if (VIsual_select) return MENU_INDEX_SELECT; return MENU_INDEX_VISUAL; } #endif if (State & INSERT) return MENU_INDEX_INSERT; if ((State & CMDLINE) || State == ASKMORE || State == HITRETURN) return MENU_INDEX_CMDLINE; if (finish_op) return MENU_INDEX_OP_PENDING; if (State & NORMAL) return MENU_INDEX_NORMAL; if (State & LANGMAP) /* must be a "r" command, like Insert mode */ return MENU_INDEX_INSERT; return MENU_INDEX_INVALID; } /* * Check that a pointer appears in the menu tree. Used to protect from using * a menu that was deleted after it was selected but before the event was * handled. * Return OK or FAIL. Used recursively. */ int check_menu_pointer(root, menu_to_check) vimmenu_T *root; vimmenu_T *menu_to_check; { vimmenu_T *p; for (p = root; p != NULL; p = p->next) if (p == menu_to_check || (p->children != NULL && check_menu_pointer(p->children, menu_to_check) == OK)) return OK; return FAIL; } /* * After we have started the GUI, then we can create any menus that have been * defined. This is done once here. add_menu_path() may have already been * called to define these menus, and may be called again. This function calls * itself recursively. Should be called at the top level with: * gui_create_initial_menus(root_menu, NULL); */ void gui_create_initial_menus(menu) vimmenu_T *menu; { int idx = 0; while (menu != NULL) { /* Don't add a menu when only a tip was defined. */ if (menu->modes & MENU_ALL_MODES) { if (menu->children != NULL) { gui_mch_add_menu(menu, idx); gui_create_initial_menus(menu->children); } else gui_mch_add_menu_item(menu, idx); } menu = menu->next; ++idx; } } /* * Used recursively by gui_update_menus (see below) */ static void gui_update_menus_recurse(menu, mode) vimmenu_T *menu; int mode; { int grey; while (menu) { if ((menu->modes & menu->enabled & mode) #if defined(FEAT_GUI_W32) && defined(FEAT_TEAROFF) || menu_is_tearoff(menu->dname) #endif ) grey = FALSE; else grey = TRUE; #ifdef FEAT_GUI_ATHENA /* Hiding menus doesn't work for Athena, it can cause a crash. */ gui_mch_menu_grey(menu, grey); #else /* Never hide a toplevel menu, it may make the menubar resize or * disappear. Same problem for ToolBar items. */ if (vim_strchr(p_go, GO_GREY) != NULL || menu->parent == NULL # ifdef FEAT_TOOLBAR || menu_is_toolbar(menu->parent->name) # endif ) gui_mch_menu_grey(menu, grey); else gui_mch_menu_hidden(menu, grey); #endif gui_update_menus_recurse(menu->children, mode); menu = menu->next; } } /* * Make sure only the valid menu items appear for this mode. If * force_menu_update is not TRUE, then we only do this if the mode has changed * since last time. If "modes" is not 0, then we use these modes instead. */ void gui_update_menus(modes) int modes; { static int prev_mode = -1; int mode = 0; if (modes != 0x0) mode = modes; else { mode = get_menu_mode(); if (mode == MENU_INDEX_INVALID) mode = 0; else mode = (1 << mode); } if (force_menu_update || mode != prev_mode) { gui_update_menus_recurse(root_menu, mode); gui_mch_draw_menubar(); prev_mode = mode; force_menu_update = FALSE; #ifdef FEAT_GUI_W32 /* This can leave a tearoff as active window - make sure we * have the focus <negri>*/ gui_mch_activate_window(); #endif } } #if defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_MOTIF) \ || defined(FEAT_GUI_GTK) || defined(FEAT_GUI_PHOTON) || defined(PROTO) /* * Check if a key is used as a mnemonic for a toplevel menu. * Case of the key is ignored. */ int gui_is_menu_shortcut(key) int key; { vimmenu_T *menu; if (key < 256) key = TOLOWER_LOC(key); for (menu = root_menu; menu != NULL; menu = menu->next) if (menu->mnemonic == key || (menu->mnemonic < 256 && TOLOWER_LOC(menu->mnemonic) == key)) return TRUE; return FALSE; } #endif /* * Display the Special "PopUp" menu as a pop-up at the current mouse * position. The "PopUpn" menu is for Normal mode, "PopUpi" for Insert mode, * etc. */ void gui_show_popupmenu() { vimmenu_T *menu; int mode; mode = get_menu_mode(); if (mode == MENU_INDEX_INVALID) return; mode = menu_mode_chars[mode]; #ifdef FEAT_AUTOCMD { char_u ename[2]; ename[0] = mode; ename[1] = NUL; apply_autocmds(EVENT_MENUPOPUP, ename, NULL, FALSE, curbuf); } #endif for (menu = root_menu; menu != NULL; menu = menu->next) if (STRNCMP("PopUp", menu->name, 5) == 0 && menu->name[5] == mode) break; /* Only show a popup when it is defined and has entries */ if (menu != NULL && menu->children != NULL) gui_mch_show_popupmenu(menu); } #endif /* FEAT_GUI */ #if (defined(FEAT_GUI_W32) && defined(FEAT_TEAROFF)) || defined(PROTO) /* * Deal with tearoff items that are added like a menu item. * Currently only for Win32 GUI. Others may follow later. */ void gui_mch_toggle_tearoffs(int enable) { int pri_tab[MENUDEPTH + 1]; int i; if (enable) { for (i = 0; i < MENUDEPTH; ++i) pri_tab[i] = 500; pri_tab[MENUDEPTH] = -1; gui_create_tearoffs_recurse(root_menu, (char_u *)"", pri_tab, 0); } else gui_destroy_tearoffs_recurse(root_menu); s_tearoffs = enable; } /* * Recursively add tearoff items */ static void gui_create_tearoffs_recurse(menu, pname, pri_tab, pri_idx) vimmenu_T *menu; const char_u *pname; int *pri_tab; int pri_idx; { char_u *newpname = NULL; int len; char_u *s; char_u *d; if (pri_tab[pri_idx + 1] != -1) ++pri_idx; while (menu != NULL) { if (menu->children != NULL && menu_is_menubar(menu->name)) { /* Add the menu name to the menu path. Insert a backslash before * dots (it's used to separate menu names). */ len = (int)STRLEN(pname) + (int)STRLEN(menu->name); for (s = menu->name; *s; ++s) if (*s == '.' || *s == '\\') ++len; newpname = alloc(len + TEAR_LEN + 2); if (newpname != NULL) { STRCPY(newpname, pname); d = newpname + STRLEN(newpname); for (s = menu->name; *s; ++s) { if (*s == '.' || *s == '\\') *d++ = '\\'; *d++ = *s; } *d = NUL; /* check if tearoff already exists */ if (STRCMP(menu->children->name, TEAR_STRING) != 0) { gui_add_tearoff(newpname, pri_tab, pri_idx - 1); *d = NUL; /* remove TEAR_STRING */ } STRCAT(newpname, "."); gui_create_tearoffs_recurse(menu->children, newpname, pri_tab, pri_idx); vim_free(newpname); } } menu = menu->next; } } /* * Add tear-off menu item for a submenu. * "tearpath" is the menu path, and must have room to add TEAR_STRING. */ static void gui_add_tearoff(tearpath, pri_tab, pri_idx) char_u *tearpath; int *pri_tab; int pri_idx; { char_u *tbuf; int t; vimmenu_T menuarg; tbuf = alloc(5 + (unsigned int)STRLEN(tearpath)); if (tbuf != NULL) { tbuf[0] = K_SPECIAL; tbuf[1] = K_SECOND(K_TEAROFF); tbuf[2] = K_THIRD(K_TEAROFF); STRCPY(tbuf + 3, tearpath); STRCAT(tbuf + 3, "\r"); STRCAT(tearpath, "."); STRCAT(tearpath, TEAR_STRING); /* Priority of tear-off is always 1 */ t = pri_tab[pri_idx + 1]; pri_tab[pri_idx + 1] = 1; #ifdef FEAT_TOOLBAR menuarg.iconfile = NULL; menuarg.iconidx = -1; menuarg.icon_builtin = FALSE; #endif menuarg.noremap[0] = REMAP_NONE; menuarg.silent[0] = TRUE; menuarg.modes = MENU_ALL_MODES; add_menu_path(tearpath, &menuarg, pri_tab, tbuf, FALSE); menuarg.modes = MENU_TIP_MODE; add_menu_path(tearpath, &menuarg, pri_tab, (char_u *)_("Tear off this menu"), FALSE); pri_tab[pri_idx + 1] = t; vim_free(tbuf); } } /* * Recursively destroy tearoff items */ static void gui_destroy_tearoffs_recurse(menu) vimmenu_T *menu; { while (menu) { if (menu->children) { /* check if tearoff exists */ if (STRCMP(menu->children->name, TEAR_STRING) == 0) { /* Disconnect the item and free the memory */ free_menu(&menu->children); } if (menu->children != NULL) /* if not the last one */ gui_destroy_tearoffs_recurse(menu->children); } menu = menu->next; } } #endif /* FEAT_GUI_W32 && FEAT_TEAROFF */ /* * Given a menu descriptor, e.g. "File.New", find it in the menu hierarchy and * execute it. */ void ex_emenu(eap) exarg_T *eap; { vimmenu_T *menu; char_u *name; char_u *saved_name; char_u *p; int idx; char_u *mode; saved_name = vim_strsave(eap->arg); if (saved_name == NULL) return; menu = root_menu; name = saved_name; while (*name) { /* Find in the menu hierarchy */ p = menu_name_skip(name); while (menu != NULL) { if (menu_name_equal(name, menu)) { if (*p == NUL && menu->children != NULL) { EMSG(_("E333: Menu path must lead to a menu item")); menu = NULL; } else if (*p != NUL && menu->children == NULL) { EMSG(_(e_notsubmenu)); menu = NULL; } break; } menu = menu->next; } if (menu == NULL || *p == NUL) break; menu = menu->children; name = p; } vim_free(saved_name); if (menu == NULL) { EMSG2(_("E334: Menu not found: %s"), eap->arg); return; } /* Found the menu, so execute. * Use the Insert mode entry when returning to Insert mode. */ if (restart_edit #ifdef FEAT_EVAL && !current_SID #endif ) { mode = (char_u *)"Insert"; idx = MENU_INDEX_INSERT; } else if (eap->addr_count) { pos_T tpos; mode = (char_u *)"Visual"; idx = MENU_INDEX_VISUAL; /* GEDDES: This is not perfect - but it is a * quick way of detecting whether we are doing this from a * selection - see if the range matches up with the visual * select start and end. */ if ((curbuf->b_visual.vi_start.lnum == eap->line1) && (curbuf->b_visual.vi_end.lnum) == eap->line2) { /* Set it up for visual mode - equivalent to gv. */ VIsual_mode = curbuf->b_visual.vi_mode; tpos = curbuf->b_visual.vi_end; curwin->w_cursor = curbuf->b_visual.vi_start; curwin->w_curswant = curbuf->b_visual.vi_curswant; } else { /* Set it up for line-wise visual mode */ VIsual_mode = 'V'; curwin->w_cursor.lnum = eap->line1; curwin->w_cursor.col = 1; tpos.lnum = eap->line2; tpos.col = MAXCOL; #ifdef FEAT_VIRTUALEDIT tpos.coladd = 0; #endif } /* Activate visual mode */ VIsual_active = TRUE; VIsual_reselect = TRUE; check_cursor(); VIsual = curwin->w_cursor; curwin->w_cursor = tpos; check_cursor(); /* Adjust the cursor to make sure it is in the correct pos * for exclusive mode */ if (*p_sel == 'e' && gchar_cursor() != NUL) ++curwin->w_cursor.col; } else { mode = (char_u *)"Normal"; idx = MENU_INDEX_NORMAL; } if (idx != MENU_INDEX_INVALID && menu->strings[idx] != NULL) { /* When executing a script or function execute the commands right now. * Otherwise put them in the typeahead buffer. */ #ifdef FEAT_EVAL if (current_SID != 0) exec_normal_cmd(menu->strings[idx], menu->noremap[idx], menu->silent[idx]); else #endif ins_typebuf(menu->strings[idx], menu->noremap[idx], 0, TRUE, menu->silent[idx]); } else EMSG2(_("E335: Menu not defined for %s mode"), mode); } #if defined(FEAT_GUI_MSWIN) \ || (defined(FEAT_GUI_GTK) && defined(FEAT_MENU)) \ || defined(FEAT_BEVAL_TIP) || defined(PROTO) /* * Given a menu descriptor, e.g. "File.New", find it in the menu hierarchy. */ vimmenu_T * gui_find_menu(path_name) char_u *path_name; { vimmenu_T *menu = NULL; char_u *name; char_u *saved_name; char_u *p; menu = root_menu; saved_name = vim_strsave(path_name); if (saved_name == NULL) return NULL; name = saved_name; while (*name) { /* find the end of one dot-separated name and put a NUL at the dot */ p = menu_name_skip(name); while (menu != NULL) { if (menu_name_equal(name, menu)) { if (menu->children == NULL) { /* found a menu item instead of a sub-menu */ if (*p == NUL) EMSG(_("E336: Menu path must lead to a sub-menu")); else EMSG(_(e_notsubmenu)); menu = NULL; goto theend; } if (*p == NUL) /* found a full match */ goto theend; break; } menu = menu->next; } if (menu == NULL) /* didn't find it */ break; /* Found a match, search the sub-menu. */ menu = menu->children; name = p; } if (menu == NULL) EMSG(_("E337: Menu not found - check menu names")); theend: vim_free(saved_name); return menu; } #endif #ifdef FEAT_MULTI_LANG /* * Translation of menu names. Just a simple lookup table. */ typedef struct { char_u *from; /* English name */ char_u *from_noamp; /* same, without '&' */ char_u *to; /* translated name */ } menutrans_T; static garray_T menutrans_ga = {0, 0, 0, 0, NULL}; #endif /* * ":menutrans". * This function is also defined without the +multi_lang feature, in which * case the commands are ignored. */ void ex_menutranslate(eap) exarg_T *eap UNUSED; { #ifdef FEAT_MULTI_LANG char_u *arg = eap->arg; menutrans_T *tp; int i; char_u *from, *from_noamp, *to; if (menutrans_ga.ga_itemsize == 0) ga_init2(&menutrans_ga, (int)sizeof(menutrans_T), 5); /* * ":menutrans clear": clear all translations. */ if (STRNCMP(arg, "clear", 5) == 0 && ends_excmd(*skipwhite(arg + 5))) { tp = (menutrans_T *)menutrans_ga.ga_data; for (i = 0; i < menutrans_ga.ga_len; ++i) { vim_free(tp[i].from); vim_free(tp[i].from_noamp); vim_free(tp[i].to); } ga_clear(&menutrans_ga); # ifdef FEAT_EVAL /* Delete all "menutrans_" global variables. */ del_menutrans_vars(); # endif } else { /* ":menutrans from to": add translation */ from = arg; arg = menu_skip_part(arg); to = skipwhite(arg); *arg = NUL; arg = menu_skip_part(to); if (arg == to) EMSG(_(e_invarg)); else { if (ga_grow(&menutrans_ga, 1) == OK) { tp = (menutrans_T *)menutrans_ga.ga_data; from = vim_strsave(from); if (from != NULL) { from_noamp = menu_text(from, NULL, NULL); to = vim_strnsave(to, (int)(arg - to)); if (from_noamp != NULL && to != NULL) { menu_translate_tab_and_shift(from); menu_translate_tab_and_shift(to); menu_unescape_name(from); menu_unescape_name(to); tp[menutrans_ga.ga_len].from = from; tp[menutrans_ga.ga_len].from_noamp = from_noamp; tp[menutrans_ga.ga_len].to = to; ++menutrans_ga.ga_len; } else { vim_free(from); vim_free(from_noamp); vim_free(to); } } } } } #endif } #if defined(FEAT_MULTI_LANG) || defined(FEAT_TOOLBAR) /* * Find the character just after one part of a menu name. */ static char_u * menu_skip_part(p) char_u *p; { while (*p != NUL && *p != '.' && !vim_iswhite(*p)) { if ((*p == '\\' || *p == Ctrl_V) && p[1] != NUL) ++p; ++p; } return p; } #endif #ifdef FEAT_MULTI_LANG /* * Lookup part of a menu name in the translations. * Return a pointer to the translation or NULL if not found. */ static char_u * menutrans_lookup(name, len) char_u *name; int len; { menutrans_T *tp = (menutrans_T *)menutrans_ga.ga_data; int i; char_u *dname; for (i = 0; i < menutrans_ga.ga_len; ++i) if (STRNCMP(name, tp[i].from, len) == 0 && tp[i].from[len] == NUL) return tp[i].to; /* Now try again while ignoring '&' characters. */ i = name[len]; name[len] = NUL; dname = menu_text(name, NULL, NULL); name[len] = i; if (dname != NULL) { for (i = 0; i < menutrans_ga.ga_len; ++i) if (STRCMP(dname, tp[i].from_noamp) == 0) { vim_free(dname); return tp[i].to; } vim_free(dname); } return NULL; } /* * Unescape the name in the translate dictionary table. */ static void menu_unescape_name(name) char_u *name; { char_u *p; for (p = name; *p && *p != '.'; mb_ptr_adv(p)) if (*p == '\\') STRMOVE(p, p + 1); } #endif /* FEAT_MULTI_LANG */ /* * Isolate the menu name. * Skip the menu name, and translate <Tab> into a real TAB. */ static char_u * menu_translate_tab_and_shift(arg_start) char_u *arg_start; { char_u *arg = arg_start; while (*arg && !vim_iswhite(*arg)) { if ((*arg == '\\' || *arg == Ctrl_V) && arg[1] != NUL) arg++; else if (STRNICMP(arg, "<TAB>", 5) == 0) { *arg = TAB; STRMOVE(arg + 1, arg + 5); } arg++; } if (*arg != NUL) *arg++ = NUL; arg = skipwhite(arg); return arg; } #endif /* FEAT_MENU */
zyz2011-vim
src/menu.c
C
gpl2
58,718
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * undo.c: multi level undo facility * * The saved lines are stored in a list of lists (one for each buffer): * * b_u_oldhead------------------------------------------------+ * | * V * +--------------+ +--------------+ +--------------+ * b_u_newhead--->| u_header | | u_header | | u_header | * | uh_next------>| uh_next------>| uh_next---->NULL * NULL<--------uh_prev |<---------uh_prev |<---------uh_prev | * | uh_entry | | uh_entry | | uh_entry | * +--------|-----+ +--------|-----+ +--------|-----+ * | | | * V V V * +--------------+ +--------------+ +--------------+ * | u_entry | | u_entry | | u_entry | * | ue_next | | ue_next | | ue_next | * +--------|-----+ +--------|-----+ +--------|-----+ * | | | * V V V * +--------------+ NULL NULL * | u_entry | * | ue_next | * +--------|-----+ * | * V * etc. * * Each u_entry list contains the information for one undo or redo. * curbuf->b_u_curhead points to the header of the last undo (the next redo), * or is NULL if nothing has been undone (end of the branch). * * For keeping alternate undo/redo branches the uh_alt field is used. Thus at * each point in the list a branch may appear for an alternate to redo. The * uh_seq field is numbered sequentially to be able to find a newer or older * branch. * * +---------------+ +---------------+ * b_u_oldhead --->| u_header | | u_header | * | uh_alt_next ---->| uh_alt_next ----> NULL * NULL <----- uh_alt_prev |<------ uh_alt_prev | * | uh_prev | | uh_prev | * +-----|---------+ +-----|---------+ * | | * V V * +---------------+ +---------------+ * | u_header | | u_header | * | uh_alt_next | | uh_alt_next | * b_u_newhead --->| uh_alt_prev | | uh_alt_prev | * | uh_prev | | uh_prev | * +-----|---------+ +-----|---------+ * | | * V V * NULL +---------------+ +---------------+ * | u_header | | u_header | * | uh_alt_next ---->| uh_alt_next | * | uh_alt_prev |<------ uh_alt_prev | * | uh_prev | | uh_prev | * +-----|---------+ +-----|---------+ * | | * etc. etc. * * * All data is allocated and will all be freed when the buffer is unloaded. */ /* Uncomment the next line for including the u_check() function. This warns * for errors in the debug information. */ /* #define U_DEBUG 1 */ #define UH_MAGIC 0x18dade /* value for uh_magic when in use */ #define UE_MAGIC 0xabc123 /* value for ue_magic when in use */ #include "vim.h" static void u_unch_branch __ARGS((u_header_T *uhp)); static u_entry_T *u_get_headentry __ARGS((void)); static void u_getbot __ARGS((void)); static void u_doit __ARGS((int count)); static void u_undoredo __ARGS((int undo)); static void u_undo_end __ARGS((int did_undo, int absolute)); static void u_add_time __ARGS((char_u *buf, size_t buflen, time_t tt)); static void u_freeheader __ARGS((buf_T *buf, u_header_T *uhp, u_header_T **uhpp)); static void u_freebranch __ARGS((buf_T *buf, u_header_T *uhp, u_header_T **uhpp)); static void u_freeentries __ARGS((buf_T *buf, u_header_T *uhp, u_header_T **uhpp)); static void u_freeentry __ARGS((u_entry_T *, long)); #ifdef FEAT_PERSISTENT_UNDO static void corruption_error __ARGS((char *mesg, char_u *file_name)); static void u_free_uhp __ARGS((u_header_T *uhp)); static size_t fwrite_crypt __ARGS((buf_T *buf UNUSED, char_u *ptr, size_t len, FILE *fp)); static char_u *read_string_decrypt __ARGS((buf_T *buf UNUSED, FILE *fd, int len)); static int serialize_header __ARGS((FILE *fp, buf_T *buf, char_u *hash)); static int serialize_uhp __ARGS((FILE *fp, buf_T *buf, u_header_T *uhp)); static u_header_T *unserialize_uhp __ARGS((FILE *fp, char_u *file_name)); static int serialize_uep __ARGS((FILE *fp, buf_T *buf, u_entry_T *uep)); static u_entry_T *unserialize_uep __ARGS((FILE *fp, int *error, char_u *file_name)); static void serialize_pos __ARGS((pos_T pos, FILE *fp)); static void unserialize_pos __ARGS((pos_T *pos, FILE *fp)); static void serialize_visualinfo __ARGS((visualinfo_T *info, FILE *fp)); static void unserialize_visualinfo __ARGS((visualinfo_T *info, FILE *fp)); static void put_header_ptr __ARGS((FILE *fp, u_header_T *uhp)); #endif #define U_ALLOC_LINE(size) lalloc((long_u)(size), FALSE) static char_u *u_save_line __ARGS((linenr_T)); /* used in undo_end() to report number of added and deleted lines */ static long u_newcount, u_oldcount; /* * When 'u' flag included in 'cpoptions', we behave like vi. Need to remember * the action that "u" should do. */ static int undo_undoes = FALSE; static int lastmark = 0; #if defined(U_DEBUG) || defined(PROTO) /* * Check the undo structures for being valid. Print a warning when something * looks wrong. */ static int seen_b_u_curhead; static int seen_b_u_newhead; static int header_count; static void u_check_tree(u_header_T *uhp, u_header_T *exp_uh_next, u_header_T *exp_uh_alt_prev) { u_entry_T *uep; if (uhp == NULL) return; ++header_count; if (uhp == curbuf->b_u_curhead && ++seen_b_u_curhead > 1) { EMSG("b_u_curhead found twice (looping?)"); return; } if (uhp == curbuf->b_u_newhead && ++seen_b_u_newhead > 1) { EMSG("b_u_newhead found twice (looping?)"); return; } if (uhp->uh_magic != UH_MAGIC) EMSG("uh_magic wrong (may be using freed memory)"); else { /* Check pointers back are correct. */ if (uhp->uh_next.ptr != exp_uh_next) { EMSG("uh_next wrong"); smsg((char_u *)"expected: 0x%x, actual: 0x%x", exp_uh_next, uhp->uh_next.ptr); } if (uhp->uh_alt_prev.ptr != exp_uh_alt_prev) { EMSG("uh_alt_prev wrong"); smsg((char_u *)"expected: 0x%x, actual: 0x%x", exp_uh_alt_prev, uhp->uh_alt_prev.ptr); } /* Check the undo tree at this header. */ for (uep = uhp->uh_entry; uep != NULL; uep = uep->ue_next) { if (uep->ue_magic != UE_MAGIC) { EMSG("ue_magic wrong (may be using freed memory)"); break; } } /* Check the next alt tree. */ u_check_tree(uhp->uh_alt_next.ptr, uhp->uh_next.ptr, uhp); /* Check the next header in this branch. */ u_check_tree(uhp->uh_prev.ptr, uhp, NULL); } } static void u_check(int newhead_may_be_NULL) { seen_b_u_newhead = 0; seen_b_u_curhead = 0; header_count = 0; u_check_tree(curbuf->b_u_oldhead, NULL, NULL); if (seen_b_u_newhead == 0 && curbuf->b_u_oldhead != NULL && !(newhead_may_be_NULL && curbuf->b_u_newhead == NULL)) EMSGN("b_u_newhead invalid: 0x%x", curbuf->b_u_newhead); if (curbuf->b_u_curhead != NULL && seen_b_u_curhead == 0) EMSGN("b_u_curhead invalid: 0x%x", curbuf->b_u_curhead); if (header_count != curbuf->b_u_numhead) { EMSG("b_u_numhead invalid"); smsg((char_u *)"expected: %ld, actual: %ld", (long)header_count, (long)curbuf->b_u_numhead); } } #endif /* * Save the current line for both the "u" and "U" command. * Returns OK or FAIL. */ int u_save_cursor() { return (u_save((linenr_T)(curwin->w_cursor.lnum - 1), (linenr_T)(curwin->w_cursor.lnum + 1))); } /* * Save the lines between "top" and "bot" for both the "u" and "U" command. * "top" may be 0 and bot may be curbuf->b_ml.ml_line_count + 1. * Careful: may trigger autocommands that reload the buffer. * Returns FAIL when lines could not be saved, OK otherwise. */ int u_save(top, bot) linenr_T top, bot; { if (undo_off) return OK; if (top > curbuf->b_ml.ml_line_count || top >= bot || bot > curbuf->b_ml.ml_line_count + 1) return FALSE; /* rely on caller to do error messages */ if (top + 2 == bot) u_saveline((linenr_T)(top + 1)); return (u_savecommon(top, bot, (linenr_T)0, FALSE)); } /* * Save the line "lnum" (used by ":s" and "~" command). * The line is replaced, so the new bottom line is lnum + 1. * Careful: may trigger autocommands that reload the buffer. * Returns FAIL when lines could not be saved, OK otherwise. */ int u_savesub(lnum) linenr_T lnum; { if (undo_off) return OK; return (u_savecommon(lnum - 1, lnum + 1, lnum + 1, FALSE)); } /* * A new line is inserted before line "lnum" (used by :s command). * The line is inserted, so the new bottom line is lnum + 1. * Careful: may trigger autocommands that reload the buffer. * Returns FAIL when lines could not be saved, OK otherwise. */ int u_inssub(lnum) linenr_T lnum; { if (undo_off) return OK; return (u_savecommon(lnum - 1, lnum, lnum + 1, FALSE)); } /* * Save the lines "lnum" - "lnum" + nlines (used by delete command). * The lines are deleted, so the new bottom line is lnum, unless the buffer * becomes empty. * Careful: may trigger autocommands that reload the buffer. * Returns FAIL when lines could not be saved, OK otherwise. */ int u_savedel(lnum, nlines) linenr_T lnum; long nlines; { if (undo_off) return OK; return (u_savecommon(lnum - 1, lnum + nlines, nlines == curbuf->b_ml.ml_line_count ? 2 : lnum, FALSE)); } /* * Return TRUE when undo is allowed. Otherwise give an error message and * return FALSE. */ int undo_allowed() { /* Don't allow changes when 'modifiable' is off. */ if (!curbuf->b_p_ma) { EMSG(_(e_modifiable)); return FALSE; } #ifdef HAVE_SANDBOX /* In the sandbox it's not allowed to change the text. */ if (sandbox != 0) { EMSG(_(e_sandbox)); return FALSE; } #endif /* Don't allow changes in the buffer while editing the cmdline. The * caller of getcmdline() may get confused. */ if (textlock != 0) { EMSG(_(e_secure)); return FALSE; } return TRUE; } /* * Common code for various ways to save text before a change. * "top" is the line above the first changed line. * "bot" is the line below the last changed line. * "newbot" is the new bottom line. Use zero when not known. * "reload" is TRUE when saving for a buffer reload. * Careful: may trigger autocommands that reload the buffer. * Returns FAIL when lines could not be saved, OK otherwise. */ int u_savecommon(top, bot, newbot, reload) linenr_T top, bot; linenr_T newbot; int reload; { linenr_T lnum; long i; u_header_T *uhp; u_header_T *old_curhead; u_entry_T *uep; u_entry_T *prev_uep; long size; if (!reload) { /* When making changes is not allowed return FAIL. It's a crude way * to make all change commands fail. */ if (!undo_allowed()) return FAIL; #ifdef FEAT_NETBEANS_INTG /* * Netbeans defines areas that cannot be modified. Bail out here when * trying to change text in a guarded area. */ if (netbeans_active()) { if (netbeans_is_guarded(top, bot)) { EMSG(_(e_guarded)); return FAIL; } if (curbuf->b_p_ro) { EMSG(_(e_nbreadonly)); return FAIL; } } #endif #ifdef FEAT_AUTOCMD /* * Saving text for undo means we are going to make a change. Give a * warning for a read-only file before making the change, so that the * FileChangedRO event can replace the buffer with a read-write version * (e.g., obtained from a source control system). */ change_warning(0); if (bot > curbuf->b_ml.ml_line_count + 1) { /* This happens when the FileChangedRO autocommand changes the * file in a way it becomes shorter. */ EMSG(_("E834: Line count changed unexpectedly")); return FAIL; } #endif } #ifdef U_DEBUG u_check(FALSE); #endif size = bot - top - 1; /* * If curbuf->b_u_synced == TRUE make a new header. */ if (curbuf->b_u_synced) { #ifdef FEAT_JUMPLIST /* Need to create new entry in b_changelist. */ curbuf->b_new_change = TRUE; #endif if (p_ul >= 0) { /* * Make a new header entry. Do this first so that we don't mess * up the undo info when out of memory. */ uhp = (u_header_T *)U_ALLOC_LINE(sizeof(u_header_T)); if (uhp == NULL) goto nomem; #ifdef U_DEBUG uhp->uh_magic = UH_MAGIC; #endif } else uhp = NULL; /* * If we undid more than we redid, move the entry lists before and * including curbuf->b_u_curhead to an alternate branch. */ old_curhead = curbuf->b_u_curhead; if (old_curhead != NULL) { curbuf->b_u_newhead = old_curhead->uh_next.ptr; curbuf->b_u_curhead = NULL; } /* * free headers to keep the size right */ while (curbuf->b_u_numhead > p_ul && curbuf->b_u_oldhead != NULL) { u_header_T *uhfree = curbuf->b_u_oldhead; if (uhfree == old_curhead) /* Can't reconnect the branch, delete all of it. */ u_freebranch(curbuf, uhfree, &old_curhead); else if (uhfree->uh_alt_next.ptr == NULL) /* There is no branch, only free one header. */ u_freeheader(curbuf, uhfree, &old_curhead); else { /* Free the oldest alternate branch as a whole. */ while (uhfree->uh_alt_next.ptr != NULL) uhfree = uhfree->uh_alt_next.ptr; u_freebranch(curbuf, uhfree, &old_curhead); } #ifdef U_DEBUG u_check(TRUE); #endif } if (uhp == NULL) /* no undo at all */ { if (old_curhead != NULL) u_freebranch(curbuf, old_curhead, NULL); curbuf->b_u_synced = FALSE; return OK; } uhp->uh_prev.ptr = NULL; uhp->uh_next.ptr = curbuf->b_u_newhead; uhp->uh_alt_next.ptr = old_curhead; if (old_curhead != NULL) { uhp->uh_alt_prev.ptr = old_curhead->uh_alt_prev.ptr; if (uhp->uh_alt_prev.ptr != NULL) uhp->uh_alt_prev.ptr->uh_alt_next.ptr = uhp; old_curhead->uh_alt_prev.ptr = uhp; if (curbuf->b_u_oldhead == old_curhead) curbuf->b_u_oldhead = uhp; } else uhp->uh_alt_prev.ptr = NULL; if (curbuf->b_u_newhead != NULL) curbuf->b_u_newhead->uh_prev.ptr = uhp; uhp->uh_seq = ++curbuf->b_u_seq_last; curbuf->b_u_seq_cur = uhp->uh_seq; uhp->uh_time = time(NULL); uhp->uh_save_nr = 0; curbuf->b_u_time_cur = uhp->uh_time + 1; uhp->uh_walk = 0; uhp->uh_entry = NULL; uhp->uh_getbot_entry = NULL; uhp->uh_cursor = curwin->w_cursor; /* save cursor pos. for undo */ #ifdef FEAT_VIRTUALEDIT if (virtual_active() && curwin->w_cursor.coladd > 0) uhp->uh_cursor_vcol = getviscol(); else uhp->uh_cursor_vcol = -1; #endif /* save changed and buffer empty flag for undo */ uhp->uh_flags = (curbuf->b_changed ? UH_CHANGED : 0) + ((curbuf->b_ml.ml_flags & ML_EMPTY) ? UH_EMPTYBUF : 0); /* save named marks and Visual marks for undo */ mch_memmove(uhp->uh_namedm, curbuf->b_namedm, sizeof(pos_T) * NMARKS); #ifdef FEAT_VISUAL uhp->uh_visual = curbuf->b_visual; #endif curbuf->b_u_newhead = uhp; if (curbuf->b_u_oldhead == NULL) curbuf->b_u_oldhead = uhp; ++curbuf->b_u_numhead; } else { if (p_ul < 0) /* no undo at all */ return OK; /* * When saving a single line, and it has been saved just before, it * doesn't make sense saving it again. Saves a lot of memory when * making lots of changes inside the same line. * This is only possible if the previous change didn't increase or * decrease the number of lines. * Check the ten last changes. More doesn't make sense and takes too * long. */ if (size == 1) { uep = u_get_headentry(); prev_uep = NULL; for (i = 0; i < 10; ++i) { if (uep == NULL) break; /* If lines have been inserted/deleted we give up. * Also when the line was included in a multi-line save. */ if ((curbuf->b_u_newhead->uh_getbot_entry != uep ? (uep->ue_top + uep->ue_size + 1 != (uep->ue_bot == 0 ? curbuf->b_ml.ml_line_count + 1 : uep->ue_bot)) : uep->ue_lcount != curbuf->b_ml.ml_line_count) || (uep->ue_size > 1 && top >= uep->ue_top && top + 2 <= uep->ue_top + uep->ue_size + 1)) break; /* If it's the same line we can skip saving it again. */ if (uep->ue_size == 1 && uep->ue_top == top) { if (i > 0) { /* It's not the last entry: get ue_bot for the last * entry now. Following deleted/inserted lines go to * the re-used entry. */ u_getbot(); curbuf->b_u_synced = FALSE; /* Move the found entry to become the last entry. The * order of undo/redo doesn't matter for the entries * we move it over, since they don't change the line * count and don't include this line. It does matter * for the found entry if the line count is changed by * the executed command. */ prev_uep->ue_next = uep->ue_next; uep->ue_next = curbuf->b_u_newhead->uh_entry; curbuf->b_u_newhead->uh_entry = uep; } /* The executed command may change the line count. */ if (newbot != 0) uep->ue_bot = newbot; else if (bot > curbuf->b_ml.ml_line_count) uep->ue_bot = 0; else { uep->ue_lcount = curbuf->b_ml.ml_line_count; curbuf->b_u_newhead->uh_getbot_entry = uep; } return OK; } prev_uep = uep; uep = uep->ue_next; } } /* find line number for ue_bot for previous u_save() */ u_getbot(); } #if !defined(UNIX) && !defined(DJGPP) && !defined(WIN32) && !defined(__EMX__) /* * With Amiga and MSDOS 16 bit we can't handle big undo's, because * then u_alloc_line would have to allocate a block larger than 32K */ if (size >= 8000) goto nomem; #endif /* * add lines in front of entry list */ uep = (u_entry_T *)U_ALLOC_LINE(sizeof(u_entry_T)); if (uep == NULL) goto nomem; vim_memset(uep, 0, sizeof(u_entry_T)); #ifdef U_DEBUG uep->ue_magic = UE_MAGIC; #endif uep->ue_size = size; uep->ue_top = top; if (newbot != 0) uep->ue_bot = newbot; /* * Use 0 for ue_bot if bot is below last line. * Otherwise we have to compute ue_bot later. */ else if (bot > curbuf->b_ml.ml_line_count) uep->ue_bot = 0; else { uep->ue_lcount = curbuf->b_ml.ml_line_count; curbuf->b_u_newhead->uh_getbot_entry = uep; } if (size > 0) { if ((uep->ue_array = (char_u **)U_ALLOC_LINE( sizeof(char_u *) * size)) == NULL) { u_freeentry(uep, 0L); goto nomem; } for (i = 0, lnum = top + 1; i < size; ++i) { fast_breakcheck(); if (got_int) { u_freeentry(uep, i); return FAIL; } if ((uep->ue_array[i] = u_save_line(lnum++)) == NULL) { u_freeentry(uep, i); goto nomem; } } } else uep->ue_array = NULL; uep->ue_next = curbuf->b_u_newhead->uh_entry; curbuf->b_u_newhead->uh_entry = uep; curbuf->b_u_synced = FALSE; undo_undoes = FALSE; #ifdef U_DEBUG u_check(FALSE); #endif return OK; nomem: msg_silent = 0; /* must display the prompt */ if (ask_yesno((char_u *)_("No undo possible; continue anyway"), TRUE) == 'y') { undo_off = TRUE; /* will be reset when character typed */ return OK; } do_outofmem_msg((long_u)0); return FAIL; } #if defined(FEAT_PERSISTENT_UNDO) || defined(PROTO) # define UF_START_MAGIC "Vim\237UnDo\345" /* magic at start of undofile */ # define UF_START_MAGIC_LEN 9 # define UF_HEADER_MAGIC 0x5fd0 /* magic at start of header */ # define UF_HEADER_END_MAGIC 0xe7aa /* magic after last header */ # define UF_ENTRY_MAGIC 0xf518 /* magic at start of entry */ # define UF_ENTRY_END_MAGIC 0x3581 /* magic after last entry */ # define UF_VERSION 2 /* 2-byte undofile version number */ # define UF_VERSION_CRYPT 0x8002 /* idem, encrypted */ /* extra fields for header */ # define UF_LAST_SAVE_NR 1 /* extra fields for uhp */ # define UHP_SAVE_NR 1 static char_u e_not_open[] = N_("E828: Cannot open undo file for writing: %s"); /* * Compute the hash for the current buffer text into hash[UNDO_HASH_SIZE]. */ void u_compute_hash(hash) char_u *hash; { context_sha256_T ctx; linenr_T lnum; char_u *p; sha256_start(&ctx); for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum) { p = ml_get(lnum); sha256_update(&ctx, p, (UINT32_T)(STRLEN(p) + 1)); } sha256_finish(&ctx, hash); } /* * Return an allocated string of the full path of the target undofile. * When "reading" is TRUE find the file to read, go over all directories in * 'undodir'. * When "reading" is FALSE use the first name where the directory exists. * Returns NULL when there is no place to write or no file to read. */ char_u * u_get_undo_file_name(buf_ffname, reading) char_u *buf_ffname; int reading; { char_u *dirp; char_u dir_name[IOSIZE + 1]; char_u *munged_name = NULL; char_u *undo_file_name = NULL; int dir_len; char_u *p; struct stat st; char_u *ffname = buf_ffname; #ifdef HAVE_READLINK char_u fname_buf[MAXPATHL]; #endif if (ffname == NULL) return NULL; #ifdef HAVE_READLINK /* Expand symlink in the file name, so that we put the undo file with the * actual file instead of with the symlink. */ if (resolve_symlink(ffname, fname_buf) == OK) ffname = fname_buf; #endif /* Loop over 'undodir'. When reading find the first file that exists. * When not reading use the first directory that exists or ".". */ dirp = p_udir; while (*dirp != NUL) { dir_len = copy_option_part(&dirp, dir_name, IOSIZE, ","); if (dir_len == 1 && dir_name[0] == '.') { /* Use same directory as the ffname, * "dir/name" -> "dir/.name.un~" */ undo_file_name = vim_strnsave(ffname, (int)(STRLEN(ffname) + 5)); if (undo_file_name == NULL) break; p = gettail(undo_file_name); mch_memmove(p + 1, p, STRLEN(p) + 1); *p = '.'; STRCAT(p, ".un~"); } else { dir_name[dir_len] = NUL; if (mch_isdir(dir_name)) { if (munged_name == NULL) { munged_name = vim_strsave(ffname); if (munged_name == NULL) return NULL; for (p = munged_name; *p != NUL; mb_ptr_adv(p)) if (vim_ispathsep(*p)) *p = '%'; } undo_file_name = concat_fnames(dir_name, munged_name, TRUE); } } /* When reading check if the file exists. */ if (undo_file_name != NULL && (!reading || mch_stat((char *)undo_file_name, &st) >= 0)) break; vim_free(undo_file_name); undo_file_name = NULL; } vim_free(munged_name); return undo_file_name; } static void corruption_error(mesg, file_name) char *mesg; char_u *file_name; { EMSG3(_("E825: Corrupted undo file (%s): %s"), mesg, file_name); } static void u_free_uhp(uhp) u_header_T *uhp; { u_entry_T *nuep; u_entry_T *uep; uep = uhp->uh_entry; while (uep != NULL) { nuep = uep->ue_next; u_freeentry(uep, uep->ue_size); uep = nuep; } vim_free(uhp); } /* * Like fwrite() but crypt the bytes when 'key' is set. * Returns 1 if successful. */ static size_t fwrite_crypt(buf, ptr, len, fp) buf_T *buf UNUSED; char_u *ptr; size_t len; FILE *fp; { #ifdef FEAT_CRYPT char_u *copy; char_u small_buf[100]; size_t i; if (*buf->b_p_key == NUL) return fwrite(ptr, len, (size_t)1, fp); if (len < 100) copy = small_buf; /* no malloc()/free() for short strings */ else { copy = lalloc(len, FALSE); if (copy == NULL) return 0; } crypt_encode(ptr, len, copy); i = fwrite(copy, len, (size_t)1, fp); if (copy != small_buf) vim_free(copy); return i; #else return fwrite(ptr, len, (size_t)1, fp); #endif } /* * Read a string of length "len" from "fd". * When 'key' is set decrypt the bytes. */ static char_u * read_string_decrypt(buf, fd, len) buf_T *buf UNUSED; FILE *fd; int len; { char_u *ptr; ptr = read_string(fd, len); #ifdef FEAT_CRYPT if (ptr != NULL && *buf->b_p_key != NUL) crypt_decode(ptr, len); #endif return ptr; } static int serialize_header(fp, buf, hash) FILE *fp; buf_T *buf; char_u *hash; { int len; /* Start writing, first the magic marker and undo info version. */ if (fwrite(UF_START_MAGIC, (size_t)UF_START_MAGIC_LEN, (size_t)1, fp) != 1) return FAIL; /* If the buffer is encrypted then all text bytes following will be * encrypted. Numbers and other info is not crypted. */ #ifdef FEAT_CRYPT if (*buf->b_p_key != NUL) { char_u *header; int header_len; put_bytes(fp, (long_u)UF_VERSION_CRYPT, 2); header = prepare_crypt_write(buf, &header_len); if (header == NULL) return FAIL; len = (int)fwrite(header, (size_t)header_len, (size_t)1, fp); vim_free(header); if (len != 1) { crypt_pop_state(); return FAIL; } } else #endif put_bytes(fp, (long_u)UF_VERSION, 2); /* Write a hash of the buffer text, so that we can verify it is still the * same when reading the buffer text. */ if (fwrite(hash, (size_t)UNDO_HASH_SIZE, (size_t)1, fp) != 1) return FAIL; /* buffer-specific data */ put_bytes(fp, (long_u)buf->b_ml.ml_line_count, 4); len = buf->b_u_line_ptr != NULL ? (int)STRLEN(buf->b_u_line_ptr) : 0; put_bytes(fp, (long_u)len, 4); if (len > 0 && fwrite_crypt(buf, buf->b_u_line_ptr, (size_t)len, fp) != 1) return FAIL; put_bytes(fp, (long_u)buf->b_u_line_lnum, 4); put_bytes(fp, (long_u)buf->b_u_line_colnr, 4); /* Undo structures header data */ put_header_ptr(fp, buf->b_u_oldhead); put_header_ptr(fp, buf->b_u_newhead); put_header_ptr(fp, buf->b_u_curhead); put_bytes(fp, (long_u)buf->b_u_numhead, 4); put_bytes(fp, (long_u)buf->b_u_seq_last, 4); put_bytes(fp, (long_u)buf->b_u_seq_cur, 4); put_time(fp, buf->b_u_time_cur); /* Optional fields. */ putc(4, fp); putc(UF_LAST_SAVE_NR, fp); put_bytes(fp, (long_u)buf->b_u_save_nr_last, 4); putc(0, fp); /* end marker */ return OK; } static int serialize_uhp(fp, buf, uhp) FILE *fp; buf_T *buf; u_header_T *uhp; { int i; u_entry_T *uep; if (put_bytes(fp, (long_u)UF_HEADER_MAGIC, 2) == FAIL) return FAIL; put_header_ptr(fp, uhp->uh_next.ptr); put_header_ptr(fp, uhp->uh_prev.ptr); put_header_ptr(fp, uhp->uh_alt_next.ptr); put_header_ptr(fp, uhp->uh_alt_prev.ptr); put_bytes(fp, uhp->uh_seq, 4); serialize_pos(uhp->uh_cursor, fp); #ifdef FEAT_VIRTUALEDIT put_bytes(fp, (long_u)uhp->uh_cursor_vcol, 4); #else put_bytes(fp, (long_u)0, 4); #endif put_bytes(fp, (long_u)uhp->uh_flags, 2); /* Assume NMARKS will stay the same. */ for (i = 0; i < NMARKS; ++i) serialize_pos(uhp->uh_namedm[i], fp); #ifdef FEAT_VISUAL serialize_visualinfo(&uhp->uh_visual, fp); #else { visualinfo_T info; memset(&info, 0, sizeof(visualinfo_T)); serialize_visualinfo(&info, fp); } #endif put_time(fp, uhp->uh_time); /* Optional fields. */ putc(4, fp); putc(UHP_SAVE_NR, fp); put_bytes(fp, (long_u)uhp->uh_save_nr, 4); putc(0, fp); /* end marker */ /* Write all the entries. */ for (uep = uhp->uh_entry; uep != NULL; uep = uep->ue_next) { put_bytes(fp, (long_u)UF_ENTRY_MAGIC, 2); if (serialize_uep(fp, buf, uep) == FAIL) return FAIL; } put_bytes(fp, (long_u)UF_ENTRY_END_MAGIC, 2); return OK; } static u_header_T * unserialize_uhp(fp, file_name) FILE *fp; char_u *file_name; { u_header_T *uhp; int i; u_entry_T *uep, *last_uep; int c; int error; uhp = (u_header_T *)U_ALLOC_LINE(sizeof(u_header_T)); if (uhp == NULL) return NULL; vim_memset(uhp, 0, sizeof(u_header_T)); #ifdef U_DEBUG uhp->uh_magic = UH_MAGIC; #endif uhp->uh_next.seq = get4c(fp); uhp->uh_prev.seq = get4c(fp); uhp->uh_alt_next.seq = get4c(fp); uhp->uh_alt_prev.seq = get4c(fp); uhp->uh_seq = get4c(fp); if (uhp->uh_seq <= 0) { corruption_error("uh_seq", file_name); vim_free(uhp); return NULL; } unserialize_pos(&uhp->uh_cursor, fp); #ifdef FEAT_VIRTUALEDIT uhp->uh_cursor_vcol = get4c(fp); #else (void)get4c(fp); #endif uhp->uh_flags = get2c(fp); for (i = 0; i < NMARKS; ++i) unserialize_pos(&uhp->uh_namedm[i], fp); #ifdef FEAT_VISUAL unserialize_visualinfo(&uhp->uh_visual, fp); #else { visualinfo_T info; unserialize_visualinfo(&info, fp); } #endif uhp->uh_time = get8ctime(fp); /* Optional fields. */ for (;;) { int len = getc(fp); int what; if (len == 0) break; what = getc(fp); switch (what) { case UHP_SAVE_NR: uhp->uh_save_nr = get4c(fp); break; default: /* field not supported, skip */ while (--len >= 0) (void)getc(fp); } } /* Unserialize the uep list. */ last_uep = NULL; while ((c = get2c(fp)) == UF_ENTRY_MAGIC) { error = FALSE; uep = unserialize_uep(fp, &error, file_name); if (last_uep == NULL) uhp->uh_entry = uep; else last_uep->ue_next = uep; last_uep = uep; if (uep == NULL || error) { u_free_uhp(uhp); return NULL; } } if (c != UF_ENTRY_END_MAGIC) { corruption_error("entry end", file_name); u_free_uhp(uhp); return NULL; } return uhp; } /* * Serialize "uep" to "fp". */ static int serialize_uep(fp, buf, uep) FILE *fp; buf_T *buf; u_entry_T *uep; { int i; size_t len; put_bytes(fp, (long_u)uep->ue_top, 4); put_bytes(fp, (long_u)uep->ue_bot, 4); put_bytes(fp, (long_u)uep->ue_lcount, 4); put_bytes(fp, (long_u)uep->ue_size, 4); for (i = 0; i < uep->ue_size; ++i) { len = STRLEN(uep->ue_array[i]); if (put_bytes(fp, (long_u)len, 4) == FAIL) return FAIL; if (len > 0 && fwrite_crypt(buf, uep->ue_array[i], len, fp) != 1) return FAIL; } return OK; } static u_entry_T * unserialize_uep(fp, error, file_name) FILE *fp; int *error; char_u *file_name; { int i; u_entry_T *uep; char_u **array; char_u *line; int line_len; uep = (u_entry_T *)U_ALLOC_LINE(sizeof(u_entry_T)); if (uep == NULL) return NULL; vim_memset(uep, 0, sizeof(u_entry_T)); #ifdef U_DEBUG uep->ue_magic = UE_MAGIC; #endif uep->ue_top = get4c(fp); uep->ue_bot = get4c(fp); uep->ue_lcount = get4c(fp); uep->ue_size = get4c(fp); if (uep->ue_size > 0) { array = (char_u **)U_ALLOC_LINE(sizeof(char_u *) * uep->ue_size); if (array == NULL) { *error = TRUE; return uep; } vim_memset(array, 0, sizeof(char_u *) * uep->ue_size); } else array = NULL; uep->ue_array = array; for (i = 0; i < uep->ue_size; ++i) { line_len = get4c(fp); if (line_len >= 0) line = read_string_decrypt(curbuf, fp, line_len); else { line = NULL; corruption_error("line length", file_name); } if (line == NULL) { *error = TRUE; return uep; } array[i] = line; } return uep; } /* * Serialize "pos" to "fp". */ static void serialize_pos(pos, fp) pos_T pos; FILE *fp; { put_bytes(fp, (long_u)pos.lnum, 4); put_bytes(fp, (long_u)pos.col, 4); #ifdef FEAT_VIRTUALEDIT put_bytes(fp, (long_u)pos.coladd, 4); #else put_bytes(fp, (long_u)0, 4); #endif } /* * Unserialize the pos_T at the current position in fp. */ static void unserialize_pos(pos, fp) pos_T *pos; FILE *fp; { pos->lnum = get4c(fp); if (pos->lnum < 0) pos->lnum = 0; pos->col = get4c(fp); if (pos->col < 0) pos->col = 0; #ifdef FEAT_VIRTUALEDIT pos->coladd = get4c(fp); if (pos->coladd < 0) pos->coladd = 0; #else (void)get4c(fp); #endif } /* * Serialize "info" to "fp". */ static void serialize_visualinfo(info, fp) visualinfo_T *info; FILE *fp; { serialize_pos(info->vi_start, fp); serialize_pos(info->vi_end, fp); put_bytes(fp, (long_u)info->vi_mode, 4); put_bytes(fp, (long_u)info->vi_curswant, 4); } /* * Unserialize the visualinfo_T at the current position in fp. */ static void unserialize_visualinfo(info, fp) visualinfo_T *info; FILE *fp; { unserialize_pos(&info->vi_start, fp); unserialize_pos(&info->vi_end, fp); info->vi_mode = get4c(fp); info->vi_curswant = get4c(fp); } /* * Write the pointer to an undo header. Instead of writing the pointer itself * we use the sequence number of the header. This is converted back to * pointers when reading. */ static void put_header_ptr(fp, uhp) FILE *fp; u_header_T *uhp; { put_bytes(fp, (long_u)(uhp != NULL ? uhp->uh_seq : 0), 4); } /* * Write the undo tree in an undo file. * When "name" is not NULL, use it as the name of the undo file. * Otherwise use buf->b_ffname to generate the undo file name. * "buf" must never be null, buf->b_ffname is used to obtain the original file * permissions. * "forceit" is TRUE for ":wundo!", FALSE otherwise. * "hash[UNDO_HASH_SIZE]" must be the hash value of the buffer text. */ void u_write_undo(name, forceit, buf, hash) char_u *name; int forceit; buf_T *buf; char_u *hash; { u_header_T *uhp; char_u *file_name; int mark; #ifdef U_DEBUG int headers_written = 0; #endif int fd; FILE *fp = NULL; int perm; int write_ok = FALSE; #ifdef UNIX int st_old_valid = FALSE; struct stat st_old; struct stat st_new; #endif #ifdef FEAT_CRYPT int do_crypt = FALSE; #endif if (name == NULL) { file_name = u_get_undo_file_name(buf->b_ffname, FALSE); if (file_name == NULL) { if (p_verbose > 0) { verbose_enter(); smsg((char_u *) _("Cannot write undo file in any directory in 'undodir'")); verbose_leave(); } return; } } else file_name = name; /* * Decide about the permission to use for the undo file. If the buffer * has a name use the permission of the original file. Otherwise only * allow the user to access the undo file. */ perm = 0600; if (buf->b_ffname != NULL) { #ifdef UNIX if (mch_stat((char *)buf->b_ffname, &st_old) >= 0) { perm = st_old.st_mode; st_old_valid = TRUE; } #else perm = mch_getperm(buf->b_ffname); if (perm < 0) perm = 0600; #endif } /* strip any s-bit */ perm = perm & 0777; /* If the undo file already exists, verify that it actually is an undo * file, and delete it. */ if (mch_getperm(file_name) >= 0) { if (name == NULL || !forceit) { /* Check we can read it and it's an undo file. */ fd = mch_open((char *)file_name, O_RDONLY|O_EXTRA, 0); if (fd < 0) { if (name != NULL || p_verbose > 0) { if (name == NULL) verbose_enter(); smsg((char_u *) _("Will not overwrite with undo file, cannot read: %s"), file_name); if (name == NULL) verbose_leave(); } goto theend; } else { char_u mbuf[UF_START_MAGIC_LEN]; int len; len = read_eintr(fd, mbuf, UF_START_MAGIC_LEN); close(fd); if (len < UF_START_MAGIC_LEN || memcmp(mbuf, UF_START_MAGIC, UF_START_MAGIC_LEN) != 0) { if (name != NULL || p_verbose > 0) { if (name == NULL) verbose_enter(); smsg((char_u *) _("Will not overwrite, this is not an undo file: %s"), file_name); if (name == NULL) verbose_leave(); } goto theend; } } } mch_remove(file_name); } /* If there is no undo information at all, quit here after deleting any * existing undo file. */ if (buf->b_u_numhead == 0 && buf->b_u_line_ptr == NULL) { if (p_verbose > 0) verb_msg((char_u *)_("Skipping undo file write, nothing to undo")); goto theend; } fd = mch_open((char *)file_name, O_CREAT|O_EXTRA|O_WRONLY|O_EXCL|O_NOFOLLOW, perm); if (fd < 0) { EMSG2(_(e_not_open), file_name); goto theend; } (void)mch_setperm(file_name, perm); if (p_verbose > 0) { verbose_enter(); smsg((char_u *)_("Writing undo file: %s"), file_name); verbose_leave(); } #ifdef U_DEBUG /* Check there is no problem in undo info before writing. */ u_check(FALSE); #endif #ifdef UNIX /* * Try to set the group of the undo file same as the original file. If * this fails, set the protection bits for the group same as the * protection bits for others. */ if (st_old_valid && mch_stat((char *)file_name, &st_new) >= 0 && st_new.st_gid != st_old.st_gid # ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */ && fchown(fd, (uid_t)-1, st_old.st_gid) != 0 # endif ) mch_setperm(file_name, (perm & 0707) | ((perm & 07) << 3)); # ifdef HAVE_SELINUX if (buf->b_ffname != NULL) mch_copy_sec(buf->b_ffname, file_name); # endif #endif fp = fdopen(fd, "w"); if (fp == NULL) { EMSG2(_(e_not_open), file_name); close(fd); mch_remove(file_name); goto theend; } /* Undo must be synced. */ u_sync(TRUE); /* * Write the header. */ if (serialize_header(fp, buf, hash) == FAIL) goto write_error; #ifdef FEAT_CRYPT if (*buf->b_p_key != NUL) do_crypt = TRUE; #endif /* * Iteratively serialize UHPs and their UEPs from the top down. */ mark = ++lastmark; uhp = buf->b_u_oldhead; while (uhp != NULL) { /* Serialize current UHP if we haven't seen it */ if (uhp->uh_walk != mark) { uhp->uh_walk = mark; #ifdef U_DEBUG ++headers_written; #endif if (serialize_uhp(fp, buf, uhp) == FAIL) goto write_error; } /* Now walk through the tree - algorithm from undo_time(). */ if (uhp->uh_prev.ptr != NULL && uhp->uh_prev.ptr->uh_walk != mark) uhp = uhp->uh_prev.ptr; else if (uhp->uh_alt_next.ptr != NULL && uhp->uh_alt_next.ptr->uh_walk != mark) uhp = uhp->uh_alt_next.ptr; else if (uhp->uh_next.ptr != NULL && uhp->uh_alt_prev.ptr == NULL && uhp->uh_next.ptr->uh_walk != mark) uhp = uhp->uh_next.ptr; else if (uhp->uh_alt_prev.ptr != NULL) uhp = uhp->uh_alt_prev.ptr; else uhp = uhp->uh_next.ptr; } if (put_bytes(fp, (long_u)UF_HEADER_END_MAGIC, 2) == OK) write_ok = TRUE; #ifdef U_DEBUG if (headers_written != buf->b_u_numhead) EMSG3("Written %ld headers, but numhead is %ld", headers_written, buf->b_u_numhead); #endif write_error: fclose(fp); if (!write_ok) EMSG2(_("E829: write error in undo file: %s"), file_name); #if defined(MACOS_CLASSIC) || defined(WIN3264) /* Copy file attributes; for systems where this can only be done after * closing the file. */ if (buf->b_ffname != NULL) (void)mch_copy_file_attribute(buf->b_ffname, file_name); #endif #ifdef HAVE_ACL if (buf->b_ffname != NULL) { vim_acl_T acl; /* For systems that support ACL: get the ACL from the original file. */ acl = mch_get_acl(buf->b_ffname); mch_set_acl(file_name, acl); mch_free_acl(acl); } #endif theend: #ifdef FEAT_CRYPT if (do_crypt) crypt_pop_state(); #endif if (file_name != name) vim_free(file_name); } /* * Load the undo tree from an undo file. * If "name" is not NULL use it as the undo file name. This also means being * a bit more verbose. * Otherwise use curbuf->b_ffname to generate the undo file name. * "hash[UNDO_HASH_SIZE]" must be the hash value of the buffer text. */ void u_read_undo(name, hash, orig_name) char_u *name; char_u *hash; char_u *orig_name; { char_u *file_name; FILE *fp; long version, str_len; char_u *line_ptr = NULL; linenr_T line_lnum; colnr_T line_colnr; linenr_T line_count; int num_head = 0; long old_header_seq, new_header_seq, cur_header_seq; long seq_last, seq_cur; long last_save_nr = 0; short old_idx = -1, new_idx = -1, cur_idx = -1; long num_read_uhps = 0; time_t seq_time; int i, j; int c; u_header_T *uhp; u_header_T **uhp_table = NULL; char_u read_hash[UNDO_HASH_SIZE]; char_u magic_buf[UF_START_MAGIC_LEN]; #ifdef U_DEBUG int *uhp_table_used; #endif #ifdef UNIX struct stat st_orig; struct stat st_undo; #endif #ifdef FEAT_CRYPT int do_decrypt = FALSE; #endif if (name == NULL) { file_name = u_get_undo_file_name(curbuf->b_ffname, TRUE); if (file_name == NULL) return; #ifdef UNIX /* For safety we only read an undo file if the owner is equal to the * owner of the text file. */ if (mch_stat((char *)orig_name, &st_orig) >= 0 && mch_stat((char *)file_name, &st_undo) >= 0 && st_orig.st_uid != st_undo.st_uid) { if (p_verbose > 0) { verbose_enter(); smsg((char_u *)_("Not reading undo file, owner differs: %s"), file_name); verbose_leave(); } return; } #endif } else file_name = name; if (p_verbose > 0) { verbose_enter(); smsg((char_u *)_("Reading undo file: %s"), file_name); verbose_leave(); } fp = mch_fopen((char *)file_name, "r"); if (fp == NULL) { if (name != NULL || p_verbose > 0) EMSG2(_("E822: Cannot open undo file for reading: %s"), file_name); goto error; } /* * Read the undo file header. */ if (fread(magic_buf, UF_START_MAGIC_LEN, 1, fp) != 1 || memcmp(magic_buf, UF_START_MAGIC, UF_START_MAGIC_LEN) != 0) { EMSG2(_("E823: Not an undo file: %s"), file_name); goto error; } version = get2c(fp); if (version == UF_VERSION_CRYPT) { #ifdef FEAT_CRYPT if (*curbuf->b_p_key == NUL) { EMSG2(_("E832: Non-encrypted file has encrypted undo file: %s"), file_name); goto error; } if (prepare_crypt_read(fp) == FAIL) { EMSG2(_("E826: Undo file decryption failed: %s"), file_name); goto error; } do_decrypt = TRUE; #else EMSG2(_("E827: Undo file is encrypted: %s"), file_name); goto error; #endif } else if (version != UF_VERSION) { EMSG2(_("E824: Incompatible undo file: %s"), file_name); goto error; } if (fread(read_hash, UNDO_HASH_SIZE, 1, fp) != 1) { corruption_error("hash", file_name); goto error; } line_count = (linenr_T)get4c(fp); if (memcmp(hash, read_hash, UNDO_HASH_SIZE) != 0 || line_count != curbuf->b_ml.ml_line_count) { if (p_verbose > 0 || name != NULL) { if (name == NULL) verbose_enter(); give_warning((char_u *) _("File contents changed, cannot use undo info"), TRUE); if (name == NULL) verbose_leave(); } goto error; } /* Read undo data for "U" command. */ str_len = get4c(fp); if (str_len < 0) goto error; if (str_len > 0) line_ptr = read_string_decrypt(curbuf, fp, str_len); line_lnum = (linenr_T)get4c(fp); line_colnr = (colnr_T)get4c(fp); if (line_lnum < 0 || line_colnr < 0) { corruption_error("line lnum/col", file_name); goto error; } /* Begin general undo data */ old_header_seq = get4c(fp); new_header_seq = get4c(fp); cur_header_seq = get4c(fp); num_head = get4c(fp); seq_last = get4c(fp); seq_cur = get4c(fp); seq_time = get8ctime(fp); /* Optional header fields. */ for (;;) { int len = getc(fp); int what; if (len == 0 || len == EOF) break; what = getc(fp); switch (what) { case UF_LAST_SAVE_NR: last_save_nr = get4c(fp); break; default: /* field not supported, skip */ while (--len >= 0) (void)getc(fp); } } /* uhp_table will store the freshly created undo headers we allocate * until we insert them into curbuf. The table remains sorted by the * sequence numbers of the headers. * When there are no headers uhp_table is NULL. */ if (num_head > 0) { uhp_table = (u_header_T **)U_ALLOC_LINE( num_head * sizeof(u_header_T *)); if (uhp_table == NULL) goto error; } while ((c = get2c(fp)) == UF_HEADER_MAGIC) { if (num_read_uhps >= num_head) { corruption_error("num_head too small", file_name); goto error; } uhp = unserialize_uhp(fp, file_name); if (uhp == NULL) goto error; uhp_table[num_read_uhps++] = uhp; } if (num_read_uhps != num_head) { corruption_error("num_head", file_name); goto error; } if (c != UF_HEADER_END_MAGIC) { corruption_error("end marker", file_name); goto error; } #ifdef U_DEBUG uhp_table_used = (int *)alloc_clear( (unsigned)(sizeof(int) * num_head + 1)); # define SET_FLAG(j) ++uhp_table_used[j] #else # define SET_FLAG(j) #endif /* We have put all of the headers into a table. Now we iterate through the * table and swizzle each sequence number we have stored in uh_*_seq into * a pointer corresponding to the header with that sequence number. */ for (i = 0; i < num_head; i++) { uhp = uhp_table[i]; if (uhp == NULL) continue; for (j = 0; j < num_head; j++) if (uhp_table[j] != NULL && i != j && uhp_table[i]->uh_seq == uhp_table[j]->uh_seq) { corruption_error("duplicate uh_seq", file_name); goto error; } for (j = 0; j < num_head; j++) if (uhp_table[j] != NULL && uhp_table[j]->uh_seq == uhp->uh_next.seq) { uhp->uh_next.ptr = uhp_table[j]; SET_FLAG(j); break; } for (j = 0; j < num_head; j++) if (uhp_table[j] != NULL && uhp_table[j]->uh_seq == uhp->uh_prev.seq) { uhp->uh_prev.ptr = uhp_table[j]; SET_FLAG(j); break; } for (j = 0; j < num_head; j++) if (uhp_table[j] != NULL && uhp_table[j]->uh_seq == uhp->uh_alt_next.seq) { uhp->uh_alt_next.ptr = uhp_table[j]; SET_FLAG(j); break; } for (j = 0; j < num_head; j++) if (uhp_table[j] != NULL && uhp_table[j]->uh_seq == uhp->uh_alt_prev.seq) { uhp->uh_alt_prev.ptr = uhp_table[j]; SET_FLAG(j); break; } if (old_header_seq > 0 && old_idx < 0 && uhp->uh_seq == old_header_seq) { old_idx = i; SET_FLAG(i); } if (new_header_seq > 0 && new_idx < 0 && uhp->uh_seq == new_header_seq) { new_idx = i; SET_FLAG(i); } if (cur_header_seq > 0 && cur_idx < 0 && uhp->uh_seq == cur_header_seq) { cur_idx = i; SET_FLAG(i); } } /* Now that we have read the undo info successfully, free the current undo * info and use the info from the file. */ u_blockfree(curbuf); curbuf->b_u_oldhead = old_idx < 0 ? NULL : uhp_table[old_idx]; curbuf->b_u_newhead = new_idx < 0 ? NULL : uhp_table[new_idx]; curbuf->b_u_curhead = cur_idx < 0 ? NULL : uhp_table[cur_idx]; curbuf->b_u_line_ptr = line_ptr; curbuf->b_u_line_lnum = line_lnum; curbuf->b_u_line_colnr = line_colnr; curbuf->b_u_numhead = num_head; curbuf->b_u_seq_last = seq_last; curbuf->b_u_seq_cur = seq_cur; curbuf->b_u_time_cur = seq_time; curbuf->b_u_save_nr_last = last_save_nr; curbuf->b_u_save_nr_cur = last_save_nr; curbuf->b_u_synced = TRUE; vim_free(uhp_table); #ifdef U_DEBUG for (i = 0; i < num_head; ++i) if (uhp_table_used[i] == 0) EMSGN("uhp_table entry %ld not used, leaking memory", i); vim_free(uhp_table_used); u_check(TRUE); #endif if (name != NULL) smsg((char_u *)_("Finished reading undo file %s"), file_name); goto theend; error: vim_free(line_ptr); if (uhp_table != NULL) { for (i = 0; i < num_read_uhps; i++) if (uhp_table[i] != NULL) u_free_uhp(uhp_table[i]); vim_free(uhp_table); } theend: #ifdef FEAT_CRYPT if (do_decrypt) crypt_pop_state(); #endif if (fp != NULL) fclose(fp); if (file_name != name) vim_free(file_name); return; } #endif /* FEAT_PERSISTENT_UNDO */ /* * If 'cpoptions' contains 'u': Undo the previous undo or redo (vi compatible). * If 'cpoptions' does not contain 'u': Always undo. */ void u_undo(count) int count; { /* * If we get an undo command while executing a macro, we behave like the * original vi. If this happens twice in one macro the result will not * be compatible. */ if (curbuf->b_u_synced == FALSE) { u_sync(TRUE); count = 1; } if (vim_strchr(p_cpo, CPO_UNDO) == NULL) undo_undoes = TRUE; else undo_undoes = !undo_undoes; u_doit(count); } /* * If 'cpoptions' contains 'u': Repeat the previous undo or redo. * If 'cpoptions' does not contain 'u': Always redo. */ void u_redo(count) int count; { if (vim_strchr(p_cpo, CPO_UNDO) == NULL) undo_undoes = FALSE; u_doit(count); } /* * Undo or redo, depending on 'undo_undoes', 'count' times. */ static void u_doit(startcount) int startcount; { int count = startcount; if (!undo_allowed()) return; u_newcount = 0; u_oldcount = 0; if (curbuf->b_ml.ml_flags & ML_EMPTY) u_oldcount = -1; while (count--) { /* Do the change warning now, so that it triggers FileChangedRO when * needed. This may cause the file to be reloaded, that must happen * before we do anything, because it may change curbuf->b_u_curhead * and more. */ change_warning(0); if (undo_undoes) { if (curbuf->b_u_curhead == NULL) /* first undo */ curbuf->b_u_curhead = curbuf->b_u_newhead; else if (p_ul > 0) /* multi level undo */ /* get next undo */ curbuf->b_u_curhead = curbuf->b_u_curhead->uh_next.ptr; /* nothing to undo */ if (curbuf->b_u_numhead == 0 || curbuf->b_u_curhead == NULL) { /* stick curbuf->b_u_curhead at end */ curbuf->b_u_curhead = curbuf->b_u_oldhead; beep_flush(); if (count == startcount - 1) { MSG(_("Already at oldest change")); return; } break; } u_undoredo(TRUE); } else { if (curbuf->b_u_curhead == NULL || p_ul <= 0) { beep_flush(); /* nothing to redo */ if (count == startcount - 1) { MSG(_("Already at newest change")); return; } break; } u_undoredo(FALSE); /* Advance for next redo. Set "newhead" when at the end of the * redoable changes. */ if (curbuf->b_u_curhead->uh_prev.ptr == NULL) curbuf->b_u_newhead = curbuf->b_u_curhead; curbuf->b_u_curhead = curbuf->b_u_curhead->uh_prev.ptr; } } u_undo_end(undo_undoes, FALSE); } /* * Undo or redo over the timeline. * When "step" is negative go back in time, otherwise goes forward in time. * When "sec" is FALSE make "step" steps, when "sec" is TRUE use "step" as * seconds. * When "file" is TRUE use "step" as a number of file writes. * When "absolute" is TRUE use "step" as the sequence number to jump to. * "sec" must be FALSE then. */ void undo_time(step, sec, file, absolute) long step; int sec; int file; int absolute; { long target; long closest; long closest_start; long closest_seq = 0; long val; u_header_T *uhp; u_header_T *last; int mark; int nomark; int round; int dosec = sec; int dofile = file; int above = FALSE; int did_undo = TRUE; /* First make sure the current undoable change is synced. */ if (curbuf->b_u_synced == FALSE) u_sync(TRUE); u_newcount = 0; u_oldcount = 0; if (curbuf->b_ml.ml_flags & ML_EMPTY) u_oldcount = -1; /* "target" is the node below which we want to be. * Init "closest" to a value we can't reach. */ if (absolute) { target = step; closest = -1; } else { /* When doing computations with time_t subtract starttime, because * time_t converted to a long may result in a wrong number. */ if (dosec) target = (long)(curbuf->b_u_time_cur - starttime) + step; else if (dofile) { if (step < 0) { /* Going back to a previous write. If there were changes after * the last write, count that as moving one file-write, so * that ":earlier 1f" undoes all changes since the last save. */ uhp = curbuf->b_u_curhead; if (uhp != NULL) uhp = uhp->uh_next.ptr; else uhp = curbuf->b_u_newhead; if (uhp != NULL && uhp->uh_save_nr != 0) /* "uh_save_nr" was set in the last block, that means * there were no changes since the last write */ target = curbuf->b_u_save_nr_cur + step; else /* count the changes since the last write as one step */ target = curbuf->b_u_save_nr_cur + step + 1; if (target <= 0) /* Go to before first write: before the oldest change. Use * the sequence number for that. */ dofile = FALSE; } else { /* Moving forward to a newer write. */ target = curbuf->b_u_save_nr_cur + step; if (target > curbuf->b_u_save_nr_last) { /* Go to after last write: after the latest change. Use * the sequence number for that. */ target = curbuf->b_u_seq_last + 1; dofile = FALSE; } } } else target = curbuf->b_u_seq_cur + step; if (step < 0) { if (target < 0) target = 0; closest = -1; } else { if (dosec) closest = (long)(time(NULL) - starttime + 1); else if (dofile) closest = curbuf->b_u_save_nr_last + 2; else closest = curbuf->b_u_seq_last + 2; if (target >= closest) target = closest - 1; } } closest_start = closest; closest_seq = curbuf->b_u_seq_cur; /* * May do this twice: * 1. Search for "target", update "closest" to the best match found. * 2. If "target" not found search for "closest". * * When using the closest time we use the sequence number in the second * round, because there may be several entries with the same time. */ for (round = 1; round <= 2; ++round) { /* Find the path from the current state to where we want to go. The * desired state can be anywhere in the undo tree, need to go all over * it. We put "nomark" in uh_walk where we have been without success, * "mark" where it could possibly be. */ mark = ++lastmark; nomark = ++lastmark; if (curbuf->b_u_curhead == NULL) /* at leaf of the tree */ uhp = curbuf->b_u_newhead; else uhp = curbuf->b_u_curhead; while (uhp != NULL) { uhp->uh_walk = mark; if (dosec) val = (long)(uhp->uh_time - starttime); else if (dofile) val = uhp->uh_save_nr; else val = uhp->uh_seq; if (round == 1 && !(dofile && val == 0)) { /* Remember the header that is closest to the target. * It must be at least in the right direction (checked with * "b_u_seq_cur"). When the timestamp is equal find the * highest/lowest sequence number. */ if ((step < 0 ? uhp->uh_seq <= curbuf->b_u_seq_cur : uhp->uh_seq > curbuf->b_u_seq_cur) && ((dosec && val == closest) ? (step < 0 ? uhp->uh_seq < closest_seq : uhp->uh_seq > closest_seq) : closest == closest_start || (val > target ? (closest > target ? val - target <= closest - target : val - target <= target - closest) : (closest > target ? target - val <= closest - target : target - val <= target - closest)))) { closest = val; closest_seq = uhp->uh_seq; } } /* Quit searching when we found a match. But when searching for a * time we need to continue looking for the best uh_seq. */ if (target == val && !dosec) { target = uhp->uh_seq; break; } /* go down in the tree if we haven't been there */ if (uhp->uh_prev.ptr != NULL && uhp->uh_prev.ptr->uh_walk != nomark && uhp->uh_prev.ptr->uh_walk != mark) uhp = uhp->uh_prev.ptr; /* go to alternate branch if we haven't been there */ else if (uhp->uh_alt_next.ptr != NULL && uhp->uh_alt_next.ptr->uh_walk != nomark && uhp->uh_alt_next.ptr->uh_walk != mark) uhp = uhp->uh_alt_next.ptr; /* go up in the tree if we haven't been there and we are at the * start of alternate branches */ else if (uhp->uh_next.ptr != NULL && uhp->uh_alt_prev.ptr == NULL && uhp->uh_next.ptr->uh_walk != nomark && uhp->uh_next.ptr->uh_walk != mark) { /* If still at the start we don't go through this change. */ if (uhp == curbuf->b_u_curhead) uhp->uh_walk = nomark; uhp = uhp->uh_next.ptr; } else { /* need to backtrack; mark this node as useless */ uhp->uh_walk = nomark; if (uhp->uh_alt_prev.ptr != NULL) uhp = uhp->uh_alt_prev.ptr; else uhp = uhp->uh_next.ptr; } } if (uhp != NULL) /* found it */ break; if (absolute) { EMSGN(_("E830: Undo number %ld not found"), step); return; } if (closest == closest_start) { if (step < 0) MSG(_("Already at oldest change")); else MSG(_("Already at newest change")); return; } target = closest_seq; dosec = FALSE; dofile = FALSE; if (step < 0) above = TRUE; /* stop above the header */ } /* If we found it: Follow the path to go to where we want to be. */ if (uhp != NULL) { /* * First go up the tree as much as needed. */ while (!got_int) { /* Do the change warning now, for the same reason as above. */ change_warning(0); uhp = curbuf->b_u_curhead; if (uhp == NULL) uhp = curbuf->b_u_newhead; else uhp = uhp->uh_next.ptr; if (uhp == NULL || uhp->uh_walk != mark || (uhp->uh_seq == target && !above)) break; curbuf->b_u_curhead = uhp; u_undoredo(TRUE); uhp->uh_walk = nomark; /* don't go back down here */ } /* * And now go down the tree (redo), branching off where needed. */ while (!got_int) { /* Do the change warning now, for the same reason as above. */ change_warning(0); uhp = curbuf->b_u_curhead; if (uhp == NULL) break; /* Go back to the first branch with a mark. */ while (uhp->uh_alt_prev.ptr != NULL && uhp->uh_alt_prev.ptr->uh_walk == mark) uhp = uhp->uh_alt_prev.ptr; /* Find the last branch with a mark, that's the one. */ last = uhp; while (last->uh_alt_next.ptr != NULL && last->uh_alt_next.ptr->uh_walk == mark) last = last->uh_alt_next.ptr; if (last != uhp) { /* Make the used branch the first entry in the list of * alternatives to make "u" and CTRL-R take this branch. */ while (uhp->uh_alt_prev.ptr != NULL) uhp = uhp->uh_alt_prev.ptr; if (last->uh_alt_next.ptr != NULL) last->uh_alt_next.ptr->uh_alt_prev.ptr = last->uh_alt_prev.ptr; last->uh_alt_prev.ptr->uh_alt_next.ptr = last->uh_alt_next.ptr; last->uh_alt_prev.ptr = NULL; last->uh_alt_next.ptr = uhp; uhp->uh_alt_prev.ptr = last; if (curbuf->b_u_oldhead == uhp) curbuf->b_u_oldhead = last; uhp = last; if (uhp->uh_next.ptr != NULL) uhp->uh_next.ptr->uh_prev.ptr = uhp; } curbuf->b_u_curhead = uhp; if (uhp->uh_walk != mark) break; /* must have reached the target */ /* Stop when going backwards in time and didn't find the exact * header we were looking for. */ if (uhp->uh_seq == target && above) { curbuf->b_u_seq_cur = target - 1; break; } u_undoredo(FALSE); /* Advance "curhead" to below the header we last used. If it * becomes NULL then we need to set "newhead" to this leaf. */ if (uhp->uh_prev.ptr == NULL) curbuf->b_u_newhead = uhp; curbuf->b_u_curhead = uhp->uh_prev.ptr; did_undo = FALSE; if (uhp->uh_seq == target) /* found it! */ break; uhp = uhp->uh_prev.ptr; if (uhp == NULL || uhp->uh_walk != mark) { /* Need to redo more but can't find it... */ EMSG2(_(e_intern2), "undo_time()"); break; } } } u_undo_end(did_undo, absolute); } /* * u_undoredo: common code for undo and redo * * The lines in the file are replaced by the lines in the entry list at * curbuf->b_u_curhead. The replaced lines in the file are saved in the entry * list for the next undo/redo. * * When "undo" is TRUE we go up in the tree, when FALSE we go down. */ static void u_undoredo(undo) int undo; { char_u **newarray = NULL; linenr_T oldsize; linenr_T newsize; linenr_T top, bot; linenr_T lnum; linenr_T newlnum = MAXLNUM; long i; u_entry_T *uep, *nuep; u_entry_T *newlist = NULL; int old_flags; int new_flags; pos_T namedm[NMARKS]; #ifdef FEAT_VISUAL visualinfo_T visualinfo; #endif int empty_buffer; /* buffer became empty */ u_header_T *curhead = curbuf->b_u_curhead; #ifdef FEAT_AUTOCMD /* Don't want autocommands using the undo structures here, they are * invalid till the end. */ block_autocmds(); #endif #ifdef U_DEBUG u_check(FALSE); #endif old_flags = curhead->uh_flags; new_flags = (curbuf->b_changed ? UH_CHANGED : 0) + ((curbuf->b_ml.ml_flags & ML_EMPTY) ? UH_EMPTYBUF : 0); setpcmark(); /* * save marks before undo/redo */ mch_memmove(namedm, curbuf->b_namedm, sizeof(pos_T) * NMARKS); #ifdef FEAT_VISUAL visualinfo = curbuf->b_visual; #endif curbuf->b_op_start.lnum = curbuf->b_ml.ml_line_count; curbuf->b_op_start.col = 0; curbuf->b_op_end.lnum = 0; curbuf->b_op_end.col = 0; for (uep = curhead->uh_entry; uep != NULL; uep = nuep) { top = uep->ue_top; bot = uep->ue_bot; if (bot == 0) bot = curbuf->b_ml.ml_line_count + 1; if (top > curbuf->b_ml.ml_line_count || top >= bot || bot > curbuf->b_ml.ml_line_count + 1) { #ifdef FEAT_AUTOCMD unblock_autocmds(); #endif EMSG(_("E438: u_undo: line numbers wrong")); changed(); /* don't want UNCHANGED now */ return; } oldsize = bot - top - 1; /* number of lines before undo */ newsize = uep->ue_size; /* number of lines after undo */ if (top < newlnum) { /* If the saved cursor is somewhere in this undo block, move it to * the remembered position. Makes "gwap" put the cursor back * where it was. */ lnum = curhead->uh_cursor.lnum; if (lnum >= top && lnum <= top + newsize + 1) { curwin->w_cursor = curhead->uh_cursor; newlnum = curwin->w_cursor.lnum - 1; } else { /* Use the first line that actually changed. Avoids that * undoing auto-formatting puts the cursor in the previous * line. */ for (i = 0; i < newsize && i < oldsize; ++i) if (STRCMP(uep->ue_array[i], ml_get(top + 1 + i)) != 0) break; if (i == newsize && newlnum == MAXLNUM && uep->ue_next == NULL) { newlnum = top; curwin->w_cursor.lnum = newlnum + 1; } else if (i < newsize) { newlnum = top + i; curwin->w_cursor.lnum = newlnum + 1; } } } empty_buffer = FALSE; /* delete the lines between top and bot and save them in newarray */ if (oldsize > 0) { if ((newarray = (char_u **)U_ALLOC_LINE( sizeof(char_u *) * oldsize)) == NULL) { do_outofmem_msg((long_u)(sizeof(char_u *) * oldsize)); /* * We have messed up the entry list, repair is impossible. * we have to free the rest of the list. */ while (uep != NULL) { nuep = uep->ue_next; u_freeentry(uep, uep->ue_size); uep = nuep; } break; } /* delete backwards, it goes faster in most cases */ for (lnum = bot - 1, i = oldsize; --i >= 0; --lnum) { /* what can we do when we run out of memory? */ if ((newarray[i] = u_save_line(lnum)) == NULL) do_outofmem_msg((long_u)0); /* remember we deleted the last line in the buffer, and a * dummy empty line will be inserted */ if (curbuf->b_ml.ml_line_count == 1) empty_buffer = TRUE; ml_delete(lnum, FALSE); } } else newarray = NULL; /* insert the lines in u_array between top and bot */ if (newsize) { for (lnum = top, i = 0; i < newsize; ++i, ++lnum) { /* * If the file is empty, there is an empty line 1 that we * should get rid of, by replacing it with the new line */ if (empty_buffer && lnum == 0) ml_replace((linenr_T)1, uep->ue_array[i], TRUE); else ml_append(lnum, uep->ue_array[i], (colnr_T)0, FALSE); vim_free(uep->ue_array[i]); } vim_free((char_u *)uep->ue_array); } /* adjust marks */ if (oldsize != newsize) { mark_adjust(top + 1, top + oldsize, (long)MAXLNUM, (long)newsize - (long)oldsize); if (curbuf->b_op_start.lnum > top + oldsize) curbuf->b_op_start.lnum += newsize - oldsize; if (curbuf->b_op_end.lnum > top + oldsize) curbuf->b_op_end.lnum += newsize - oldsize; } changed_lines(top + 1, 0, bot, newsize - oldsize); /* set '[ and '] mark */ if (top + 1 < curbuf->b_op_start.lnum) curbuf->b_op_start.lnum = top + 1; if (newsize == 0 && top + 1 > curbuf->b_op_end.lnum) curbuf->b_op_end.lnum = top + 1; else if (top + newsize > curbuf->b_op_end.lnum) curbuf->b_op_end.lnum = top + newsize; u_newcount += newsize; u_oldcount += oldsize; uep->ue_size = oldsize; uep->ue_array = newarray; uep->ue_bot = top + newsize + 1; /* * insert this entry in front of the new entry list */ nuep = uep->ue_next; uep->ue_next = newlist; newlist = uep; } curhead->uh_entry = newlist; curhead->uh_flags = new_flags; if ((old_flags & UH_EMPTYBUF) && bufempty()) curbuf->b_ml.ml_flags |= ML_EMPTY; if (old_flags & UH_CHANGED) changed(); else #ifdef FEAT_NETBEANS_INTG /* per netbeans undo rules, keep it as modified */ if (!isNetbeansModified(curbuf)) #endif unchanged(curbuf, FALSE); /* * restore marks from before undo/redo */ for (i = 0; i < NMARKS; ++i) if (curhead->uh_namedm[i].lnum != 0) { curbuf->b_namedm[i] = curhead->uh_namedm[i]; curhead->uh_namedm[i] = namedm[i]; } #ifdef FEAT_VISUAL if (curhead->uh_visual.vi_start.lnum != 0) { curbuf->b_visual = curhead->uh_visual; curhead->uh_visual = visualinfo; } #endif /* * If the cursor is only off by one line, put it at the same position as * before starting the change (for the "o" command). * Otherwise the cursor should go to the first undone line. */ if (curhead->uh_cursor.lnum + 1 == curwin->w_cursor.lnum && curwin->w_cursor.lnum > 1) --curwin->w_cursor.lnum; if (curwin->w_cursor.lnum <= curbuf->b_ml.ml_line_count) { if (curhead->uh_cursor.lnum == curwin->w_cursor.lnum) { curwin->w_cursor.col = curhead->uh_cursor.col; #ifdef FEAT_VIRTUALEDIT if (virtual_active() && curhead->uh_cursor_vcol >= 0) coladvance((colnr_T)curhead->uh_cursor_vcol); else curwin->w_cursor.coladd = 0; #endif } else beginline(BL_SOL | BL_FIX); } else { /* We get here with the current cursor line being past the end (eg * after adding lines at the end of the file, and then undoing it). * check_cursor() will move the cursor to the last line. Move it to * the first column here. */ curwin->w_cursor.col = 0; #ifdef FEAT_VIRTUALEDIT curwin->w_cursor.coladd = 0; #endif } /* Make sure the cursor is on an existing line and column. */ check_cursor(); /* Remember where we are for "g-" and ":earlier 10s". */ curbuf->b_u_seq_cur = curhead->uh_seq; if (undo) /* We are below the previous undo. However, to make ":earlier 1s" * work we compute this as being just above the just undone change. */ --curbuf->b_u_seq_cur; /* Remember where we are for ":earlier 1f" and ":later 1f". */ if (curhead->uh_save_nr != 0) { if (undo) curbuf->b_u_save_nr_cur = curhead->uh_save_nr - 1; else curbuf->b_u_save_nr_cur = curhead->uh_save_nr; } /* The timestamp can be the same for multiple changes, just use the one of * the undone/redone change. */ curbuf->b_u_time_cur = curhead->uh_time; #ifdef FEAT_AUTOCMD unblock_autocmds(); #endif #ifdef U_DEBUG u_check(FALSE); #endif } /* * If we deleted or added lines, report the number of less/more lines. * Otherwise, report the number of changes (this may be incorrect * in some cases, but it's better than nothing). */ static void u_undo_end(did_undo, absolute) int did_undo; /* just did an undo */ int absolute; /* used ":undo N" */ { char *msgstr; u_header_T *uhp; char_u msgbuf[80]; #ifdef FEAT_FOLDING if ((fdo_flags & FDO_UNDO) && KeyTyped) foldOpenCursor(); #endif if (global_busy /* no messages now, wait until global is finished */ || !messaging()) /* 'lazyredraw' set, don't do messages now */ return; if (curbuf->b_ml.ml_flags & ML_EMPTY) --u_newcount; u_oldcount -= u_newcount; if (u_oldcount == -1) msgstr = N_("more line"); else if (u_oldcount < 0) msgstr = N_("more lines"); else if (u_oldcount == 1) msgstr = N_("line less"); else if (u_oldcount > 1) msgstr = N_("fewer lines"); else { u_oldcount = u_newcount; if (u_newcount == 1) msgstr = N_("change"); else msgstr = N_("changes"); } if (curbuf->b_u_curhead != NULL) { /* For ":undo N" we prefer a "after #N" message. */ if (absolute && curbuf->b_u_curhead->uh_next.ptr != NULL) { uhp = curbuf->b_u_curhead->uh_next.ptr; did_undo = FALSE; } else if (did_undo) uhp = curbuf->b_u_curhead; else uhp = curbuf->b_u_curhead->uh_next.ptr; } else uhp = curbuf->b_u_newhead; if (uhp == NULL) *msgbuf = NUL; else u_add_time(msgbuf, sizeof(msgbuf), uhp->uh_time); #ifdef FEAT_CONCEAL { win_T *wp; FOR_ALL_WINDOWS(wp) { if (wp->w_buffer == curbuf && wp->w_p_cole > 0) redraw_win_later(wp, NOT_VALID); } } #endif smsg((char_u *)_("%ld %s; %s #%ld %s"), u_oldcount < 0 ? -u_oldcount : u_oldcount, _(msgstr), did_undo ? _("before") : _("after"), uhp == NULL ? 0L : uhp->uh_seq, msgbuf); } /* * u_sync: stop adding to the current entry list */ void u_sync(force) int force; /* Also sync when no_u_sync is set. */ { /* Skip it when already synced or syncing is disabled. */ if (curbuf->b_u_synced || (!force && no_u_sync > 0)) return; #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK) if (im_is_preediting()) return; /* XIM is busy, don't break an undo sequence */ #endif if (p_ul < 0) curbuf->b_u_synced = TRUE; /* no entries, nothing to do */ else { u_getbot(); /* compute ue_bot of previous u_save */ curbuf->b_u_curhead = NULL; } } /* * ":undolist": List the leafs of the undo tree */ void ex_undolist(eap) exarg_T *eap UNUSED; { garray_T ga; u_header_T *uhp; int mark; int nomark; int changes = 1; int i; /* * 1: walk the tree to find all leafs, put the info in "ga". * 2: sort the lines * 3: display the list */ mark = ++lastmark; nomark = ++lastmark; ga_init2(&ga, (int)sizeof(char *), 20); uhp = curbuf->b_u_oldhead; while (uhp != NULL) { if (uhp->uh_prev.ptr == NULL && uhp->uh_walk != nomark && uhp->uh_walk != mark) { if (ga_grow(&ga, 1) == FAIL) break; vim_snprintf((char *)IObuff, IOSIZE, "%6ld %7ld ", uhp->uh_seq, changes); u_add_time(IObuff + STRLEN(IObuff), IOSIZE - STRLEN(IObuff), uhp->uh_time); if (uhp->uh_save_nr > 0) { while (STRLEN(IObuff) < 33) STRCAT(IObuff, " "); vim_snprintf_add((char *)IObuff, IOSIZE, " %3ld", uhp->uh_save_nr); } ((char_u **)(ga.ga_data))[ga.ga_len++] = vim_strsave(IObuff); } uhp->uh_walk = mark; /* go down in the tree if we haven't been there */ if (uhp->uh_prev.ptr != NULL && uhp->uh_prev.ptr->uh_walk != nomark && uhp->uh_prev.ptr->uh_walk != mark) { uhp = uhp->uh_prev.ptr; ++changes; } /* go to alternate branch if we haven't been there */ else if (uhp->uh_alt_next.ptr != NULL && uhp->uh_alt_next.ptr->uh_walk != nomark && uhp->uh_alt_next.ptr->uh_walk != mark) uhp = uhp->uh_alt_next.ptr; /* go up in the tree if we haven't been there and we are at the * start of alternate branches */ else if (uhp->uh_next.ptr != NULL && uhp->uh_alt_prev.ptr == NULL && uhp->uh_next.ptr->uh_walk != nomark && uhp->uh_next.ptr->uh_walk != mark) { uhp = uhp->uh_next.ptr; --changes; } else { /* need to backtrack; mark this node as done */ uhp->uh_walk = nomark; if (uhp->uh_alt_prev.ptr != NULL) uhp = uhp->uh_alt_prev.ptr; else { uhp = uhp->uh_next.ptr; --changes; } } } if (ga.ga_len == 0) MSG(_("Nothing to undo")); else { sort_strings((char_u **)ga.ga_data, ga.ga_len); msg_start(); msg_puts_attr((char_u *)_("number changes when saved"), hl_attr(HLF_T)); for (i = 0; i < ga.ga_len && !got_int; ++i) { msg_putchar('\n'); if (got_int) break; msg_puts(((char_u **)ga.ga_data)[i]); } msg_end(); ga_clear_strings(&ga); } } /* * Put the timestamp of an undo header in "buf[buflen]" in a nice format. */ static void u_add_time(buf, buflen, tt) char_u *buf; size_t buflen; time_t tt; { #ifdef HAVE_STRFTIME struct tm *curtime; if (time(NULL) - tt >= 100) { curtime = localtime(&tt); if (time(NULL) - tt < (60L * 60L * 12L)) /* within 12 hours */ (void)strftime((char *)buf, buflen, "%H:%M:%S", curtime); else if (time(NULL) - tt < (60L * 60L * 24L * 180L)) /* within 6 months */ (void)strftime((char *)buf, buflen, "%m/%d %H:%M:%S", curtime); else /* long ago */ (void)strftime((char *)buf, buflen, "%Y/%m/%d %H:%M:%S", curtime); } else #endif vim_snprintf((char *)buf, buflen, _("%ld seconds ago"), (long)(time(NULL) - tt)); } /* * ":undojoin": continue adding to the last entry list */ void ex_undojoin(eap) exarg_T *eap UNUSED; { if (curbuf->b_u_newhead == NULL) return; /* nothing changed before */ if (curbuf->b_u_curhead != NULL) { EMSG(_("E790: undojoin is not allowed after undo")); return; } if (!curbuf->b_u_synced) return; /* already unsynced */ if (p_ul < 0) return; /* no entries, nothing to do */ else { /* Go back to the last entry */ curbuf->b_u_curhead = curbuf->b_u_newhead; curbuf->b_u_synced = FALSE; /* no entries, nothing to do */ } } /* * Called after writing or reloading the file and setting b_changed to FALSE. * Now an undo means that the buffer is modified. */ void u_unchanged(buf) buf_T *buf; { u_unch_branch(buf->b_u_oldhead); buf->b_did_warn = FALSE; } /* * After reloading a buffer which was saved for 'undoreload': Find the first * line that was changed and set the cursor there. */ void u_find_first_changed() { u_header_T *uhp = curbuf->b_u_newhead; u_entry_T *uep; linenr_T lnum; if (curbuf->b_u_curhead != NULL || uhp == NULL) return; /* undid something in an autocmd? */ /* Check that the last undo block was for the whole file. */ uep = uhp->uh_entry; if (uep->ue_top != 0 || uep->ue_bot != 0) return; for (lnum = 1; lnum < curbuf->b_ml.ml_line_count && lnum <= uep->ue_size; ++lnum) if (STRCMP(ml_get_buf(curbuf, lnum, FALSE), uep->ue_array[lnum - 1]) != 0) { clearpos(&(uhp->uh_cursor)); uhp->uh_cursor.lnum = lnum; return; } if (curbuf->b_ml.ml_line_count != uep->ue_size) { /* lines added or deleted at the end, put the cursor there */ clearpos(&(uhp->uh_cursor)); uhp->uh_cursor.lnum = lnum; } } /* * Increase the write count, store it in the last undo header, what would be * used for "u". */ void u_update_save_nr(buf) buf_T *buf; { u_header_T *uhp; ++buf->b_u_save_nr_last; buf->b_u_save_nr_cur = buf->b_u_save_nr_last; uhp = buf->b_u_curhead; if (uhp != NULL) uhp = uhp->uh_next.ptr; else uhp = buf->b_u_newhead; if (uhp != NULL) uhp->uh_save_nr = buf->b_u_save_nr_last; } static void u_unch_branch(uhp) u_header_T *uhp; { u_header_T *uh; for (uh = uhp; uh != NULL; uh = uh->uh_prev.ptr) { uh->uh_flags |= UH_CHANGED; if (uh->uh_alt_next.ptr != NULL) u_unch_branch(uh->uh_alt_next.ptr); /* recursive */ } } /* * Get pointer to last added entry. * If it's not valid, give an error message and return NULL. */ static u_entry_T * u_get_headentry() { if (curbuf->b_u_newhead == NULL || curbuf->b_u_newhead->uh_entry == NULL) { EMSG(_("E439: undo list corrupt")); return NULL; } return curbuf->b_u_newhead->uh_entry; } /* * u_getbot(): compute the line number of the previous u_save * It is called only when b_u_synced is FALSE. */ static void u_getbot() { u_entry_T *uep; linenr_T extra; uep = u_get_headentry(); /* check for corrupt undo list */ if (uep == NULL) return; uep = curbuf->b_u_newhead->uh_getbot_entry; if (uep != NULL) { /* * the new ue_bot is computed from the number of lines that has been * inserted (0 - deleted) since calling u_save. This is equal to the * old line count subtracted from the current line count. */ extra = curbuf->b_ml.ml_line_count - uep->ue_lcount; uep->ue_bot = uep->ue_top + uep->ue_size + 1 + extra; if (uep->ue_bot < 1 || uep->ue_bot > curbuf->b_ml.ml_line_count) { EMSG(_("E440: undo line missing")); uep->ue_bot = uep->ue_top + 1; /* assume all lines deleted, will * get all the old lines back * without deleting the current * ones */ } curbuf->b_u_newhead->uh_getbot_entry = NULL; } curbuf->b_u_synced = TRUE; } /* * Free one header "uhp" and its entry list and adjust the pointers. */ static void u_freeheader(buf, uhp, uhpp) buf_T *buf; u_header_T *uhp; u_header_T **uhpp; /* if not NULL reset when freeing this header */ { u_header_T *uhap; /* When there is an alternate redo list free that branch completely, * because we can never go there. */ if (uhp->uh_alt_next.ptr != NULL) u_freebranch(buf, uhp->uh_alt_next.ptr, uhpp); if (uhp->uh_alt_prev.ptr != NULL) uhp->uh_alt_prev.ptr->uh_alt_next.ptr = NULL; /* Update the links in the list to remove the header. */ if (uhp->uh_next.ptr == NULL) buf->b_u_oldhead = uhp->uh_prev.ptr; else uhp->uh_next.ptr->uh_prev.ptr = uhp->uh_prev.ptr; if (uhp->uh_prev.ptr == NULL) buf->b_u_newhead = uhp->uh_next.ptr; else for (uhap = uhp->uh_prev.ptr; uhap != NULL; uhap = uhap->uh_alt_next.ptr) uhap->uh_next.ptr = uhp->uh_next.ptr; u_freeentries(buf, uhp, uhpp); } /* * Free an alternate branch and any following alternate branches. */ static void u_freebranch(buf, uhp, uhpp) buf_T *buf; u_header_T *uhp; u_header_T **uhpp; /* if not NULL reset when freeing this header */ { u_header_T *tofree, *next; /* If this is the top branch we may need to use u_freeheader() to update * all the pointers. */ if (uhp == buf->b_u_oldhead) { u_freeheader(buf, uhp, uhpp); return; } if (uhp->uh_alt_prev.ptr != NULL) uhp->uh_alt_prev.ptr->uh_alt_next.ptr = NULL; next = uhp; while (next != NULL) { tofree = next; if (tofree->uh_alt_next.ptr != NULL) u_freebranch(buf, tofree->uh_alt_next.ptr, uhpp); /* recursive */ next = tofree->uh_prev.ptr; u_freeentries(buf, tofree, uhpp); } } /* * Free all the undo entries for one header and the header itself. * This means that "uhp" is invalid when returning. */ static void u_freeentries(buf, uhp, uhpp) buf_T *buf; u_header_T *uhp; u_header_T **uhpp; /* if not NULL reset when freeing this header */ { u_entry_T *uep, *nuep; /* Check for pointers to the header that become invalid now. */ if (buf->b_u_curhead == uhp) buf->b_u_curhead = NULL; if (buf->b_u_newhead == uhp) buf->b_u_newhead = NULL; /* freeing the newest entry */ if (uhpp != NULL && uhp == *uhpp) *uhpp = NULL; for (uep = uhp->uh_entry; uep != NULL; uep = nuep) { nuep = uep->ue_next; u_freeentry(uep, uep->ue_size); } #ifdef U_DEBUG uhp->uh_magic = 0; #endif vim_free((char_u *)uhp); --buf->b_u_numhead; } /* * free entry 'uep' and 'n' lines in uep->ue_array[] */ static void u_freeentry(uep, n) u_entry_T *uep; long n; { while (n > 0) vim_free(uep->ue_array[--n]); vim_free((char_u *)uep->ue_array); #ifdef U_DEBUG uep->ue_magic = 0; #endif vim_free((char_u *)uep); } /* * invalidate the undo buffer; called when storage has already been released */ void u_clearall(buf) buf_T *buf; { buf->b_u_newhead = buf->b_u_oldhead = buf->b_u_curhead = NULL; buf->b_u_synced = TRUE; buf->b_u_numhead = 0; buf->b_u_line_ptr = NULL; buf->b_u_line_lnum = 0; } /* * save the line "lnum" for the "U" command */ void u_saveline(lnum) linenr_T lnum; { if (lnum == curbuf->b_u_line_lnum) /* line is already saved */ return; if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count) /* should never happen */ return; u_clearline(); curbuf->b_u_line_lnum = lnum; if (curwin->w_cursor.lnum == lnum) curbuf->b_u_line_colnr = curwin->w_cursor.col; else curbuf->b_u_line_colnr = 0; if ((curbuf->b_u_line_ptr = u_save_line(lnum)) == NULL) do_outofmem_msg((long_u)0); } /* * clear the line saved for the "U" command * (this is used externally for crossing a line while in insert mode) */ void u_clearline() { if (curbuf->b_u_line_ptr != NULL) { vim_free(curbuf->b_u_line_ptr); curbuf->b_u_line_ptr = NULL; curbuf->b_u_line_lnum = 0; } } /* * Implementation of the "U" command. * Differentiation from vi: "U" can be undone with the next "U". * We also allow the cursor to be in another line. * Careful: may trigger autocommands that reload the buffer. */ void u_undoline() { colnr_T t; char_u *oldp; if (undo_off) return; if (curbuf->b_u_line_ptr == NULL || curbuf->b_u_line_lnum > curbuf->b_ml.ml_line_count) { beep_flush(); return; } /* first save the line for the 'u' command */ if (u_savecommon(curbuf->b_u_line_lnum - 1, curbuf->b_u_line_lnum + 1, (linenr_T)0, FALSE) == FAIL) return; oldp = u_save_line(curbuf->b_u_line_lnum); if (oldp == NULL) { do_outofmem_msg((long_u)0); return; } ml_replace(curbuf->b_u_line_lnum, curbuf->b_u_line_ptr, TRUE); changed_bytes(curbuf->b_u_line_lnum, 0); vim_free(curbuf->b_u_line_ptr); curbuf->b_u_line_ptr = oldp; t = curbuf->b_u_line_colnr; if (curwin->w_cursor.lnum == curbuf->b_u_line_lnum) curbuf->b_u_line_colnr = curwin->w_cursor.col; curwin->w_cursor.col = t; curwin->w_cursor.lnum = curbuf->b_u_line_lnum; check_cursor_col(); } /* * Free all allocated memory blocks for the buffer 'buf'. */ void u_blockfree(buf) buf_T *buf; { while (buf->b_u_oldhead != NULL) u_freeheader(buf, buf->b_u_oldhead, NULL); vim_free(buf->b_u_line_ptr); } /* * u_save_line(): allocate memory and copy line 'lnum' into it. * Returns NULL when out of memory. */ static char_u * u_save_line(lnum) linenr_T lnum; { return vim_strsave(ml_get(lnum)); } /* * Check if the 'modified' flag is set, or 'ff' has changed (only need to * check the first character, because it can only be "dos", "unix" or "mac"). * "nofile" and "scratch" type buffers are considered to always be unchanged. */ int bufIsChanged(buf) buf_T *buf; { return #ifdef FEAT_QUICKFIX !bt_dontwrite(buf) && #endif (buf->b_changed || file_ff_differs(buf, TRUE)); } int curbufIsChanged() { return #ifdef FEAT_QUICKFIX !bt_dontwrite(curbuf) && #endif (curbuf->b_changed || file_ff_differs(curbuf, TRUE)); } #if defined(FEAT_EVAL) || defined(PROTO) /* * For undotree(): Append the list of undo blocks at "first_uhp" to "list". * Recursive. */ void u_eval_tree(first_uhp, list) u_header_T *first_uhp; list_T *list; { u_header_T *uhp = first_uhp; dict_T *dict; while (uhp != NULL) { dict = dict_alloc(); if (dict == NULL) return; dict_add_nr_str(dict, "seq", uhp->uh_seq, NULL); dict_add_nr_str(dict, "time", (long)uhp->uh_time, NULL); if (uhp == curbuf->b_u_newhead) dict_add_nr_str(dict, "newhead", 1, NULL); if (uhp == curbuf->b_u_curhead) dict_add_nr_str(dict, "curhead", 1, NULL); if (uhp->uh_save_nr > 0) dict_add_nr_str(dict, "save", uhp->uh_save_nr, NULL); if (uhp->uh_alt_next.ptr != NULL) { list_T *alt_list = list_alloc(); if (alt_list != NULL) { /* Recursive call to add alternate undo tree. */ u_eval_tree(uhp->uh_alt_next.ptr, alt_list); dict_add_list(dict, "alt", alt_list); } } list_append_dict(list, dict); uhp = uhp->uh_prev.ptr; } } #endif
zyz2011-vim
src/undo.c
C
gpl2
84,608
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * GUI/Motif support by Robert Webb * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * Icons used by the toolbar code. */ #include "../pixmaps/tb_new.xpm" #include "../pixmaps/tb_open.xpm" #include "../pixmaps/tb_close.xpm" #include "../pixmaps/tb_save.xpm" #include "../pixmaps/tb_print.xpm" #include "../pixmaps/tb_cut.xpm" #include "../pixmaps/tb_copy.xpm" #include "../pixmaps/tb_paste.xpm" #include "../pixmaps/tb_find.xpm" #include "../pixmaps/tb_find_next.xpm" #include "../pixmaps/tb_find_prev.xpm" #include "../pixmaps/tb_find_help.xpm" #include "../pixmaps/tb_exit.xpm" #include "../pixmaps/tb_undo.xpm" #include "../pixmaps/tb_redo.xpm" #include "../pixmaps/tb_help.xpm" #include "../pixmaps/tb_macro.xpm" #include "../pixmaps/tb_make.xpm" #include "../pixmaps/tb_save_all.xpm" #include "../pixmaps/tb_jump.xpm" #include "../pixmaps/tb_ctags.xpm" #include "../pixmaps/tb_load_session.xpm" #include "../pixmaps/tb_save_session.xpm" #include "../pixmaps/tb_new_session.xpm" #include "../pixmaps/tb_blank.xpm" #include "../pixmaps/tb_maximize.xpm" #include "../pixmaps/tb_split.xpm" #include "../pixmaps/tb_minimize.xpm" #include "../pixmaps/tb_shell.xpm" #include "../pixmaps/tb_replace.xpm" #include "../pixmaps/tb_vsplit.xpm" #include "../pixmaps/tb_maxwidth.xpm" #include "../pixmaps/tb_minwidth.xpm" /* * Those are the pixmaps used for the default buttons. */ static char **(built_in_pixmaps[]) = { tb_new_xpm, tb_open_xpm, tb_save_xpm, tb_undo_xpm, tb_redo_xpm, tb_cut_xpm, tb_copy_xpm, tb_paste_xpm, tb_print_xpm, tb_help_xpm, tb_find_xpm, tb_save_all_xpm, tb_save_session_xpm, tb_new_session_xpm, tb_load_session_xpm, tb_macro_xpm, tb_replace_xpm, tb_close_xpm, tb_maximize_xpm, tb_minimize_xpm, tb_split_xpm, tb_shell_xpm, tb_find_prev_xpm, tb_find_next_xpm, tb_find_help_xpm, tb_make_xpm, tb_jump_xpm, tb_ctags_xpm, tb_vsplit_xpm, tb_maxwidth_xpm, tb_minwidth_xpm, tb_exit_xpm }; /* Indices for named colors */ #define BACKGROUND 0 #define FOREGROUND 1 #define BOTTOM_SHADOW 2 #define TOP_SHADOW 3 #define HIGHLIGHT 4
zyz2011-vim
src/gui_x11_pm.h
C
gpl2
2,400
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * GUI support by Robert Webb * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * gui_w48.c: This file is included in gui_w16.c and gui_w32.c. * * GUI support for Microsoft Windows (Win16 + Win32 = Win48 :-) * * The combined efforts of: * George V. Reilly <george@reilly.org> * Robert Webb * Vince Negri * ...and contributions from many others * */ #include "vim.h" #include "version.h" /* used by dialog box routine for default title */ #ifdef DEBUG # include <tchar.h> #endif #ifndef __MINGW32__ # include <shellapi.h> #endif #if defined(FEAT_TOOLBAR) || defined(FEAT_BEVAL) || defined(FEAT_GUI_TABLINE) # include <commctrl.h> #endif #ifdef WIN16 # include <commdlg.h> # include <shellapi.h> # ifdef WIN16_3DLOOK # include <ctl3d.h> # endif #endif #include <windowsx.h> #ifdef GLOBAL_IME # include "glbl_ime.h" #endif #ifdef FEAT_MENU # define MENUHINTS /* show menu hints in command line */ #endif /* Some parameters for dialog boxes. All in pixels. */ #define DLG_PADDING_X 10 #define DLG_PADDING_Y 10 #define DLG_OLD_STYLE_PADDING_X 5 #define DLG_OLD_STYLE_PADDING_Y 5 #define DLG_VERT_PADDING_X 4 /* For vertical buttons */ #define DLG_VERT_PADDING_Y 4 #define DLG_ICON_WIDTH 34 #define DLG_ICON_HEIGHT 34 #define DLG_MIN_WIDTH 150 #define DLG_FONT_NAME "MS Sans Serif" #define DLG_FONT_POINT_SIZE 8 #define DLG_MIN_MAX_WIDTH 400 #define DLG_MIN_MAX_HEIGHT 400 #define DLG_NONBUTTON_CONTROL 5000 /* First ID of non-button controls */ #ifndef WM_XBUTTONDOWN /* For Win2K / winME ONLY */ # define WM_XBUTTONDOWN 0x020B # define WM_XBUTTONUP 0x020C # define WM_XBUTTONDBLCLK 0x020D # define MK_XBUTTON1 0x0020 # define MK_XBUTTON2 0x0040 #endif #ifdef PROTO /* * Define a few things for generating prototypes. This is just to avoid * syntax errors, the defines do not need to be correct. */ # define APIENTRY # define CALLBACK # define CONST # define FAR # define NEAR # define _cdecl typedef int BOOL; typedef int BYTE; typedef int DWORD; typedef int WCHAR; typedef int ENUMLOGFONT; typedef int FINDREPLACE; typedef int HANDLE; typedef int HBITMAP; typedef int HBRUSH; typedef int HDROP; typedef int INT; typedef int LOGFONT[]; typedef int LPARAM; typedef int LPCREATESTRUCT; typedef int LPCSTR; typedef int LPCTSTR; typedef int LPRECT; typedef int LPSTR; typedef int LPWINDOWPOS; typedef int LPWORD; typedef int LRESULT; typedef int HRESULT; # undef MSG typedef int MSG; typedef int NEWTEXTMETRIC; typedef int OSVERSIONINFO; typedef int PWORD; typedef int RECT; typedef int UINT; typedef int WORD; typedef int WPARAM; typedef int POINT; typedef void *HINSTANCE; typedef void *HMENU; typedef void *HWND; typedef void *HDC; typedef void VOID; typedef int LPNMHDR; typedef int LONG; #endif #ifndef GET_X_LPARAM # define GET_X_LPARAM(lp) ((int)(short)LOWORD(lp)) #endif static void _OnPaint( HWND hwnd); static void clear_rect(RECT *rcp); static int gui_mswin_get_menu_height(int fix_window); static WORD s_dlgfntheight; /* height of the dialog font */ static WORD s_dlgfntwidth; /* width of the dialog font */ #ifdef FEAT_MENU static HMENU s_menuBar = NULL; #endif #ifdef FEAT_TEAROFF static void rebuild_tearoff(vimmenu_T *menu); static HBITMAP s_htearbitmap; /* bitmap used to indicate tearoff */ #endif /* Flag that is set while processing a message that must not be interrupted by * processing another message. */ static int s_busy_processing = FALSE; static int destroying = FALSE; /* call DestroyWindow() ourselves */ #ifdef MSWIN_FIND_REPLACE static UINT s_findrep_msg = 0; /* set in gui_w[16/32].c */ static FINDREPLACE s_findrep_struct; # if defined(FEAT_MBYTE) && defined(WIN3264) static FINDREPLACEW s_findrep_struct_w; # endif static HWND s_findrep_hwnd = NULL; static int s_findrep_is_find; /* TRUE for find dialog, FALSE for find/replace dialog */ #endif static HINSTANCE s_hinst = NULL; #if !defined(FEAT_SNIFF) && !defined(FEAT_GUI) static #endif HWND s_hwnd = NULL; static HDC s_hdc = NULL; static HBRUSH s_brush = NULL; #ifdef FEAT_TOOLBAR static HWND s_toolbarhwnd = NULL; #endif #ifdef FEAT_GUI_TABLINE static HWND s_tabhwnd = NULL; static int showing_tabline = 0; #endif static WPARAM s_wParam = 0; static LPARAM s_lParam = 0; static HWND s_textArea = NULL; static UINT s_uMsg = 0; static char_u *s_textfield; /* Used by dialogs to pass back strings */ static int s_need_activate = FALSE; /* This variable is set when waiting for an event, which is the only moment * scrollbar dragging can be done directly. It's not allowed while commands * are executed, because it may move the cursor and that may cause unexpected * problems (e.g., while ":s" is working). */ static int allow_scrollbar = FALSE; #ifdef GLOBAL_IME # define MyTranslateMessage(x) global_ime_TranslateMessage(x) #else # define MyTranslateMessage(x) TranslateMessage(x) #endif #if (defined(WIN3264) && defined(FEAT_MBYTE)) || defined(GLOBAL_IME) /* use of WindowProc depends on wide_WindowProc */ # define MyWindowProc vim_WindowProc #else /* use ordinary WindowProc */ # define MyWindowProc DefWindowProc #endif extern int current_font_height; /* this is in os_mswin.c */ static struct { UINT key_sym; char_u vim_code0; char_u vim_code1; } special_keys[] = { {VK_UP, 'k', 'u'}, {VK_DOWN, 'k', 'd'}, {VK_LEFT, 'k', 'l'}, {VK_RIGHT, 'k', 'r'}, {VK_F1, 'k', '1'}, {VK_F2, 'k', '2'}, {VK_F3, 'k', '3'}, {VK_F4, 'k', '4'}, {VK_F5, 'k', '5'}, {VK_F6, 'k', '6'}, {VK_F7, 'k', '7'}, {VK_F8, 'k', '8'}, {VK_F9, 'k', '9'}, {VK_F10, 'k', ';'}, {VK_F11, 'F', '1'}, {VK_F12, 'F', '2'}, {VK_F13, 'F', '3'}, {VK_F14, 'F', '4'}, {VK_F15, 'F', '5'}, {VK_F16, 'F', '6'}, {VK_F17, 'F', '7'}, {VK_F18, 'F', '8'}, {VK_F19, 'F', '9'}, {VK_F20, 'F', 'A'}, {VK_F21, 'F', 'B'}, #ifdef FEAT_NETBEANS_INTG {VK_PAUSE, 'F', 'B'}, /* Pause == F21 (see gui_gtk_x11.c) */ #endif {VK_F22, 'F', 'C'}, {VK_F23, 'F', 'D'}, {VK_F24, 'F', 'E'}, /* winuser.h defines up to F24 */ {VK_HELP, '%', '1'}, {VK_BACK, 'k', 'b'}, {VK_INSERT, 'k', 'I'}, {VK_DELETE, 'k', 'D'}, {VK_HOME, 'k', 'h'}, {VK_END, '@', '7'}, {VK_PRIOR, 'k', 'P'}, {VK_NEXT, 'k', 'N'}, {VK_PRINT, '%', '9'}, {VK_ADD, 'K', '6'}, {VK_SUBTRACT, 'K', '7'}, {VK_DIVIDE, 'K', '8'}, {VK_MULTIPLY, 'K', '9'}, {VK_SEPARATOR, 'K', 'A'}, /* Keypad Enter */ {VK_DECIMAL, 'K', 'B'}, {VK_NUMPAD0, 'K', 'C'}, {VK_NUMPAD1, 'K', 'D'}, {VK_NUMPAD2, 'K', 'E'}, {VK_NUMPAD3, 'K', 'F'}, {VK_NUMPAD4, 'K', 'G'}, {VK_NUMPAD5, 'K', 'H'}, {VK_NUMPAD6, 'K', 'I'}, {VK_NUMPAD7, 'K', 'J'}, {VK_NUMPAD8, 'K', 'K'}, {VK_NUMPAD9, 'K', 'L'}, /* Keys that we want to be able to use any modifier with: */ {VK_SPACE, ' ', NUL}, {VK_TAB, TAB, NUL}, {VK_ESCAPE, ESC, NUL}, {NL, NL, NUL}, {CAR, CAR, NUL}, /* End of list marker: */ {0, 0, 0} }; /* Local variables */ static int s_button_pending = -1; /* s_getting_focus is set when we got focus but didn't see mouse-up event yet, * so don't reset s_button_pending. */ static int s_getting_focus = FALSE; static int s_x_pending; static int s_y_pending; static UINT s_kFlags_pending; static UINT s_wait_timer = 0; /* Timer for get char from user */ static int s_timed_out = FALSE; static int dead_key = 0; /* 0 - no dead key, 1 - dead key pressed */ #ifdef WIN3264 static OSVERSIONINFO os_version; /* like it says. Init in gui_mch_init() */ #endif #ifdef FEAT_BEVAL /* balloon-eval WM_NOTIFY_HANDLER */ static void Handle_WM_Notify __ARGS((HWND hwnd, LPNMHDR pnmh)); static void TrackUserActivity __ARGS((UINT uMsg)); #endif /* * For control IME. */ #ifdef FEAT_MBYTE # ifdef USE_IM_CONTROL static LOGFONT norm_logfont; # endif #endif #ifdef FEAT_MBYTE_IME static LRESULT _OnImeNotify(HWND hWnd, DWORD dwCommand, DWORD dwData); #endif #if defined(FEAT_MBYTE) && defined(WIN3264) static char_u *convert_filter(char_u *s); #endif #ifdef DEBUG_PRINT_ERROR /* * Print out the last Windows error message */ static void print_windows_error(void) { LPVOID lpMsgBuf; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL); TRACE1("Error: %s\n", lpMsgBuf); LocalFree(lpMsgBuf); } #endif /* * Cursor blink functions. * * This is a simple state machine: * BLINK_NONE not blinking at all * BLINK_OFF blinking, cursor is not shown * BLINK_ON blinking, cursor is shown */ #define BLINK_NONE 0 #define BLINK_OFF 1 #define BLINK_ON 2 static int blink_state = BLINK_NONE; static long_u blink_waittime = 700; static long_u blink_ontime = 400; static long_u blink_offtime = 250; static UINT blink_timer = 0; void gui_mch_set_blinking(long wait, long on, long off) { blink_waittime = wait; blink_ontime = on; blink_offtime = off; } /* ARGSUSED */ static VOID CALLBACK _OnBlinkTimer( HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime) { MSG msg; /* TRACE2("Got timer event, id %d, blink_timer %d\n", idEvent, blink_timer); */ KillTimer(NULL, idEvent); /* Eat spurious WM_TIMER messages */ while (pPeekMessage(&msg, hwnd, WM_TIMER, WM_TIMER, PM_REMOVE)) ; if (blink_state == BLINK_ON) { gui_undraw_cursor(); blink_state = BLINK_OFF; blink_timer = (UINT) SetTimer(NULL, 0, (UINT)blink_offtime, (TIMERPROC)_OnBlinkTimer); } else { gui_update_cursor(TRUE, FALSE); blink_state = BLINK_ON; blink_timer = (UINT) SetTimer(NULL, 0, (UINT)blink_ontime, (TIMERPROC)_OnBlinkTimer); } } static void gui_mswin_rm_blink_timer(void) { MSG msg; if (blink_timer != 0) { KillTimer(NULL, blink_timer); /* Eat spurious WM_TIMER messages */ while (pPeekMessage(&msg, s_hwnd, WM_TIMER, WM_TIMER, PM_REMOVE)) ; blink_timer = 0; } } /* * Stop the cursor blinking. Show the cursor if it wasn't shown. */ void gui_mch_stop_blink(void) { gui_mswin_rm_blink_timer(); if (blink_state == BLINK_OFF) gui_update_cursor(TRUE, FALSE); blink_state = BLINK_NONE; } /* * Start the cursor blinking. If it was already blinking, this restarts the * waiting time and shows the cursor. */ void gui_mch_start_blink(void) { gui_mswin_rm_blink_timer(); /* Only switch blinking on if none of the times is zero */ if (blink_waittime && blink_ontime && blink_offtime && gui.in_focus) { blink_timer = (UINT)SetTimer(NULL, 0, (UINT)blink_waittime, (TIMERPROC)_OnBlinkTimer); blink_state = BLINK_ON; gui_update_cursor(TRUE, FALSE); } } /* * Call-back routines. */ /*ARGSUSED*/ static VOID CALLBACK _OnTimer( HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime) { MSG msg; /* TRACE2("Got timer event, id %d, s_wait_timer %d\n", idEvent, s_wait_timer); */ KillTimer(NULL, idEvent); s_timed_out = TRUE; /* Eat spurious WM_TIMER messages */ while (pPeekMessage(&msg, hwnd, WM_TIMER, WM_TIMER, PM_REMOVE)) ; if (idEvent == s_wait_timer) s_wait_timer = 0; } /*ARGSUSED*/ static void _OnDeadChar( HWND hwnd, UINT ch, int cRepeat) { dead_key = 1; } /* * Convert Unicode character "ch" to bytes in "string[slen]". * When "had_alt" is TRUE the ALT key was included in "ch". * Return the length. */ static int char_to_string(int ch, char_u *string, int slen, int had_alt) { int len; int i; #ifdef FEAT_MBYTE WCHAR wstring[2]; char_u *ws = NULL;; if (os_version.dwPlatformId != VER_PLATFORM_WIN32_NT) { /* On Windows 95/98 we apparently get the character in the active * codepage, not in UCS-2. If conversion is needed convert it to * UCS-2 first. */ if ((int)GetACP() == enc_codepage) len = 0; /* no conversion required */ else { string[0] = ch; len = MultiByteToWideChar(GetACP(), 0, string, 1, wstring, 2); } } else { wstring[0] = ch; len = 1; } if (len > 0) { /* "ch" is a UTF-16 character. Convert it to a string of bytes. When * "enc_codepage" is non-zero use the standard Win32 function, * otherwise use our own conversion function (e.g., for UTF-8). */ if (enc_codepage > 0) { len = WideCharToMultiByte(enc_codepage, 0, wstring, len, string, slen, 0, NULL); /* If we had included the ALT key into the character but now the * upper bit is no longer set, that probably means the conversion * failed. Convert the original character and set the upper bit * afterwards. */ if (had_alt && len == 1 && ch >= 0x80 && string[0] < 0x80) { wstring[0] = ch & 0x7f; len = WideCharToMultiByte(enc_codepage, 0, wstring, len, string, slen, 0, NULL); if (len == 1) /* safety check */ string[0] |= 0x80; } } else { len = 1; ws = utf16_to_enc(wstring, &len); if (ws == NULL) len = 0; else { if (len > slen) /* just in case */ len = slen; mch_memmove(string, ws, len); vim_free(ws); } } } if (len == 0) #endif { string[0] = ch; len = 1; } for (i = 0; i < len; ++i) if (string[i] == CSI && len <= slen - 2) { /* Insert CSI as K_CSI. */ mch_memmove(string + i + 3, string + i + 1, len - i - 1); string[++i] = KS_EXTRA; string[++i] = (int)KE_CSI; len += 2; } return len; } /* * Key hit, add it to the input buffer. */ /*ARGSUSED*/ static void _OnChar( HWND hwnd, UINT ch, int cRepeat) { char_u string[40]; int len = 0; len = char_to_string(ch, string, 40, FALSE); if (len == 1 && string[0] == Ctrl_C && ctrl_c_interrupts) { trash_input_buf(); got_int = TRUE; } add_to_input_buf(string, len); } /* * Alt-Key hit, add it to the input buffer. */ /*ARGSUSED*/ static void _OnSysChar( HWND hwnd, UINT cch, int cRepeat) { char_u string[40]; /* Enough for multibyte character */ int len; int modifiers; int ch = cch; /* special keys are negative */ /* TRACE("OnSysChar(%d, %c)\n", ch, ch); */ /* OK, we have a character key (given by ch) which was entered with the * ALT key pressed. Eg, if the user presses Alt-A, then ch == 'A'. Note * that the system distinguishes Alt-a and Alt-A (Alt-Shift-a unless * CAPSLOCK is pressed) at this point. */ modifiers = MOD_MASK_ALT; if (GetKeyState(VK_SHIFT) & 0x8000) modifiers |= MOD_MASK_SHIFT; if (GetKeyState(VK_CONTROL) & 0x8000) modifiers |= MOD_MASK_CTRL; ch = simplify_key(ch, &modifiers); /* remove the SHIFT modifier for keys where it's already included, e.g., * '(' and '*' */ if (ch < 0x100 && !isalpha(ch) && isprint(ch)) modifiers &= ~MOD_MASK_SHIFT; /* Interpret the ALT key as making the key META, include SHIFT, etc. */ ch = extract_modifiers(ch, &modifiers); if (ch == CSI) ch = K_CSI; len = 0; if (modifiers) { string[len++] = CSI; string[len++] = KS_MODIFIER; string[len++] = modifiers; } if (IS_SPECIAL((int)ch)) { string[len++] = CSI; string[len++] = K_SECOND((int)ch); string[len++] = K_THIRD((int)ch); } else { /* Although the documentation isn't clear about it, we assume "ch" is * a Unicode character. */ len += char_to_string(ch, string + len, 40 - len, TRUE); } add_to_input_buf(string, len); } static void _OnMouseEvent( int button, int x, int y, int repeated_click, UINT keyFlags) { int vim_modifiers = 0x0; s_getting_focus = FALSE; if (keyFlags & MK_SHIFT) vim_modifiers |= MOUSE_SHIFT; if (keyFlags & MK_CONTROL) vim_modifiers |= MOUSE_CTRL; if (GetKeyState(VK_MENU) & 0x8000) vim_modifiers |= MOUSE_ALT; gui_send_mouse_event(button, x, y, repeated_click, vim_modifiers); } /*ARGSUSED*/ static void _OnMouseButtonDown( HWND hwnd, BOOL fDoubleClick, int x, int y, UINT keyFlags) { static LONG s_prevTime = 0; LONG currentTime = GetMessageTime(); int button = -1; int repeated_click; /* Give main window the focus: this is so the cursor isn't hollow. */ (void)SetFocus(s_hwnd); if (s_uMsg == WM_LBUTTONDOWN || s_uMsg == WM_LBUTTONDBLCLK) button = MOUSE_LEFT; else if (s_uMsg == WM_MBUTTONDOWN || s_uMsg == WM_MBUTTONDBLCLK) button = MOUSE_MIDDLE; else if (s_uMsg == WM_RBUTTONDOWN || s_uMsg == WM_RBUTTONDBLCLK) button = MOUSE_RIGHT; #ifndef WIN16 /*<VN>*/ else if (s_uMsg == WM_XBUTTONDOWN || s_uMsg == WM_XBUTTONDBLCLK) { #ifndef GET_XBUTTON_WPARAM # define GET_XBUTTON_WPARAM(wParam) (HIWORD(wParam)) #endif button = ((GET_XBUTTON_WPARAM(s_wParam) == 1) ? MOUSE_X1 : MOUSE_X2); } else if (s_uMsg == WM_CAPTURECHANGED) { /* on W95/NT4, somehow you get in here with an odd Msg * if you press one button while holding down the other..*/ if (s_button_pending == MOUSE_LEFT) button = MOUSE_RIGHT; else button = MOUSE_LEFT; } #endif if (button >= 0) { repeated_click = ((int)(currentTime - s_prevTime) < p_mouset); /* * Holding down the left and right buttons simulates pushing the middle * button. */ if (repeated_click && ((button == MOUSE_LEFT && s_button_pending == MOUSE_RIGHT) || (button == MOUSE_RIGHT && s_button_pending == MOUSE_LEFT))) { /* * Hmm, gui.c will ignore more than one button down at a time, so * pretend we let go of it first. */ gui_send_mouse_event(MOUSE_RELEASE, x, y, FALSE, 0x0); button = MOUSE_MIDDLE; repeated_click = FALSE; s_button_pending = -1; _OnMouseEvent(button, x, y, repeated_click, keyFlags); } else if ((repeated_click) || (mouse_model_popup() && (button == MOUSE_RIGHT))) { if (s_button_pending > -1) { _OnMouseEvent(s_button_pending, x, y, FALSE, keyFlags); s_button_pending = -1; } /* TRACE("Button down at x %d, y %d\n", x, y); */ _OnMouseEvent(button, x, y, repeated_click, keyFlags); } else { /* * If this is the first press (i.e. not a multiple click) don't * action immediately, but store and wait for: * i) button-up * ii) mouse move * iii) another button press * before using it. * This enables us to make left+right simulate middle button, * without left or right being actioned first. The side-effect is * that if you click and hold the mouse without dragging, the * cursor doesn't move until you release the button. In practice * this is hardly a problem. */ s_button_pending = button; s_x_pending = x; s_y_pending = y; s_kFlags_pending = keyFlags; } s_prevTime = currentTime; } } /*ARGSUSED*/ static void _OnMouseMoveOrRelease( HWND hwnd, int x, int y, UINT keyFlags) { int button; s_getting_focus = FALSE; if (s_button_pending > -1) { /* Delayed action for mouse down event */ _OnMouseEvent(s_button_pending, s_x_pending, s_y_pending, FALSE, s_kFlags_pending); s_button_pending = -1; } if (s_uMsg == WM_MOUSEMOVE) { /* * It's only a MOUSE_DRAG if one or more mouse buttons are being held * down. */ if (!(keyFlags & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON | MK_XBUTTON1 | MK_XBUTTON2))) { gui_mouse_moved(x, y); return; } /* * While button is down, keep grabbing mouse move events when * the mouse goes outside the window */ SetCapture(s_textArea); button = MOUSE_DRAG; /* TRACE(" move at x %d, y %d\n", x, y); */ } else { ReleaseCapture(); button = MOUSE_RELEASE; /* TRACE(" up at x %d, y %d\n", x, y); */ } _OnMouseEvent(button, x, y, FALSE, keyFlags); } #ifdef FEAT_MENU /* * Find the vimmenu_T with the given id */ static vimmenu_T * gui_mswin_find_menu( vimmenu_T *pMenu, int id) { vimmenu_T *pChildMenu; while (pMenu) { if (pMenu->id == (UINT)id) break; if (pMenu->children != NULL) { pChildMenu = gui_mswin_find_menu(pMenu->children, id); if (pChildMenu) { pMenu = pChildMenu; break; } } pMenu = pMenu->next; } return pMenu; } /*ARGSUSED*/ static void _OnMenu( HWND hwnd, int id, HWND hwndCtl, UINT codeNotify) { vimmenu_T *pMenu; pMenu = gui_mswin_find_menu(root_menu, id); if (pMenu) gui_menu_cb(pMenu); } #endif #ifdef MSWIN_FIND_REPLACE # if defined(FEAT_MBYTE) && defined(WIN3264) /* * copy useful data from structure LPFINDREPLACE to structure LPFINDREPLACEW */ static void findrep_atow(LPFINDREPLACEW lpfrw, LPFINDREPLACE lpfr) { WCHAR *wp; lpfrw->hwndOwner = lpfr->hwndOwner; lpfrw->Flags = lpfr->Flags; wp = enc_to_utf16(lpfr->lpstrFindWhat, NULL); wcsncpy(lpfrw->lpstrFindWhat, wp, lpfrw->wFindWhatLen - 1); vim_free(wp); /* the field "lpstrReplaceWith" doesn't need to be copied */ } /* * copy useful data from structure LPFINDREPLACEW to structure LPFINDREPLACE */ static void findrep_wtoa(LPFINDREPLACE lpfr, LPFINDREPLACEW lpfrw) { char_u *p; lpfr->Flags = lpfrw->Flags; p = utf16_to_enc(lpfrw->lpstrFindWhat, NULL); vim_strncpy(lpfr->lpstrFindWhat, p, lpfr->wFindWhatLen - 1); vim_free(p); p = utf16_to_enc(lpfrw->lpstrReplaceWith, NULL); vim_strncpy(lpfr->lpstrReplaceWith, p, lpfr->wReplaceWithLen - 1); vim_free(p); } # endif /* * Handle a Find/Replace window message. */ static void _OnFindRepl(void) { int flags = 0; int down; # if defined(FEAT_MBYTE) && defined(WIN3264) /* If the OS is Windows NT, and 'encoding' differs from active codepage: * convert text from wide string. */ if (os_version.dwPlatformId == VER_PLATFORM_WIN32_NT && enc_codepage >= 0 && (int)GetACP() != enc_codepage) { findrep_wtoa(&s_findrep_struct, &s_findrep_struct_w); } # endif if (s_findrep_struct.Flags & FR_DIALOGTERM) /* Give main window the focus back. */ (void)SetFocus(s_hwnd); if (s_findrep_struct.Flags & FR_FINDNEXT) { flags = FRD_FINDNEXT; /* Give main window the focus back: this is so the cursor isn't * hollow. */ (void)SetFocus(s_hwnd); } else if (s_findrep_struct.Flags & FR_REPLACE) { flags = FRD_REPLACE; /* Give main window the focus back: this is so the cursor isn't * hollow. */ (void)SetFocus(s_hwnd); } else if (s_findrep_struct.Flags & FR_REPLACEALL) { flags = FRD_REPLACEALL; } if (flags != 0) { /* Call the generic GUI function to do the actual work. */ if (s_findrep_struct.Flags & FR_WHOLEWORD) flags |= FRD_WHOLE_WORD; if (s_findrep_struct.Flags & FR_MATCHCASE) flags |= FRD_MATCH_CASE; down = (s_findrep_struct.Flags & FR_DOWN) != 0; gui_do_findrepl(flags, s_findrep_struct.lpstrFindWhat, s_findrep_struct.lpstrReplaceWith, down); } } #endif static void HandleMouseHide(UINT uMsg, LPARAM lParam) { static LPARAM last_lParam = 0L; /* We sometimes get a mousemove when the mouse didn't move... */ if (uMsg == WM_MOUSEMOVE) { if (lParam == last_lParam) return; last_lParam = lParam; } /* Handle specially, to centralise coding. We need to be sure we catch all * possible events which should cause us to restore the cursor (as it is a * shared resource, we take full responsibility for it). */ switch (uMsg) { case WM_KEYUP: case WM_CHAR: /* * blank out the pointer if necessary */ if (p_mh) gui_mch_mousehide(TRUE); break; case WM_SYSKEYUP: /* show the pointer when a system-key is pressed */ case WM_SYSCHAR: case WM_MOUSEMOVE: /* show the pointer on any mouse action */ case WM_LBUTTONDOWN: case WM_LBUTTONUP: case WM_MBUTTONDOWN: case WM_MBUTTONUP: case WM_RBUTTONDOWN: case WM_RBUTTONUP: case WM_XBUTTONDOWN: case WM_XBUTTONUP: case WM_NCMOUSEMOVE: case WM_NCLBUTTONDOWN: case WM_NCLBUTTONUP: case WM_NCMBUTTONDOWN: case WM_NCMBUTTONUP: case WM_NCRBUTTONDOWN: case WM_NCRBUTTONUP: case WM_KILLFOCUS: /* * if the pointer is currently hidden, then we should show it. */ gui_mch_mousehide(FALSE); break; } } static LRESULT CALLBACK _TextAreaWndProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { /* TRACE("TextAreaWndProc: hwnd = %08x, msg = %x, wParam = %x, lParam = %x\n", hwnd, uMsg, wParam, lParam); */ HandleMouseHide(uMsg, lParam); s_uMsg = uMsg; s_wParam = wParam; s_lParam = lParam; #ifdef FEAT_BEVAL TrackUserActivity(uMsg); #endif switch (uMsg) { HANDLE_MSG(hwnd, WM_LBUTTONDBLCLK,_OnMouseButtonDown); HANDLE_MSG(hwnd, WM_LBUTTONDOWN,_OnMouseButtonDown); HANDLE_MSG(hwnd, WM_LBUTTONUP, _OnMouseMoveOrRelease); HANDLE_MSG(hwnd, WM_MBUTTONDBLCLK,_OnMouseButtonDown); HANDLE_MSG(hwnd, WM_MBUTTONDOWN,_OnMouseButtonDown); HANDLE_MSG(hwnd, WM_MBUTTONUP, _OnMouseMoveOrRelease); HANDLE_MSG(hwnd, WM_MOUSEMOVE, _OnMouseMoveOrRelease); HANDLE_MSG(hwnd, WM_PAINT, _OnPaint); HANDLE_MSG(hwnd, WM_RBUTTONDBLCLK,_OnMouseButtonDown); HANDLE_MSG(hwnd, WM_RBUTTONDOWN,_OnMouseButtonDown); HANDLE_MSG(hwnd, WM_RBUTTONUP, _OnMouseMoveOrRelease); #ifndef WIN16 /*<VN>*/ HANDLE_MSG(hwnd, WM_XBUTTONDBLCLK,_OnMouseButtonDown); HANDLE_MSG(hwnd, WM_XBUTTONDOWN,_OnMouseButtonDown); HANDLE_MSG(hwnd, WM_XBUTTONUP, _OnMouseMoveOrRelease); #endif #ifdef FEAT_BEVAL case WM_NOTIFY: Handle_WM_Notify(hwnd, (LPNMHDR)lParam); return TRUE; #endif default: return MyWindowProc(hwnd, uMsg, wParam, lParam); } } #if (defined(WIN3264) && defined(FEAT_MBYTE)) \ || defined(GLOBAL_IME) \ || defined(PROTO) # ifdef PROTO typedef int WINAPI; # endif LRESULT WINAPI vim_WindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { # ifdef GLOBAL_IME return global_ime_DefWindowProc(hwnd, message, wParam, lParam); # else if (wide_WindowProc) return DefWindowProcW(hwnd, message, wParam, lParam); return DefWindowProc(hwnd, message, wParam, lParam); #endif } #endif /* * Called when the foreground or background color has been changed. */ void gui_mch_new_colors(void) { /* nothing to do? */ } /* * Set the colors to their default values. */ void gui_mch_def_colors() { gui.norm_pixel = GetSysColor(COLOR_WINDOWTEXT); gui.back_pixel = GetSysColor(COLOR_WINDOW); gui.def_norm_pixel = gui.norm_pixel; gui.def_back_pixel = gui.back_pixel; } /* * Open the GUI window which was created by a call to gui_mch_init(). */ int gui_mch_open(void) { #ifndef SW_SHOWDEFAULT # define SW_SHOWDEFAULT 10 /* Borland 5.0 doesn't have it */ #endif /* Actually open the window, if not already visible * (may be done already in gui_mch_set_shellsize) */ if (!IsWindowVisible(s_hwnd)) ShowWindow(s_hwnd, SW_SHOWDEFAULT); #ifdef MSWIN_FIND_REPLACE /* Init replace string here, so that we keep it when re-opening the * dialog. */ s_findrep_struct.lpstrReplaceWith[0] = NUL; #endif return OK; } /* * Get the position of the top left corner of the window. */ int gui_mch_get_winpos(int *x, int *y) { RECT rect; GetWindowRect(s_hwnd, &rect); *x = rect.left; *y = rect.top; return OK; } /* * Set the position of the top left corner of the window to the given * coordinates. */ void gui_mch_set_winpos(int x, int y) { SetWindowPos(s_hwnd, NULL, x, y, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE); } void gui_mch_set_text_area_pos(int x, int y, int w, int h) { static int oldx = 0; static int oldy = 0; SetWindowPos(s_textArea, NULL, x, y, w, h, SWP_NOZORDER | SWP_NOACTIVATE); #ifdef FEAT_TOOLBAR if (vim_strchr(p_go, GO_TOOLBAR) != NULL) SendMessage(s_toolbarhwnd, WM_SIZE, (WPARAM)0, (LPARAM)(w + ((long)(TOOLBAR_BUTTON_HEIGHT+8)<<16))); #endif #if defined(FEAT_GUI_TABLINE) if (showing_tabline) { int top = 0; RECT rect; # ifdef FEAT_TOOLBAR if (vim_strchr(p_go, GO_TOOLBAR) != NULL) top = TOOLBAR_BUTTON_HEIGHT + TOOLBAR_BORDER_HEIGHT; # endif GetClientRect(s_hwnd, &rect); MoveWindow(s_tabhwnd, 0, top, rect.right, gui.tabline_height, TRUE); } #endif /* When side scroll bar is unshown, the size of window will change. * then, the text area move left or right. thus client rect should be * forcely redraw. (Yasuhiro Matsumoto) */ if (oldx != x || oldy != y) { InvalidateRect(s_hwnd, NULL, FALSE); oldx = x; oldy = y; } } /* * Scrollbar stuff: */ void gui_mch_enable_scrollbar( scrollbar_T *sb, int flag) { ShowScrollBar(sb->id, SB_CTL, flag); /* TODO: When the window is maximized, the size of the window stays the * same, thus the size of the text area changes. On Win98 it's OK, on Win * NT 4.0 it's not... */ } void gui_mch_set_scrollbar_pos( scrollbar_T *sb, int x, int y, int w, int h) { SetWindowPos(sb->id, NULL, x, y, w, h, SWP_NOZORDER | SWP_NOACTIVATE | SWP_SHOWWINDOW); } void gui_mch_create_scrollbar( scrollbar_T *sb, int orient) /* SBAR_VERT or SBAR_HORIZ */ { sb->id = CreateWindow( "SCROLLBAR", "Scrollbar", WS_CHILD | ((orient == SBAR_VERT) ? SBS_VERT : SBS_HORZ), 0, 0, 10, /* Any value will do for now */ 10, /* Any value will do for now */ s_hwnd, NULL, s_hinst, NULL); } /* * Find the scrollbar with the given hwnd. */ static scrollbar_T * gui_mswin_find_scrollbar(HWND hwnd) { win_T *wp; if (gui.bottom_sbar.id == hwnd) return &gui.bottom_sbar; FOR_ALL_WINDOWS(wp) { if (wp->w_scrollbars[SBAR_LEFT].id == hwnd) return &wp->w_scrollbars[SBAR_LEFT]; if (wp->w_scrollbars[SBAR_RIGHT].id == hwnd) return &wp->w_scrollbars[SBAR_RIGHT]; } return NULL; } /* * Get the character size of a font. */ static void GetFontSize(GuiFont font) { HWND hwnd = GetDesktopWindow(); HDC hdc = GetWindowDC(hwnd); HFONT hfntOld = SelectFont(hdc, (HFONT)font); TEXTMETRIC tm; GetTextMetrics(hdc, &tm); gui.char_width = tm.tmAveCharWidth + tm.tmOverhang; gui.char_height = tm.tmHeight #ifndef MSWIN16_FASTTEXT + p_linespace #endif ; SelectFont(hdc, hfntOld); ReleaseDC(hwnd, hdc); } /* * Adjust gui.char_height (after 'linespace' was changed). */ int gui_mch_adjust_charheight(void) { GetFontSize(gui.norm_font); return OK; } static GuiFont get_font_handle(LOGFONT *lf) { HFONT font = NULL; /* Load the font */ font = CreateFontIndirect(lf); if (font == NULL) return NOFONT; return (GuiFont)font; } static int pixels_to_points(int pixels, int vertical) { int points; HWND hwnd; HDC hdc; hwnd = GetDesktopWindow(); hdc = GetWindowDC(hwnd); points = MulDiv(pixels, 72, GetDeviceCaps(hdc, vertical ? LOGPIXELSY : LOGPIXELSX)); ReleaseDC(hwnd, hdc); return points; } GuiFont gui_mch_get_font( char_u *name, int giveErrorIfMissing) { LOGFONT lf; GuiFont font = NOFONT; if (get_logfont(&lf, name, NULL, giveErrorIfMissing) == OK) font = get_font_handle(&lf); if (font == NOFONT && giveErrorIfMissing) EMSG2(_(e_font), name); return font; } #if defined(FEAT_EVAL) || defined(PROTO) /* * Return the name of font "font" in allocated memory. * Don't know how to get the actual name, thus use the provided name. */ /*ARGSUSED*/ char_u * gui_mch_get_fontname(font, name) GuiFont font; char_u *name; { if (name == NULL) return NULL; return vim_strsave(name); } #endif void gui_mch_free_font(GuiFont font) { if (font) DeleteObject((HFONT)font); } static int hex_digit(int c) { if (VIM_ISDIGIT(c)) return c - '0'; c = TOLOWER_ASC(c); if (c >= 'a' && c <= 'f') return c - 'a' + 10; return -1000; } /* * Return the Pixel value (color) for the given color name. * Return INVALCOLOR for error. */ guicolor_T gui_mch_get_color(char_u *name) { typedef struct guicolor_tTable { char *name; COLORREF color; } guicolor_tTable; static guicolor_tTable table[] = { {"Black", RGB(0x00, 0x00, 0x00)}, {"DarkGray", RGB(0xA9, 0xA9, 0xA9)}, {"DarkGrey", RGB(0xA9, 0xA9, 0xA9)}, {"Gray", RGB(0xC0, 0xC0, 0xC0)}, {"Grey", RGB(0xC0, 0xC0, 0xC0)}, {"LightGray", RGB(0xD3, 0xD3, 0xD3)}, {"LightGrey", RGB(0xD3, 0xD3, 0xD3)}, {"Gray10", RGB(0x1A, 0x1A, 0x1A)}, {"Grey10", RGB(0x1A, 0x1A, 0x1A)}, {"Gray20", RGB(0x33, 0x33, 0x33)}, {"Grey20", RGB(0x33, 0x33, 0x33)}, {"Gray30", RGB(0x4D, 0x4D, 0x4D)}, {"Grey30", RGB(0x4D, 0x4D, 0x4D)}, {"Gray40", RGB(0x66, 0x66, 0x66)}, {"Grey40", RGB(0x66, 0x66, 0x66)}, {"Gray50", RGB(0x7F, 0x7F, 0x7F)}, {"Grey50", RGB(0x7F, 0x7F, 0x7F)}, {"Gray60", RGB(0x99, 0x99, 0x99)}, {"Grey60", RGB(0x99, 0x99, 0x99)}, {"Gray70", RGB(0xB3, 0xB3, 0xB3)}, {"Grey70", RGB(0xB3, 0xB3, 0xB3)}, {"Gray80", RGB(0xCC, 0xCC, 0xCC)}, {"Grey80", RGB(0xCC, 0xCC, 0xCC)}, {"Gray90", RGB(0xE5, 0xE5, 0xE5)}, {"Grey90", RGB(0xE5, 0xE5, 0xE5)}, {"White", RGB(0xFF, 0xFF, 0xFF)}, {"DarkRed", RGB(0x80, 0x00, 0x00)}, {"Red", RGB(0xFF, 0x00, 0x00)}, {"LightRed", RGB(0xFF, 0xA0, 0xA0)}, {"DarkBlue", RGB(0x00, 0x00, 0x80)}, {"Blue", RGB(0x00, 0x00, 0xFF)}, {"LightBlue", RGB(0xAD, 0xD8, 0xE6)}, {"DarkGreen", RGB(0x00, 0x80, 0x00)}, {"Green", RGB(0x00, 0xFF, 0x00)}, {"LightGreen", RGB(0x90, 0xEE, 0x90)}, {"DarkCyan", RGB(0x00, 0x80, 0x80)}, {"Cyan", RGB(0x00, 0xFF, 0xFF)}, {"LightCyan", RGB(0xE0, 0xFF, 0xFF)}, {"DarkMagenta", RGB(0x80, 0x00, 0x80)}, {"Magenta", RGB(0xFF, 0x00, 0xFF)}, {"LightMagenta", RGB(0xFF, 0xA0, 0xFF)}, {"Brown", RGB(0x80, 0x40, 0x40)}, {"Yellow", RGB(0xFF, 0xFF, 0x00)}, {"LightYellow", RGB(0xFF, 0xFF, 0xE0)}, {"DarkYellow", RGB(0xBB, 0xBB, 0x00)}, {"SeaGreen", RGB(0x2E, 0x8B, 0x57)}, {"Orange", RGB(0xFF, 0xA5, 0x00)}, {"Purple", RGB(0xA0, 0x20, 0xF0)}, {"SlateBlue", RGB(0x6A, 0x5A, 0xCD)}, {"Violet", RGB(0xEE, 0x82, 0xEE)}, }; typedef struct SysColorTable { char *name; int color; } SysColorTable; static SysColorTable sys_table[] = { #ifdef WIN3264 {"SYS_3DDKSHADOW", COLOR_3DDKSHADOW}, {"SYS_3DHILIGHT", COLOR_3DHILIGHT}, #ifndef __MINGW32__ {"SYS_3DHIGHLIGHT", COLOR_3DHIGHLIGHT}, #endif {"SYS_BTNHILIGHT", COLOR_BTNHILIGHT}, {"SYS_BTNHIGHLIGHT", COLOR_BTNHIGHLIGHT}, {"SYS_3DLIGHT", COLOR_3DLIGHT}, {"SYS_3DSHADOW", COLOR_3DSHADOW}, {"SYS_DESKTOP", COLOR_DESKTOP}, {"SYS_INFOBK", COLOR_INFOBK}, {"SYS_INFOTEXT", COLOR_INFOTEXT}, {"SYS_3DFACE", COLOR_3DFACE}, #endif {"SYS_BTNFACE", COLOR_BTNFACE}, {"SYS_BTNSHADOW", COLOR_BTNSHADOW}, {"SYS_ACTIVEBORDER", COLOR_ACTIVEBORDER}, {"SYS_ACTIVECAPTION", COLOR_ACTIVECAPTION}, {"SYS_APPWORKSPACE", COLOR_APPWORKSPACE}, {"SYS_BACKGROUND", COLOR_BACKGROUND}, {"SYS_BTNTEXT", COLOR_BTNTEXT}, {"SYS_CAPTIONTEXT", COLOR_CAPTIONTEXT}, {"SYS_GRAYTEXT", COLOR_GRAYTEXT}, {"SYS_HIGHLIGHT", COLOR_HIGHLIGHT}, {"SYS_HIGHLIGHTTEXT", COLOR_HIGHLIGHTTEXT}, {"SYS_INACTIVEBORDER", COLOR_INACTIVEBORDER}, {"SYS_INACTIVECAPTION", COLOR_INACTIVECAPTION}, {"SYS_INACTIVECAPTIONTEXT", COLOR_INACTIVECAPTIONTEXT}, {"SYS_MENU", COLOR_MENU}, {"SYS_MENUTEXT", COLOR_MENUTEXT}, {"SYS_SCROLLBAR", COLOR_SCROLLBAR}, {"SYS_WINDOW", COLOR_WINDOW}, {"SYS_WINDOWFRAME", COLOR_WINDOWFRAME}, {"SYS_WINDOWTEXT", COLOR_WINDOWTEXT} }; int r, g, b; int i; if (name[0] == '#' && strlen(name) == 7) { /* Name is in "#rrggbb" format */ r = hex_digit(name[1]) * 16 + hex_digit(name[2]); g = hex_digit(name[3]) * 16 + hex_digit(name[4]); b = hex_digit(name[5]) * 16 + hex_digit(name[6]); if (r < 0 || g < 0 || b < 0) return INVALCOLOR; return RGB(r, g, b); } else { /* Check if the name is one of the colors we know */ for (i = 0; i < sizeof(table) / sizeof(table[0]); i++) if (STRICMP(name, table[i].name) == 0) return table[i].color; } /* * Try to look up a system colour. */ for (i = 0; i < sizeof(sys_table) / sizeof(sys_table[0]); i++) if (STRICMP(name, sys_table[i].name) == 0) return GetSysColor(sys_table[i].color); /* * Last attempt. Look in the file "$VIMRUNTIME/rgb.txt". */ { #define LINE_LEN 100 FILE *fd; char line[LINE_LEN]; char_u *fname; fname = expand_env_save((char_u *)"$VIMRUNTIME/rgb.txt"); if (fname == NULL) return INVALCOLOR; fd = mch_fopen((char *)fname, "rt"); vim_free(fname); if (fd == NULL) return INVALCOLOR; while (!feof(fd)) { int len; int pos; char *color; fgets(line, LINE_LEN, fd); len = (int)STRLEN(line); if (len <= 1 || line[len-1] != '\n') continue; line[len-1] = '\0'; i = sscanf(line, "%d %d %d %n", &r, &g, &b, &pos); if (i != 3) continue; color = line + pos; if (STRICMP(color, name) == 0) { fclose(fd); return (guicolor_T) RGB(r, g, b); } } fclose(fd); } return INVALCOLOR; } /* * Return OK if the key with the termcap name "name" is supported. */ int gui_mch_haskey(char_u *name) { int i; for (i = 0; special_keys[i].vim_code1 != NUL; i++) if (name[0] == special_keys[i].vim_code0 && name[1] == special_keys[i].vim_code1) return OK; return FAIL; } void gui_mch_beep(void) { MessageBeep(MB_OK); } /* * Invert a rectangle from row r, column c, for nr rows and nc columns. */ void gui_mch_invert_rectangle( int r, int c, int nr, int nc) { RECT rc; /* * Note: InvertRect() excludes right and bottom of rectangle. */ rc.left = FILL_X(c); rc.top = FILL_Y(r); rc.right = rc.left + nc * gui.char_width; rc.bottom = rc.top + nr * gui.char_height; InvertRect(s_hdc, &rc); } /* * Iconify the GUI window. */ void gui_mch_iconify(void) { ShowWindow(s_hwnd, SW_MINIMIZE); } /* * Draw a cursor without focus. */ void gui_mch_draw_hollow_cursor(guicolor_T color) { HBRUSH hbr; RECT rc; /* * Note: FrameRect() excludes right and bottom of rectangle. */ rc.left = FILL_X(gui.col); rc.top = FILL_Y(gui.row); rc.right = rc.left + gui.char_width; #ifdef FEAT_MBYTE if (mb_lefthalve(gui.row, gui.col)) rc.right += gui.char_width; #endif rc.bottom = rc.top + gui.char_height; hbr = CreateSolidBrush(color); FrameRect(s_hdc, &rc, hbr); DeleteBrush(hbr); } /* * Draw part of a cursor, "w" pixels wide, and "h" pixels high, using * color "color". */ void gui_mch_draw_part_cursor( int w, int h, guicolor_T color) { HBRUSH hbr; RECT rc; /* * Note: FillRect() excludes right and bottom of rectangle. */ rc.left = #ifdef FEAT_RIGHTLEFT /* vertical line should be on the right of current point */ CURSOR_BAR_RIGHT ? FILL_X(gui.col + 1) - w : #endif FILL_X(gui.col); rc.top = FILL_Y(gui.row) + gui.char_height - h; rc.right = rc.left + w; rc.bottom = rc.top + h; hbr = CreateSolidBrush(color); FillRect(s_hdc, &rc, hbr); DeleteBrush(hbr); } /* * Process a single Windows message. * If one is not available we hang until one is. */ static void process_message(void) { MSG msg; UINT vk = 0; /* Virtual key */ char_u string[40]; int i; int modifiers = 0; int key; #ifdef FEAT_MENU static char_u k10[] = {K_SPECIAL, 'k', ';', 0}; #endif pGetMessage(&msg, NULL, 0, 0); #ifdef FEAT_OLE /* Look after OLE Automation commands */ if (msg.message == WM_OLE) { char_u *str = (char_u *)msg.lParam; if (str == NULL || *str == NUL) { /* Message can't be ours, forward it. Fixes problem with Ultramon * 3.0.4 */ pDispatchMessage(&msg); } else { add_to_input_buf(str, (int)STRLEN(str)); vim_free(str); /* was allocated in CVim::SendKeys() */ } return; } #endif #ifdef FEAT_NETBEANS_INTG if (msg.message == WM_NETBEANS) { netbeans_read(); return; } #endif #ifdef FEAT_SNIFF if (sniff_request_waiting && want_sniff_request) { static char_u bytes[3] = {CSI, (char_u)KS_EXTRA, (char_u)KE_SNIFF}; add_to_input_buf(bytes, 3); /* K_SNIFF */ sniff_request_waiting = 0; want_sniff_request = 0; /* request is handled in normal.c */ } if (msg.message == WM_USER) { MyTranslateMessage(&msg); pDispatchMessage(&msg); return; } #endif #ifdef MSWIN_FIND_REPLACE /* Don't process messages used by the dialog */ if (s_findrep_hwnd != NULL && pIsDialogMessage(s_findrep_hwnd, &msg)) { HandleMouseHide(msg.message, msg.lParam); return; } #endif /* * Check if it's a special key that we recognise. If not, call * TranslateMessage(). */ if (msg.message == WM_KEYDOWN || msg.message == WM_SYSKEYDOWN) { vk = (int) msg.wParam; /* handle key after dead key, but ignore shift, alt and control */ if (dead_key && vk != VK_SHIFT && vk != VK_MENU && vk != VK_CONTROL) { dead_key = 0; /* handle non-alphabetic keys (ones that hopefully cannot generate * umlaut-characters), unless when control is down */ if (vk < 'A' || vk > 'Z' || (GetKeyState(VK_CONTROL) & 0x8000)) { MSG dm; dm.message = msg.message; dm.hwnd = msg.hwnd; dm.wParam = VK_SPACE; MyTranslateMessage(&dm); /* generate dead character */ if (vk != VK_SPACE) /* and send current character once more */ PostMessage(msg.hwnd, msg.message, msg.wParam, msg.lParam); return; } } /* Check for CTRL-BREAK */ if (vk == VK_CANCEL) { trash_input_buf(); got_int = TRUE; string[0] = Ctrl_C; add_to_input_buf(string, 1); } for (i = 0; special_keys[i].key_sym != 0; i++) { /* ignore VK_SPACE when ALT key pressed: system menu */ if (special_keys[i].key_sym == vk && (vk != VK_SPACE || !(GetKeyState(VK_MENU) & 0x8000))) { #ifdef FEAT_MENU /* Check for <F10>: Windows selects the menu. When <F10> is * mapped we want to use the mapping instead. */ if (vk == VK_F10 && gui.menu_is_active && check_map(k10, State, FALSE, TRUE, FALSE, NULL, NULL) == NULL) break; #endif if (GetKeyState(VK_SHIFT) & 0x8000) modifiers |= MOD_MASK_SHIFT; /* * Don't use caps-lock as shift, because these are special keys * being considered here, and we only want letters to get * shifted -- webb */ /* if (GetKeyState(VK_CAPITAL) & 0x0001) modifiers ^= MOD_MASK_SHIFT; */ if (GetKeyState(VK_CONTROL) & 0x8000) modifiers |= MOD_MASK_CTRL; if (GetKeyState(VK_MENU) & 0x8000) modifiers |= MOD_MASK_ALT; if (special_keys[i].vim_code1 == NUL) key = special_keys[i].vim_code0; else key = TO_SPECIAL(special_keys[i].vim_code0, special_keys[i].vim_code1); key = simplify_key(key, &modifiers); if (key == CSI) key = K_CSI; if (modifiers) { string[0] = CSI; string[1] = KS_MODIFIER; string[2] = modifiers; add_to_input_buf(string, 3); } if (IS_SPECIAL(key)) { string[0] = CSI; string[1] = K_SECOND(key); string[2] = K_THIRD(key); add_to_input_buf(string, 3); } else { int len; /* Handle "key" as a Unicode character. */ len = char_to_string(key, string, 40, FALSE); add_to_input_buf(string, len); } break; } } if (special_keys[i].key_sym == 0) { /* Some keys need C-S- where they should only need C-. * Ignore 0xff, Windows XP sends it when NUMLOCK has changed since * system startup (Helmut Stiegler, 2003 Oct 3). */ if (vk != 0xff && (GetKeyState(VK_CONTROL) & 0x8000) && !(GetKeyState(VK_SHIFT) & 0x8000) && !(GetKeyState(VK_MENU) & 0x8000)) { /* CTRL-6 is '^'; Japanese keyboard maps '^' to vk == 0xDE */ if (vk == '6' || MapVirtualKey(vk, 2) == (UINT)'^') { string[0] = Ctrl_HAT; add_to_input_buf(string, 1); } /* vk == 0xBD AZERTY for CTRL-'-', but CTRL-[ for * QWERTY! */ else if (vk == 0xBD) /* QWERTY for CTRL-'-' */ { string[0] = Ctrl__; add_to_input_buf(string, 1); } /* CTRL-2 is '@'; Japanese keyboard maps '@' to vk == 0xC0 */ else if (vk == '2' || MapVirtualKey(vk, 2) == (UINT)'@') { string[0] = Ctrl_AT; add_to_input_buf(string, 1); } else MyTranslateMessage(&msg); } else MyTranslateMessage(&msg); } } #ifdef FEAT_MBYTE_IME else if (msg.message == WM_IME_NOTIFY) _OnImeNotify(msg.hwnd, (DWORD)msg.wParam, (DWORD)msg.lParam); else if (msg.message == WM_KEYUP && im_get_status()) /* added for non-MS IME (Yasuhiro Matsumoto) */ MyTranslateMessage(&msg); #endif #if !defined(FEAT_MBYTE_IME) && defined(GLOBAL_IME) /* GIME_TEST */ else if (msg.message == WM_IME_STARTCOMPOSITION) { POINT point; global_ime_set_font(&norm_logfont); point.x = FILL_X(gui.col); point.y = FILL_Y(gui.row); MapWindowPoints(s_textArea, s_hwnd, &point, 1); global_ime_set_position(&point); } #endif #ifdef FEAT_MENU /* Check for <F10>: Default effect is to select the menu. When <F10> is * mapped we need to stop it here to avoid strange effects (e.g., for the * key-up event) */ if (vk != VK_F10 || check_map(k10, State, FALSE, TRUE, FALSE, NULL, NULL) == NULL) #endif pDispatchMessage(&msg); } /* * Catch up with any queued events. This may put keyboard input into the * input buffer, call resize call-backs, trigger timers etc. If there is * nothing in the event queue (& no timers pending), then we return * immediately. */ void gui_mch_update(void) { MSG msg; if (!s_busy_processing) while (pPeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE) && !vim_is_input_buf_full()) process_message(); } /* * GUI input routine called by gui_wait_for_chars(). Waits for a character * from the keyboard. * wtime == -1 Wait forever. * wtime == 0 This should never happen. * wtime > 0 Wait wtime milliseconds for a character. * Returns OK if a character was found to be available within the given time, * or FAIL otherwise. */ int gui_mch_wait_for_chars(int wtime) { MSG msg; int focus; s_timed_out = FALSE; if (wtime > 0) { /* Don't do anything while processing a (scroll) message. */ if (s_busy_processing) return FAIL; s_wait_timer = (UINT)SetTimer(NULL, 0, (UINT)wtime, (TIMERPROC)_OnTimer); } allow_scrollbar = TRUE; focus = gui.in_focus; while (!s_timed_out) { /* Stop or start blinking when focus changes */ if (gui.in_focus != focus) { if (gui.in_focus) gui_mch_start_blink(); else gui_mch_stop_blink(); focus = gui.in_focus; } if (s_need_activate) { #ifdef WIN32 (void)SetForegroundWindow(s_hwnd); #else (void)SetActiveWindow(s_hwnd); #endif s_need_activate = FALSE; } #ifdef FEAT_NETBEANS_INTG /* Process the queued netbeans messages. */ netbeans_parse_messages(); #endif /* * Don't use gui_mch_update() because then we will spin-lock until a * char arrives, instead we use GetMessage() to hang until an * event arrives. No need to check for input_buf_full because we are * returning as soon as it contains a single char -- webb */ process_message(); if (input_available()) { if (s_wait_timer != 0 && !s_timed_out) { KillTimer(NULL, s_wait_timer); /* Eat spurious WM_TIMER messages */ while (pPeekMessage(&msg, s_hwnd, WM_TIMER, WM_TIMER, PM_REMOVE)) ; s_wait_timer = 0; } allow_scrollbar = FALSE; /* Clear pending mouse button, the release event may have been * taken by the dialog window. But don't do this when getting * focus, we need the mouse-up event then. */ if (!s_getting_focus) s_button_pending = -1; return OK; } } allow_scrollbar = FALSE; return FAIL; } /* * Clear a rectangular region of the screen from text pos (row1, col1) to * (row2, col2) inclusive. */ void gui_mch_clear_block( int row1, int col1, int row2, int col2) { RECT rc; /* * Clear one extra pixel at the far right, for when bold characters have * spilled over to the window border. * Note: FillRect() excludes right and bottom of rectangle. */ rc.left = FILL_X(col1); rc.top = FILL_Y(row1); rc.right = FILL_X(col2 + 1) + (col2 == Columns - 1); rc.bottom = FILL_Y(row2 + 1); clear_rect(&rc); } /* * Clear the whole text window. */ void gui_mch_clear_all(void) { RECT rc; rc.left = 0; rc.top = 0; rc.right = Columns * gui.char_width + 2 * gui.border_width; rc.bottom = Rows * gui.char_height + 2 * gui.border_width; clear_rect(&rc); } /* * Menu stuff. */ void gui_mch_enable_menu(int flag) { #ifdef FEAT_MENU SetMenu(s_hwnd, flag ? s_menuBar : NULL); #endif } /*ARGSUSED*/ void gui_mch_set_menu_pos( int x, int y, int w, int h) { /* It will be in the right place anyway */ } #if defined(FEAT_MENU) || defined(PROTO) /* * Make menu item hidden or not hidden */ void gui_mch_menu_hidden( vimmenu_T *menu, int hidden) { /* * This doesn't do what we want. Hmm, just grey the menu items for now. */ /* if (hidden) EnableMenuItem(s_menuBar, menu->id, MF_BYCOMMAND | MF_DISABLED); else EnableMenuItem(s_menuBar, menu->id, MF_BYCOMMAND | MF_ENABLED); */ gui_mch_menu_grey(menu, hidden); } /* * This is called after setting all the menus to grey/hidden or not. */ void gui_mch_draw_menubar(void) { DrawMenuBar(s_hwnd); } #endif /*FEAT_MENU*/ #ifndef PROTO void #ifdef VIMDLL _export #endif _cdecl SaveInst(HINSTANCE hInst) { s_hinst = hInst; } #endif /* * Return the RGB value of a pixel as a long. */ long_u gui_mch_get_rgb(guicolor_T pixel) { return (GetRValue(pixel) << 16) + (GetGValue(pixel) << 8) + GetBValue(pixel); } #if defined(FEAT_GUI_DIALOG) || defined(PROTO) /* Convert pixels in X to dialog units */ static WORD PixelToDialogX(int numPixels) { return (WORD)((numPixels * 4) / s_dlgfntwidth); } /* Convert pixels in Y to dialog units */ static WORD PixelToDialogY(int numPixels) { return (WORD)((numPixels * 8) / s_dlgfntheight); } /* Return the width in pixels of the given text in the given DC. */ static int GetTextWidth(HDC hdc, char_u *str, int len) { SIZE size; GetTextExtentPoint(hdc, str, len, &size); return size.cx; } #ifdef FEAT_MBYTE /* * Return the width in pixels of the given text in the given DC, taking care * of 'encoding' to active codepage conversion. */ static int GetTextWidthEnc(HDC hdc, char_u *str, int len) { SIZE size; WCHAR *wstr; int n; int wlen = len; if (enc_codepage >= 0 && (int)GetACP() != enc_codepage) { /* 'encoding' differs from active codepage: convert text and use wide * function */ wstr = enc_to_utf16(str, &wlen); if (wstr != NULL) { n = GetTextExtentPointW(hdc, wstr, wlen, &size); vim_free(wstr); if (n) return size.cx; } } return GetTextWidth(hdc, str, len); } #else # define GetTextWidthEnc(h, s, l) GetTextWidth((h), (s), (l)) #endif /* * A quick little routine that will center one window over another, handy for * dialog boxes. Taken from the Win32SDK samples. */ static BOOL CenterWindow( HWND hwndChild, HWND hwndParent) { RECT rChild, rParent; int wChild, hChild, wParent, hParent; int wScreen, hScreen, xNew, yNew; HDC hdc; GetWindowRect(hwndChild, &rChild); wChild = rChild.right - rChild.left; hChild = rChild.bottom - rChild.top; /* If Vim is minimized put the window in the middle of the screen. */ if (hwndParent == NULL || IsMinimized(hwndParent)) { #ifdef WIN16 rParent.left = 0; rParent.top = 0; rParent.right = GetSystemMetrics(SM_CXSCREEN); rParent.bottom = GetSystemMetrics(SM_CYFULLSCREEN); #else SystemParametersInfo(SPI_GETWORKAREA, 0, &rParent, 0); #endif } else GetWindowRect(hwndParent, &rParent); wParent = rParent.right - rParent.left; hParent = rParent.bottom - rParent.top; hdc = GetDC(hwndChild); wScreen = GetDeviceCaps (hdc, HORZRES); hScreen = GetDeviceCaps (hdc, VERTRES); ReleaseDC(hwndChild, hdc); xNew = rParent.left + ((wParent - wChild) /2); if (xNew < 0) { xNew = 0; } else if ((xNew+wChild) > wScreen) { xNew = wScreen - wChild; } yNew = rParent.top + ((hParent - hChild) /2); if (yNew < 0) yNew = 0; else if ((yNew+hChild) > hScreen) yNew = hScreen - hChild; return SetWindowPos(hwndChild, NULL, xNew, yNew, 0, 0, SWP_NOSIZE | SWP_NOZORDER); } #endif /* FEAT_GUI_DIALOG */ void gui_mch_activate_window(void) { (void)SetActiveWindow(s_hwnd); } #if defined(FEAT_TOOLBAR) || defined(PROTO) void gui_mch_show_toolbar(int showit) { if (s_toolbarhwnd == NULL) return; if (showit) { # ifdef FEAT_MBYTE # ifndef TB_SETUNICODEFORMAT /* For older compilers. We assume this never changes. */ # define TB_SETUNICODEFORMAT 0x2005 # endif /* Enable/disable unicode support */ int uu = (enc_codepage >= 0 && (int)GetACP() != enc_codepage); SendMessage(s_toolbarhwnd, TB_SETUNICODEFORMAT, (WPARAM)uu, (LPARAM)0); # endif ShowWindow(s_toolbarhwnd, SW_SHOW); } else ShowWindow(s_toolbarhwnd, SW_HIDE); } /* Then number of bitmaps is fixed. Exit is missing! */ #define TOOLBAR_BITMAP_COUNT 31 #endif #if defined(FEAT_GUI_TABLINE) || defined(PROTO) static void add_tabline_popup_menu_entry(HMENU pmenu, UINT item_id, char_u *item_text) { #ifdef FEAT_MBYTE WCHAR *wn = NULL; int n; if (enc_codepage >= 0 && (int)GetACP() != enc_codepage) { /* 'encoding' differs from active codepage: convert menu name * and use wide function */ wn = enc_to_utf16(item_text, NULL); if (wn != NULL) { MENUITEMINFOW infow; infow.cbSize = sizeof(infow); infow.fMask = MIIM_TYPE | MIIM_ID; infow.wID = item_id; infow.fType = MFT_STRING; infow.dwTypeData = wn; infow.cch = (UINT)wcslen(wn); n = InsertMenuItemW(pmenu, item_id, FALSE, &infow); vim_free(wn); if (n == 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED) /* Failed, try using non-wide function. */ wn = NULL; } } if (wn == NULL) #endif { MENUITEMINFO info; info.cbSize = sizeof(info); info.fMask = MIIM_TYPE | MIIM_ID; info.wID = item_id; info.fType = MFT_STRING; info.dwTypeData = item_text; info.cch = (UINT)STRLEN(item_text); InsertMenuItem(pmenu, item_id, FALSE, &info); } } static void show_tabline_popup_menu(void) { HMENU tab_pmenu; long rval; POINT pt; /* When ignoring events don't show the menu. */ if (hold_gui_events # ifdef FEAT_CMDWIN || cmdwin_type != 0 # endif ) return; tab_pmenu = CreatePopupMenu(); if (tab_pmenu == NULL) return; add_tabline_popup_menu_entry(tab_pmenu, TABLINE_MENU_CLOSE, _("Close tab")); add_tabline_popup_menu_entry(tab_pmenu, TABLINE_MENU_NEW, _("New tab")); add_tabline_popup_menu_entry(tab_pmenu, TABLINE_MENU_OPEN, _("Open tab...")); GetCursorPos(&pt); rval = TrackPopupMenuEx(tab_pmenu, TPM_RETURNCMD, pt.x, pt.y, s_tabhwnd, NULL); DestroyMenu(tab_pmenu); /* Add the string cmd into input buffer */ if (rval > 0) { TCHITTESTINFO htinfo; int idx; if (ScreenToClient(s_tabhwnd, &pt) == 0) return; htinfo.pt.x = pt.x; htinfo.pt.y = pt.y; idx = TabCtrl_HitTest(s_tabhwnd, &htinfo); if (idx == -1) idx = 0; else idx += 1; send_tabline_menu_event(idx, (int)rval); } } /* * Show or hide the tabline. */ void gui_mch_show_tabline(int showit) { if (s_tabhwnd == NULL) return; if (!showit != !showing_tabline) { if (showit) ShowWindow(s_tabhwnd, SW_SHOW); else ShowWindow(s_tabhwnd, SW_HIDE); showing_tabline = showit; } } /* * Return TRUE when tabline is displayed. */ int gui_mch_showing_tabline(void) { return s_tabhwnd != NULL && showing_tabline; } /* * Update the labels of the tabline. */ void gui_mch_update_tabline(void) { tabpage_T *tp; TCITEM tie; int nr = 0; int curtabidx = 0; RECT rc; #ifdef FEAT_MBYTE static int use_unicode = FALSE; int uu; WCHAR *wstr = NULL; #endif if (s_tabhwnd == NULL) return; #if defined(FEAT_MBYTE) # ifndef CCM_SETUNICODEFORMAT /* For older compilers. We assume this never changes. */ # define CCM_SETUNICODEFORMAT 0x2005 # endif uu = (enc_codepage >= 0 && (int)GetACP() != enc_codepage); if (uu != use_unicode) { /* Enable/disable unicode support */ SendMessage(s_tabhwnd, CCM_SETUNICODEFORMAT, (WPARAM)uu, (LPARAM)0); use_unicode = uu; } #endif tie.mask = TCIF_TEXT; tie.iImage = -1; /* Add a label for each tab page. They all contain the same text area. */ for (tp = first_tabpage; tp != NULL; tp = tp->tp_next, ++nr) { if (tp == curtab) curtabidx = nr; if (!TabCtrl_GetItemRect(s_tabhwnd, nr, &rc)) { /* Add the tab */ tie.pszText = "-Empty-"; TabCtrl_InsertItem(s_tabhwnd, nr, &tie); } get_tabline_label(tp, FALSE); tie.pszText = NameBuff; #ifdef FEAT_MBYTE wstr = NULL; if (use_unicode) { /* Need to go through Unicode. */ wstr = enc_to_utf16(NameBuff, NULL); if (wstr != NULL) { TCITEMW tiw; tiw.mask = TCIF_TEXT; tiw.iImage = -1; tiw.pszText = wstr; SendMessage(s_tabhwnd, TCM_SETITEMW, (WPARAM)nr, (LPARAM)&tiw); vim_free(wstr); } } if (wstr == NULL) #endif { TabCtrl_SetItem(s_tabhwnd, nr, &tie); } } /* Remove any old labels. */ while (TabCtrl_GetItemRect(s_tabhwnd, nr, &rc)) TabCtrl_DeleteItem(s_tabhwnd, nr); if (TabCtrl_GetCurSel(s_tabhwnd) != curtabidx) TabCtrl_SetCurSel(s_tabhwnd, curtabidx); } /* * Set the current tab to "nr". First tab is 1. */ void gui_mch_set_curtab(nr) int nr; { if (s_tabhwnd == NULL) return; if (TabCtrl_GetCurSel(s_tabhwnd) != nr -1) TabCtrl_SetCurSel(s_tabhwnd, nr -1); } #endif /* * ":simalt" command. */ void ex_simalt(exarg_T *eap) { char_u *keys = eap->arg; PostMessage(s_hwnd, WM_SYSCOMMAND, (WPARAM)SC_KEYMENU, (LPARAM)0); while (*keys) { if (*keys == '~') *keys = ' '; /* for showing system menu */ PostMessage(s_hwnd, WM_CHAR, (WPARAM)*keys, (LPARAM)0); keys++; } } /* * Create the find & replace dialogs. * You can't have both at once: ":find" when replace is showing, destroys * the replace dialog first, and the other way around. */ #ifdef MSWIN_FIND_REPLACE static void initialise_findrep(char_u *initial_string) { int wword = FALSE; int mcase = !p_ic; char_u *entry_text; /* Get the search string to use. */ entry_text = get_find_dialog_text(initial_string, &wword, &mcase); s_findrep_struct.hwndOwner = s_hwnd; s_findrep_struct.Flags = FR_DOWN; if (mcase) s_findrep_struct.Flags |= FR_MATCHCASE; if (wword) s_findrep_struct.Flags |= FR_WHOLEWORD; if (entry_text != NULL && *entry_text != NUL) vim_strncpy(s_findrep_struct.lpstrFindWhat, entry_text, s_findrep_struct.wFindWhatLen - 1); vim_free(entry_text); } #endif static void set_window_title(HWND hwnd, char *title) { #ifdef FEAT_MBYTE if (title != NULL && enc_codepage >= 0 && enc_codepage != (int)GetACP()) { WCHAR *wbuf; int n; /* Convert the title from 'encoding' to UTF-16. */ wbuf = (WCHAR *)enc_to_utf16((char_u *)title, NULL); if (wbuf != NULL) { n = SetWindowTextW(hwnd, wbuf); vim_free(wbuf); if (n != 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) return; /* Retry with non-wide function (for Windows 98). */ } } #endif (void)SetWindowText(hwnd, (LPCSTR)title); } void gui_mch_find_dialog(exarg_T *eap) { #ifdef MSWIN_FIND_REPLACE if (s_findrep_msg != 0) { if (IsWindow(s_findrep_hwnd) && !s_findrep_is_find) DestroyWindow(s_findrep_hwnd); if (!IsWindow(s_findrep_hwnd)) { initialise_findrep(eap->arg); # if defined(FEAT_MBYTE) && defined(WIN3264) /* If the OS is Windows NT, and 'encoding' differs from active * codepage: convert text and use wide function. */ if (os_version.dwPlatformId == VER_PLATFORM_WIN32_NT && enc_codepage >= 0 && (int)GetACP() != enc_codepage) { findrep_atow(&s_findrep_struct_w, &s_findrep_struct); s_findrep_hwnd = FindTextW( (LPFINDREPLACEW) &s_findrep_struct_w); } else # endif s_findrep_hwnd = FindText((LPFINDREPLACE) &s_findrep_struct); } set_window_title(s_findrep_hwnd, _("Find string (use '\\\\' to find a '\\')")); (void)SetFocus(s_findrep_hwnd); s_findrep_is_find = TRUE; } #endif } void gui_mch_replace_dialog(exarg_T *eap) { #ifdef MSWIN_FIND_REPLACE if (s_findrep_msg != 0) { if (IsWindow(s_findrep_hwnd) && s_findrep_is_find) DestroyWindow(s_findrep_hwnd); if (!IsWindow(s_findrep_hwnd)) { initialise_findrep(eap->arg); # if defined(FEAT_MBYTE) && defined(WIN3264) if (os_version.dwPlatformId == VER_PLATFORM_WIN32_NT && enc_codepage >= 0 && (int)GetACP() != enc_codepage) { findrep_atow(&s_findrep_struct_w, &s_findrep_struct); s_findrep_hwnd = ReplaceTextW( (LPFINDREPLACEW) &s_findrep_struct_w); } else # endif s_findrep_hwnd = ReplaceText( (LPFINDREPLACE) &s_findrep_struct); } set_window_title(s_findrep_hwnd, _("Find & Replace (use '\\\\' to find a '\\')")); (void)SetFocus(s_findrep_hwnd); s_findrep_is_find = FALSE; } #endif } /* * Set visibility of the pointer. */ void gui_mch_mousehide(int hide) { if (hide != gui.pointer_hidden) { ShowCursor(!hide); gui.pointer_hidden = hide; } } #ifdef FEAT_MENU static void gui_mch_show_popupmenu_at(vimmenu_T *menu, int x, int y) { /* Unhide the mouse, we don't get move events here. */ gui_mch_mousehide(FALSE); (void)TrackPopupMenu( (HMENU)menu->submenu_id, TPM_LEFTALIGN | TPM_LEFTBUTTON, x, y, (int)0, /*reserved param*/ s_hwnd, NULL); /* * NOTE: The pop-up menu can eat the mouse up event. * We deal with this in normal.c. */ } #endif /* * Got a message when the system will go down. */ static void _OnEndSession(void) { getout_preserve_modified(1); } /* * Get this message when the user clicks on the cross in the top right corner * of a Windows95 window. */ /*ARGSUSED*/ static void _OnClose( HWND hwnd) { gui_shell_closed(); } /* * Get a message when the window is being destroyed. */ static void _OnDestroy( HWND hwnd) { #ifdef WIN16_3DLOOK Ctl3dUnregister(s_hinst); #endif if (!destroying) _OnClose(hwnd); } static void _OnPaint( HWND hwnd) { if (!IsMinimized(hwnd)) { PAINTSTRUCT ps; out_flush(); /* make sure all output has been processed */ (void)BeginPaint(hwnd, &ps); #ifdef FEAT_MBYTE /* prevent multi-byte characters from misprinting on an invalid * rectangle */ if (has_mbyte) { RECT rect; GetClientRect(hwnd, &rect); ps.rcPaint.left = rect.left; ps.rcPaint.right = rect.right; } #endif if (!IsRectEmpty(&ps.rcPaint)) gui_redraw(ps.rcPaint.left, ps.rcPaint.top, ps.rcPaint.right - ps.rcPaint.left + 1, ps.rcPaint.bottom - ps.rcPaint.top + 1); EndPaint(hwnd, &ps); } } /*ARGSUSED*/ static void _OnSize( HWND hwnd, UINT state, int cx, int cy) { if (!IsMinimized(hwnd)) { gui_resize_shell(cx, cy); #ifdef FEAT_MENU /* Menu bar may wrap differently now */ gui_mswin_get_menu_height(TRUE); #endif } } static void _OnSetFocus( HWND hwnd, HWND hwndOldFocus) { gui_focus_change(TRUE); s_getting_focus = TRUE; (void)MyWindowProc(hwnd, WM_SETFOCUS, (WPARAM)hwndOldFocus, 0); } static void _OnKillFocus( HWND hwnd, HWND hwndNewFocus) { gui_focus_change(FALSE); s_getting_focus = FALSE; (void)MyWindowProc(hwnd, WM_KILLFOCUS, (WPARAM)hwndNewFocus, 0); } /* * Get a message when the user switches back to vim */ #ifdef WIN16 static BOOL #else static LRESULT #endif _OnActivateApp( HWND hwnd, BOOL fActivate, #ifdef WIN16 HTASK dwThreadId #else DWORD dwThreadId #endif ) { /* we call gui_focus_change() in _OnSetFocus() */ /* gui_focus_change((int)fActivate); */ return MyWindowProc(hwnd, WM_ACTIVATEAPP, fActivate, (DWORD)dwThreadId); } #if defined(FEAT_WINDOWS) || defined(PROTO) void gui_mch_destroy_scrollbar(scrollbar_T *sb) { DestroyWindow(sb->id); } #endif /* * Get current mouse coordinates in text window. */ void gui_mch_getmouse(int *x, int *y) { RECT rct; POINT mp; (void)GetWindowRect(s_textArea, &rct); (void)GetCursorPos((LPPOINT)&mp); *x = (int)(mp.x - rct.left); *y = (int)(mp.y - rct.top); } /* * Move mouse pointer to character at (x, y). */ void gui_mch_setmouse(int x, int y) { RECT rct; (void)GetWindowRect(s_textArea, &rct); (void)SetCursorPos(x + gui.border_offset + rct.left, y + gui.border_offset + rct.top); } static void gui_mswin_get_valid_dimensions( int w, int h, int *valid_w, int *valid_h) { int base_width, base_height; base_width = gui_get_base_width() + GetSystemMetrics(SM_CXFRAME) * 2; base_height = gui_get_base_height() + GetSystemMetrics(SM_CYFRAME) * 2 + GetSystemMetrics(SM_CYCAPTION) #ifdef FEAT_MENU + gui_mswin_get_menu_height(FALSE) #endif ; *valid_w = base_width + ((w - base_width) / gui.char_width) * gui.char_width; *valid_h = base_height + ((h - base_height) / gui.char_height) * gui.char_height; } void gui_mch_flash(int msec) { RECT rc; /* * Note: InvertRect() excludes right and bottom of rectangle. */ rc.left = 0; rc.top = 0; rc.right = gui.num_cols * gui.char_width; rc.bottom = gui.num_rows * gui.char_height; InvertRect(s_hdc, &rc); gui_mch_flush(); /* make sure it's displayed */ ui_delay((long)msec, TRUE); /* wait for a few msec */ InvertRect(s_hdc, &rc); } /* * Return flags used for scrolling. * The SW_INVALIDATE is required when part of the window is covered or * off-screen. Refer to MS KB Q75236. */ static int get_scroll_flags(void) { HWND hwnd; RECT rcVim, rcOther, rcDest; GetWindowRect(s_hwnd, &rcVim); /* Check if the window is partly above or below the screen. We don't care * about partly left or right of the screen, it is not relevant when * scrolling up or down. */ if (rcVim.top < 0 || rcVim.bottom > GetSystemMetrics(SM_CYFULLSCREEN)) return SW_INVALIDATE; /* Check if there is an window (partly) on top of us. */ for (hwnd = s_hwnd; (hwnd = GetWindow(hwnd, GW_HWNDPREV)) != (HWND)0; ) if (IsWindowVisible(hwnd)) { GetWindowRect(hwnd, &rcOther); if (IntersectRect(&rcDest, &rcVim, &rcOther)) return SW_INVALIDATE; } return 0; } /* * Delete the given number of lines from the given row, scrolling up any * text further down within the scroll region. */ void gui_mch_delete_lines( int row, int num_lines) { RECT rc; rc.left = FILL_X(gui.scroll_region_left); rc.right = FILL_X(gui.scroll_region_right + 1); rc.top = FILL_Y(row); rc.bottom = FILL_Y(gui.scroll_region_bot + 1); ScrollWindowEx(s_textArea, 0, -num_lines * gui.char_height, &rc, &rc, NULL, NULL, get_scroll_flags()); UpdateWindow(s_textArea); /* This seems to be required to avoid the cursor disappearing when * scrolling such that the cursor ends up in the top-left character on * the screen... But why? (Webb) */ /* It's probably fixed by disabling drawing the cursor while scrolling. */ /* gui.cursor_is_valid = FALSE; */ gui_clear_block(gui.scroll_region_bot - num_lines + 1, gui.scroll_region_left, gui.scroll_region_bot, gui.scroll_region_right); } /* * Insert the given number of lines before the given row, scrolling down any * following text within the scroll region. */ void gui_mch_insert_lines( int row, int num_lines) { RECT rc; rc.left = FILL_X(gui.scroll_region_left); rc.right = FILL_X(gui.scroll_region_right + 1); rc.top = FILL_Y(row); rc.bottom = FILL_Y(gui.scroll_region_bot + 1); /* The SW_INVALIDATE is required when part of the window is covered or * off-screen. How do we avoid it when it's not needed? */ ScrollWindowEx(s_textArea, 0, num_lines * gui.char_height, &rc, &rc, NULL, NULL, get_scroll_flags()); UpdateWindow(s_textArea); gui_clear_block(row, gui.scroll_region_left, row + num_lines - 1, gui.scroll_region_right); } /*ARGSUSED*/ void gui_mch_exit(int rc) { ReleaseDC(s_textArea, s_hdc); DeleteObject(s_brush); #ifdef FEAT_TEAROFF /* Unload the tearoff bitmap */ (void)DeleteObject((HGDIOBJ)s_htearbitmap); #endif /* Destroy our window (if we have one). */ if (s_hwnd != NULL) { destroying = TRUE; /* ignore WM_DESTROY message now */ DestroyWindow(s_hwnd); } #ifdef GLOBAL_IME global_ime_end(); #endif } static char_u * logfont2name(LOGFONT lf) { char *p; char *res; char *charset_name; charset_name = charset_id2name((int)lf.lfCharSet); res = alloc((unsigned)(strlen(lf.lfFaceName) + 20 + (charset_name == NULL ? 0 : strlen(charset_name) + 2))); if (res != NULL) { p = res; /* make a normal font string out of the lf thing:*/ sprintf((char *)p, "%s:h%d", lf.lfFaceName, pixels_to_points( lf.lfHeight < 0 ? -lf.lfHeight : lf.lfHeight, TRUE)); while (*p) { if (*p == ' ') *p = '_'; ++p; } #ifndef MSWIN16_FASTTEXT if (lf.lfItalic) STRCAT(p, ":i"); if (lf.lfWeight >= FW_BOLD) STRCAT(p, ":b"); #endif if (lf.lfUnderline) STRCAT(p, ":u"); if (lf.lfStrikeOut) STRCAT(p, ":s"); if (charset_name != NULL) { STRCAT(p, ":c"); STRCAT(p, charset_name); } } return res; } /* * Initialise vim to use the font with the given name. * Return FAIL if the font could not be loaded, OK otherwise. */ /*ARGSUSED*/ int gui_mch_init_font(char_u *font_name, int fontset) { LOGFONT lf; GuiFont font = NOFONT; char_u *p; /* Load the font */ if (get_logfont(&lf, font_name, NULL, TRUE) == OK) font = get_font_handle(&lf); if (font == NOFONT) return FAIL; if (font_name == NULL) font_name = lf.lfFaceName; #if defined(FEAT_MBYTE_IME) || defined(GLOBAL_IME) norm_logfont = lf; #endif #ifdef FEAT_MBYTE_IME im_set_font(&lf); #endif gui_mch_free_font(gui.norm_font); gui.norm_font = font; current_font_height = lf.lfHeight; GetFontSize(font); p = logfont2name(lf); if (p != NULL) { hl_set_font_name(p); /* When setting 'guifont' to "*" replace it with the actual font name. * */ if (STRCMP(font_name, "*") == 0 && STRCMP(p_guifont, "*") == 0) { vim_free(p_guifont); p_guifont = p; } else vim_free(p); } #ifndef MSWIN16_FASTTEXT gui_mch_free_font(gui.ital_font); gui.ital_font = NOFONT; gui_mch_free_font(gui.bold_font); gui.bold_font = NOFONT; gui_mch_free_font(gui.boldital_font); gui.boldital_font = NOFONT; if (!lf.lfItalic) { lf.lfItalic = TRUE; gui.ital_font = get_font_handle(&lf); lf.lfItalic = FALSE; } if (lf.lfWeight < FW_BOLD) { lf.lfWeight = FW_BOLD; gui.bold_font = get_font_handle(&lf); if (!lf.lfItalic) { lf.lfItalic = TRUE; gui.boldital_font = get_font_handle(&lf); } } #endif return OK; } #ifndef WPF_RESTORETOMAXIMIZED # define WPF_RESTORETOMAXIMIZED 2 /* just in case someone doesn't have it */ #endif /* * Return TRUE if the GUI window is maximized, filling the whole screen. */ int gui_mch_maximized() { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); if (GetWindowPlacement(s_hwnd, &wp)) return wp.showCmd == SW_SHOWMAXIMIZED || (wp.showCmd == SW_SHOWMINIMIZED && wp.flags == WPF_RESTORETOMAXIMIZED); return 0; } /* * Called when the font changed while the window is maximized. Compute the * new Rows and Columns. This is like resizing the window. */ void gui_mch_newfont() { RECT rect; GetWindowRect(s_hwnd, &rect); gui_resize_shell(rect.right - rect.left - GetSystemMetrics(SM_CXFRAME) * 2, rect.bottom - rect.top - GetSystemMetrics(SM_CYFRAME) * 2 - GetSystemMetrics(SM_CYCAPTION) #ifdef FEAT_MENU - gui_mswin_get_menu_height(FALSE) #endif ); } /* * Set the window title */ /*ARGSUSED*/ void gui_mch_settitle( char_u *title, char_u *icon) { set_window_title(s_hwnd, (title == NULL ? "VIM" : (char *)title)); } #ifdef FEAT_MOUSESHAPE /* Table for shape IDCs. Keep in sync with the mshape_names[] table in * misc2.c! */ static LPCSTR mshape_idcs[] = { MAKEINTRESOURCE(IDC_ARROW), /* arrow */ MAKEINTRESOURCE(0), /* blank */ MAKEINTRESOURCE(IDC_IBEAM), /* beam */ MAKEINTRESOURCE(IDC_SIZENS), /* updown */ MAKEINTRESOURCE(IDC_SIZENS), /* udsizing */ MAKEINTRESOURCE(IDC_SIZEWE), /* leftright */ MAKEINTRESOURCE(IDC_SIZEWE), /* lrsizing */ MAKEINTRESOURCE(IDC_WAIT), /* busy */ #ifdef WIN3264 MAKEINTRESOURCE(IDC_NO), /* no */ #else MAKEINTRESOURCE(IDC_ICON), /* no */ #endif MAKEINTRESOURCE(IDC_ARROW), /* crosshair */ MAKEINTRESOURCE(IDC_ARROW), /* hand1 */ MAKEINTRESOURCE(IDC_ARROW), /* hand2 */ MAKEINTRESOURCE(IDC_ARROW), /* pencil */ MAKEINTRESOURCE(IDC_ARROW), /* question */ MAKEINTRESOURCE(IDC_ARROW), /* right-arrow */ MAKEINTRESOURCE(IDC_UPARROW), /* up-arrow */ MAKEINTRESOURCE(IDC_ARROW) /* last one */ }; void mch_set_mouse_shape(int shape) { LPCSTR idc; if (shape == MSHAPE_HIDE) ShowCursor(FALSE); else { if (shape >= MSHAPE_NUMBERED) idc = MAKEINTRESOURCE(IDC_ARROW); else idc = mshape_idcs[shape]; #ifdef SetClassLongPtr SetClassLongPtr(s_textArea, GCLP_HCURSOR, (__int3264)(LONG_PTR)LoadCursor(NULL, idc)); #else # ifdef WIN32 SetClassLong(s_textArea, GCL_HCURSOR, (long_u)LoadCursor(NULL, idc)); # else /* Win16 */ SetClassWord(s_textArea, GCW_HCURSOR, (WORD)LoadCursor(NULL, idc)); # endif #endif if (!p_mh) { POINT mp; /* Set the position to make it redrawn with the new shape. */ (void)GetCursorPos((LPPOINT)&mp); (void)SetCursorPos(mp.x, mp.y); ShowCursor(TRUE); } } } #endif #ifdef FEAT_BROWSE /* * The file browser exists in two versions: with "W" uses wide characters, * without "W" the current codepage. When FEAT_MBYTE is defined and on * Windows NT/2000/XP the "W" functions are used. */ # if defined(FEAT_MBYTE) && defined(WIN3264) /* * Wide version of convert_filter(). */ static WCHAR * convert_filterW(char_u *s) { char_u *tmp; int len; WCHAR *res; tmp = convert_filter(s); if (tmp == NULL) return NULL; len = (int)STRLEN(s) + 3; res = enc_to_utf16(tmp, &len); vim_free(tmp); return res; } /* * Wide version of gui_mch_browse(). Keep in sync! */ static char_u * gui_mch_browseW( int saving, char_u *title, char_u *dflt, char_u *ext, char_u *initdir, char_u *filter) { /* We always use the wide function. This means enc_to_utf16() must work, * otherwise it fails miserably! */ OPENFILENAMEW fileStruct; WCHAR fileBuf[MAXPATHL]; WCHAR *wp; int i; WCHAR *titlep = NULL; WCHAR *extp = NULL; WCHAR *initdirp = NULL; WCHAR *filterp; char_u *p; if (dflt == NULL) fileBuf[0] = NUL; else { wp = enc_to_utf16(dflt, NULL); if (wp == NULL) fileBuf[0] = NUL; else { for (i = 0; wp[i] != NUL && i < MAXPATHL - 1; ++i) fileBuf[i] = wp[i]; fileBuf[i] = NUL; vim_free(wp); } } /* Convert the filter to Windows format. */ filterp = convert_filterW(filter); vim_memset(&fileStruct, 0, sizeof(OPENFILENAMEW)); #ifdef OPENFILENAME_SIZE_VERSION_400 /* be compatible with Windows NT 4.0 */ /* TODO: what to use for OPENFILENAMEW??? */ fileStruct.lStructSize = OPENFILENAME_SIZE_VERSION_400; #else fileStruct.lStructSize = sizeof(fileStruct); #endif if (title != NULL) titlep = enc_to_utf16(title, NULL); fileStruct.lpstrTitle = titlep; if (ext != NULL) extp = enc_to_utf16(ext, NULL); fileStruct.lpstrDefExt = extp; fileStruct.lpstrFile = fileBuf; fileStruct.nMaxFile = MAXPATHL; fileStruct.lpstrFilter = filterp; fileStruct.hwndOwner = s_hwnd; /* main Vim window is owner*/ /* has an initial dir been specified? */ if (initdir != NULL && *initdir != NUL) { /* Must have backslashes here, no matter what 'shellslash' says */ initdirp = enc_to_utf16(initdir, NULL); if (initdirp != NULL) { for (wp = initdirp; *wp != NUL; ++wp) if (*wp == '/') *wp = '\\'; } fileStruct.lpstrInitialDir = initdirp; } /* * TODO: Allow selection of multiple files. Needs another arg to this * function to ask for it, and need to use OFN_ALLOWMULTISELECT below. * Also, should we use OFN_FILEMUSTEXIST when opening? Vim can edit on * files that don't exist yet, so I haven't put it in. What about * OFN_PATHMUSTEXIST? * Don't use OFN_OVERWRITEPROMPT, Vim has its own ":confirm" dialog. */ fileStruct.Flags = (OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY); #ifdef FEAT_SHORTCUT if (curbuf->b_p_bin) fileStruct.Flags |= OFN_NODEREFERENCELINKS; #endif if (saving) { if (!GetSaveFileNameW(&fileStruct)) return NULL; } else { if (!GetOpenFileNameW(&fileStruct)) return NULL; } vim_free(filterp); vim_free(initdirp); vim_free(titlep); vim_free(extp); /* Convert from UCS2 to 'encoding'. */ p = utf16_to_enc(fileBuf, NULL); if (p != NULL) /* when out of memory we get garbage for non-ASCII chars */ STRCPY(fileBuf, p); vim_free(p); /* Give focus back to main window (when using MDI). */ SetFocus(s_hwnd); /* Shorten the file name if possible */ return vim_strsave(shorten_fname1((char_u *)fileBuf)); } # endif /* FEAT_MBYTE */ /* * Convert the string s to the proper format for a filter string by replacing * the \t and \n delimiters with \0. * Returns the converted string in allocated memory. * * Keep in sync with convert_filterW() above! */ static char_u * convert_filter(char_u *s) { char_u *res; unsigned s_len = (unsigned)STRLEN(s); unsigned i; res = alloc(s_len + 3); if (res != NULL) { for (i = 0; i < s_len; ++i) if (s[i] == '\t' || s[i] == '\n') res[i] = '\0'; else res[i] = s[i]; res[s_len] = NUL; /* Add two extra NULs to make sure it's properly terminated. */ res[s_len + 1] = NUL; res[s_len + 2] = NUL; } return res; } /* * Select a directory. */ char_u * gui_mch_browsedir(char_u *title, char_u *initdir) { /* We fake this: Use a filter that doesn't select anything and a default * file name that won't be used. */ return gui_mch_browse(0, title, (char_u *)_("Not Used"), NULL, initdir, (char_u *)_("Directory\t*.nothing\n")); } /* * Pop open a file browser and return the file selected, in allocated memory, * or NULL if Cancel is hit. * saving - TRUE if the file will be saved to, FALSE if it will be opened. * title - Title message for the file browser dialog. * dflt - Default name of file. * ext - Default extension to be added to files without extensions. * initdir - directory in which to open the browser (NULL = current dir) * filter - Filter for matched files to choose from. * * Keep in sync with gui_mch_browseW() above! */ char_u * gui_mch_browse( int saving, char_u *title, char_u *dflt, char_u *ext, char_u *initdir, char_u *filter) { OPENFILENAME fileStruct; char_u fileBuf[MAXPATHL]; char_u *initdirp = NULL; char_u *filterp; char_u *p; # if defined(FEAT_MBYTE) && defined(WIN3264) if (os_version.dwPlatformId == VER_PLATFORM_WIN32_NT) return gui_mch_browseW(saving, title, dflt, ext, initdir, filter); # endif if (dflt == NULL) fileBuf[0] = NUL; else vim_strncpy(fileBuf, dflt, MAXPATHL - 1); /* Convert the filter to Windows format. */ filterp = convert_filter(filter); vim_memset(&fileStruct, 0, sizeof(OPENFILENAME)); #ifdef OPENFILENAME_SIZE_VERSION_400 /* be compatible with Windows NT 4.0 */ fileStruct.lStructSize = OPENFILENAME_SIZE_VERSION_400; #else fileStruct.lStructSize = sizeof(fileStruct); #endif fileStruct.lpstrTitle = title; fileStruct.lpstrDefExt = ext; fileStruct.lpstrFile = fileBuf; fileStruct.nMaxFile = MAXPATHL; fileStruct.lpstrFilter = filterp; fileStruct.hwndOwner = s_hwnd; /* main Vim window is owner*/ /* has an initial dir been specified? */ if (initdir != NULL && *initdir != NUL) { /* Must have backslashes here, no matter what 'shellslash' says */ initdirp = vim_strsave(initdir); if (initdirp != NULL) for (p = initdirp; *p != NUL; ++p) if (*p == '/') *p = '\\'; fileStruct.lpstrInitialDir = initdirp; } /* * TODO: Allow selection of multiple files. Needs another arg to this * function to ask for it, and need to use OFN_ALLOWMULTISELECT below. * Also, should we use OFN_FILEMUSTEXIST when opening? Vim can edit on * files that don't exist yet, so I haven't put it in. What about * OFN_PATHMUSTEXIST? * Don't use OFN_OVERWRITEPROMPT, Vim has its own ":confirm" dialog. */ fileStruct.Flags = (OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY); #ifdef FEAT_SHORTCUT if (curbuf->b_p_bin) fileStruct.Flags |= OFN_NODEREFERENCELINKS; #endif if (saving) { if (!GetSaveFileName(&fileStruct)) return NULL; } else { if (!GetOpenFileName(&fileStruct)) return NULL; } vim_free(filterp); vim_free(initdirp); /* Give focus back to main window (when using MDI). */ SetFocus(s_hwnd); /* Shorten the file name if possible */ return vim_strsave(shorten_fname1((char_u *)fileBuf)); } #endif /* FEAT_BROWSE */ /*ARGSUSED*/ static void _OnDropFiles( HWND hwnd, HDROP hDrop) { #ifdef FEAT_WINDOWS #ifdef WIN3264 # define BUFPATHLEN _MAX_PATH # define DRAGQVAL 0xFFFFFFFF #else # define BUFPATHLEN MAXPATHL # define DRAGQVAL 0xFFFF #endif #ifdef FEAT_MBYTE WCHAR wszFile[BUFPATHLEN]; #endif char szFile[BUFPATHLEN]; UINT cFiles = DragQueryFile(hDrop, DRAGQVAL, NULL, 0); UINT i; char_u **fnames; POINT pt; int_u modifiers = 0; /* TRACE("_OnDropFiles: %d files dropped\n", cFiles); */ /* Obtain dropped position */ DragQueryPoint(hDrop, &pt); MapWindowPoints(s_hwnd, s_textArea, &pt, 1); # ifdef FEAT_VISUAL reset_VIsual(); # endif fnames = (char_u **)alloc(cFiles * sizeof(char_u *)); if (fnames != NULL) for (i = 0; i < cFiles; ++i) { #ifdef FEAT_MBYTE if (DragQueryFileW(hDrop, i, wszFile, BUFPATHLEN) > 0) fnames[i] = utf16_to_enc(wszFile, NULL); else #endif { DragQueryFile(hDrop, i, szFile, BUFPATHLEN); fnames[i] = vim_strsave(szFile); } } DragFinish(hDrop); if (fnames != NULL) { if ((GetKeyState(VK_SHIFT) & 0x8000) != 0) modifiers |= MOUSE_SHIFT; if ((GetKeyState(VK_CONTROL) & 0x8000) != 0) modifiers |= MOUSE_CTRL; if ((GetKeyState(VK_MENU) & 0x8000) != 0) modifiers |= MOUSE_ALT; gui_handle_drop(pt.x, pt.y, modifiers, fnames, cFiles); s_need_activate = TRUE; } #endif } /*ARGSUSED*/ static int _OnScroll( HWND hwnd, HWND hwndCtl, UINT code, int pos) { static UINT prev_code = 0; /* code of previous call */ scrollbar_T *sb, *sb_info; long val; int dragging = FALSE; int dont_scroll_save = dont_scroll; #ifndef WIN3264 int nPos; #else SCROLLINFO si; si.cbSize = sizeof(si); si.fMask = SIF_POS; #endif sb = gui_mswin_find_scrollbar(hwndCtl); if (sb == NULL) return 0; if (sb->wp != NULL) /* Left or right scrollbar */ { /* * Careful: need to get scrollbar info out of first (left) scrollbar * for window, but keep real scrollbar too because we must pass it to * gui_drag_scrollbar(). */ sb_info = &sb->wp->w_scrollbars[0]; } else /* Bottom scrollbar */ sb_info = sb; val = sb_info->value; switch (code) { case SB_THUMBTRACK: val = pos; dragging = TRUE; if (sb->scroll_shift > 0) val <<= sb->scroll_shift; break; case SB_LINEDOWN: val++; break; case SB_LINEUP: val--; break; case SB_PAGEDOWN: val += (sb_info->size > 2 ? sb_info->size - 2 : 1); break; case SB_PAGEUP: val -= (sb_info->size > 2 ? sb_info->size - 2 : 1); break; case SB_TOP: val = 0; break; case SB_BOTTOM: val = sb_info->max; break; case SB_ENDSCROLL: if (prev_code == SB_THUMBTRACK) { /* * "pos" only gives us 16-bit data. In case of large file, * use GetScrollPos() which returns 32-bit. Unfortunately it * is not valid while the scrollbar is being dragged. */ val = GetScrollPos(hwndCtl, SB_CTL); if (sb->scroll_shift > 0) val <<= sb->scroll_shift; } break; default: /* TRACE("Unknown scrollbar event %d\n", code); */ return 0; } prev_code = code; #ifdef WIN3264 si.nPos = (sb->scroll_shift > 0) ? val >> sb->scroll_shift : val; SetScrollInfo(hwndCtl, SB_CTL, &si, TRUE); #else nPos = (sb->scroll_shift > 0) ? val >> sb->scroll_shift : val; SetScrollPos(hwndCtl, SB_CTL, nPos, TRUE); #endif /* * When moving a vertical scrollbar, move the other vertical scrollbar too. */ if (sb->wp != NULL) { scrollbar_T *sba = sb->wp->w_scrollbars; HWND id = sba[ (sb == sba + SBAR_LEFT) ? SBAR_RIGHT : SBAR_LEFT].id; #ifdef WIN3264 SetScrollInfo(id, SB_CTL, &si, TRUE); #else SetScrollPos(id, SB_CTL, nPos, TRUE); #endif } /* Don't let us be interrupted here by another message. */ s_busy_processing = TRUE; /* When "allow_scrollbar" is FALSE still need to remember the new * position, but don't actually scroll by setting "dont_scroll". */ dont_scroll = !allow_scrollbar; gui_drag_scrollbar(sb, val, dragging); s_busy_processing = FALSE; dont_scroll = dont_scroll_save; return 0; } /* * Get command line arguments. * Use "prog" as the name of the program and "cmdline" as the arguments. * Copy the arguments to allocated memory. * Return the number of arguments (including program name). * Return pointers to the arguments in "argvp". Memory is allocated with * malloc(), use free() instead of vim_free(). * Return pointer to buffer in "tofree". * Returns zero when out of memory. */ /*ARGSUSED*/ int get_cmd_args(char *prog, char *cmdline, char ***argvp, char **tofree) { int i; char *p; char *progp; char *pnew = NULL; char *newcmdline; int inquote; int argc; char **argv = NULL; int round; *tofree = NULL; #ifdef FEAT_MBYTE /* Try using the Unicode version first, it takes care of conversion when * 'encoding' is changed. */ argc = get_cmd_argsW(&argv); if (argc != 0) goto done; #endif /* Handle the program name. Remove the ".exe" extension, and find the 1st * non-space. */ p = strrchr(prog, '.'); if (p != NULL) *p = NUL; for (progp = prog; *progp == ' '; ++progp) ; /* The command line is copied to allocated memory, so that we can change * it. Add the size of the string, the separating NUL and a terminating * NUL. */ newcmdline = malloc(STRLEN(cmdline) + STRLEN(progp) + 2); if (newcmdline == NULL) return 0; /* * First round: count the number of arguments ("pnew" == NULL). * Second round: produce the arguments. */ for (round = 1; round <= 2; ++round) { /* First argument is the program name. */ if (pnew != NULL) { argv[0] = pnew; strcpy(pnew, progp); pnew += strlen(pnew); *pnew++ = NUL; } /* * Isolate each argument and put it in argv[]. */ p = cmdline; argc = 1; while (*p != NUL) { inquote = FALSE; if (pnew != NULL) argv[argc] = pnew; ++argc; while (*p != NUL && (inquote || (*p != ' ' && *p != '\t'))) { /* Backslashes are only special when followed by a double * quote. */ i = (int)strspn(p, "\\"); if (p[i] == '"') { /* Halve the number of backslashes. */ if (i > 1 && pnew != NULL) { vim_memset(pnew, '\\', i / 2); pnew += i / 2; } /* Even nr of backslashes toggles quoting, uneven copies * the double quote. */ if ((i & 1) == 0) inquote = !inquote; else if (pnew != NULL) *pnew++ = '"'; p += i + 1; } else if (i > 0) { /* Copy span of backslashes unmodified. */ if (pnew != NULL) { vim_memset(pnew, '\\', i); pnew += i; } p += i; } else { if (pnew != NULL) *pnew++ = *p; #ifdef FEAT_MBYTE /* Can't use mb_* functions, because 'encoding' is not * initialized yet here. */ if (IsDBCSLeadByte(*p)) { ++p; if (pnew != NULL) *pnew++ = *p; } #endif ++p; } } if (pnew != NULL) *pnew++ = NUL; while (*p == ' ' || *p == '\t') ++p; /* advance until a non-space */ } if (round == 1) { argv = (char **)malloc((argc + 1) * sizeof(char *)); if (argv == NULL ) { free(newcmdline); return 0; /* malloc error */ } pnew = newcmdline; *tofree = newcmdline; } } #ifdef FEAT_MBYTE done: #endif argv[argc] = NULL; /* NULL-terminated list */ *argvp = argv; return argc; }
zyz2011-vim
src/gui_w48.c
C
gpl2
90,615
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * GUI support by Robert Webb * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * Windows GUI: main program (EXE) entry point: * * Ron Aaron <ronaharon@yahoo.com> wrote this and the DLL support code. */ #include "vim.h" #ifdef __MINGW32__ # ifndef _cdecl # define _cdecl # endif #endif /* cproto doesn't create a prototype for main() */ int _cdecl #if defined(FEAT_GUI_W32) VimMain #else main #endif __ARGS((int argc, char **argv)); static int (_cdecl *pmain)(int, char **); #ifndef PROTO #ifdef FEAT_GUI #ifndef VIMDLL void _cdecl SaveInst(HINSTANCE hInst); #endif static void (_cdecl *pSaveInst)(HINSTANCE); #endif /*ARGSUSED*/ int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInst, LPSTR lpszCmdLine, int nCmdShow) { int argc = 0; char **argv; char *tofree; char prog[256]; #ifdef VIMDLL char *p; HANDLE hLib; #endif /* Ron: added full path name so that the $VIM variable will get set to our * startup path (so the .vimrc file can be found w/o a VIM env. var.) */ GetModuleFileName(NULL, prog, 255); argc = get_cmd_args(prog, (char *)lpszCmdLine, &argv, &tofree); if (argc == 0) { MessageBox(0, "Could not allocate memory for command line.", "VIM Error", 0); return 0; } #ifdef DYNAMIC_GETTEXT /* Initialize gettext library */ dyn_libintl_init(NULL); #endif #ifdef VIMDLL // LoadLibrary - get name of dll to load in here: p = strrchr(prog, '\\'); if (p != NULL) { # ifdef DEBUG strcpy(p+1, "vim32d.dll"); # else strcpy(p+1, "vim32.dll"); # endif } hLib = LoadLibrary(prog); if (hLib == NULL) { MessageBox(0, _("Could not load vim32.dll!"), _("VIM Error"), 0); goto errout; } // fix up the function pointers # ifdef FEAT_GUI pSaveInst = GetProcAddress(hLib, (LPCSTR)2); # endif pmain = GetProcAddress(hLib, (LPCSTR)1); if (pmain == NULL) { MessageBox(0, _("Could not fix up function pointers to the DLL!"), _("VIM Error"),0); goto errout; } #else # ifdef FEAT_GUI pSaveInst = SaveInst; # endif pmain = # if defined(FEAT_GUI_W32) //&& defined(__MINGW32__) VimMain # else main # endif ; #endif #ifdef FEAT_GUI pSaveInst( #ifdef __MINGW32__ GetModuleHandle(NULL) #else hInstance #endif ); #endif pmain(argc, argv); #ifdef VIMDLL FreeLibrary(hLib); errout: #endif free(argv); if (tofree != NULL) free(tofree); #ifdef FEAT_MBYTE free_cmd_argsW(); #endif return 0; } #endif
zyz2011-vim
src/os_w32exe.c
C
gpl2
2,760
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * OS/2 port by Paul Slootman * VMS merge by Zoltan Arpadffy * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * os_unix.c -- code for all flavors of Unix (BSD, SYSV, SVR4, POSIX, ...) * Also for OS/2, using the excellent EMX package!!! * Also for BeOS and Atari MiNT. * * A lot of this file was originally written by Juergen Weigert and later * changed beyond recognition. */ /* * Some systems have a prototype for select() that has (int *) instead of * (fd_set *), which is wrong. This define removes that prototype. We define * our own prototype below. * Don't use it for the Mac, it causes a warning for precompiled headers. * TODO: use a configure check for precompiled headers? */ #if !defined(__APPLE__) && !defined(__TANDEM) # define select select_declared_wrong #endif #include "vim.h" #ifdef FEAT_MZSCHEME # include "if_mzsch.h" #endif #include "os_unixx.h" /* unix includes for os_unix.c only */ #ifdef USE_XSMP # include <X11/SM/SMlib.h> #endif #ifdef HAVE_SELINUX # include <selinux/selinux.h> static int selinux_enabled = -1; #endif /* * Use this prototype for select, some include files have a wrong prototype */ #ifndef __TANDEM # undef select # ifdef __BEOS__ # define select beos_select # endif #endif #ifdef __CYGWIN__ # ifndef WIN32 # include <cygwin/version.h> # include <sys/cygwin.h> /* for cygwin_conv_to_posix_path() and/or * for cygwin_conv_path() */ # endif #endif #if defined(HAVE_SELECT) extern int select __ARGS((int, fd_set *, fd_set *, fd_set *, struct timeval *)); #endif #ifdef FEAT_MOUSE_GPM # include <gpm.h> /* <linux/keyboard.h> contains defines conflicting with "keymap.h", * I just copied relevant defines here. A cleaner solution would be to put gpm * code into separate file and include there linux/keyboard.h */ /* #include <linux/keyboard.h> */ # define KG_SHIFT 0 # define KG_CTRL 2 # define KG_ALT 3 # define KG_ALTGR 1 # define KG_SHIFTL 4 # define KG_SHIFTR 5 # define KG_CTRLL 6 # define KG_CTRLR 7 # define KG_CAPSSHIFT 8 static void gpm_close __ARGS((void)); static int gpm_open __ARGS((void)); static int mch_gpm_process __ARGS((void)); #endif #ifdef FEAT_SYSMOUSE # include <sys/consio.h> # include <sys/fbio.h> static int sysmouse_open __ARGS((void)); static void sysmouse_close __ARGS((void)); static RETSIGTYPE sig_sysmouse __ARGS(SIGPROTOARG); #endif /* * end of autoconf section. To be extended... */ /* Are the following #ifdefs still required? And why? Is that for X11? */ #if defined(ESIX) || defined(M_UNIX) && !defined(SCO) # ifdef SIGWINCH # undef SIGWINCH # endif # ifdef TIOCGWINSZ # undef TIOCGWINSZ # endif #endif #if defined(SIGWINDOW) && !defined(SIGWINCH) /* hpux 9.01 has it */ # define SIGWINCH SIGWINDOW #endif #ifdef FEAT_X11 # include <X11/Xlib.h> # include <X11/Xutil.h> # include <X11/Xatom.h> # ifdef FEAT_XCLIPBOARD # include <X11/Intrinsic.h> # include <X11/Shell.h> # include <X11/StringDefs.h> static Widget xterm_Shell = (Widget)0; static void xterm_update __ARGS((void)); # endif # if defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE) Window x11_window = 0; # endif Display *x11_display = NULL; # ifdef FEAT_TITLE static int get_x11_windis __ARGS((void)); static void set_x11_title __ARGS((char_u *)); static void set_x11_icon __ARGS((char_u *)); # endif #endif #ifdef FEAT_TITLE static int get_x11_title __ARGS((int)); static int get_x11_icon __ARGS((int)); static char_u *oldtitle = NULL; static int did_set_title = FALSE; static char_u *oldicon = NULL; static int did_set_icon = FALSE; #endif static void may_core_dump __ARGS((void)); #ifdef HAVE_UNION_WAIT typedef union wait waitstatus; #else typedef int waitstatus; #endif static pid_t wait4pid __ARGS((pid_t, waitstatus *)); static int WaitForChar __ARGS((long)); #if defined(__BEOS__) int RealWaitForChar __ARGS((int, long, int *)); #else static int RealWaitForChar __ARGS((int, long, int *)); #endif #ifdef FEAT_XCLIPBOARD static int do_xterm_trace __ARGS((void)); # define XT_TRACE_DELAY 50 /* delay for xterm tracing */ #endif static void handle_resize __ARGS((void)); #if defined(SIGWINCH) static RETSIGTYPE sig_winch __ARGS(SIGPROTOARG); #endif #if defined(SIGINT) static RETSIGTYPE catch_sigint __ARGS(SIGPROTOARG); #endif #if defined(SIGPWR) static RETSIGTYPE catch_sigpwr __ARGS(SIGPROTOARG); #endif #if defined(SIGALRM) && defined(FEAT_X11) \ && defined(FEAT_TITLE) && !defined(FEAT_GUI_GTK) # define SET_SIG_ALARM static RETSIGTYPE sig_alarm __ARGS(SIGPROTOARG); /* volatile because it is used in signal handler sig_alarm(). */ static volatile int sig_alarm_called; #endif static RETSIGTYPE deathtrap __ARGS(SIGPROTOARG); static void catch_int_signal __ARGS((void)); static void set_signals __ARGS((void)); static void catch_signals __ARGS((RETSIGTYPE (*func_deadly)(), RETSIGTYPE (*func_other)())); #ifndef __EMX__ static int have_wildcard __ARGS((int, char_u **)); static int have_dollars __ARGS((int, char_u **)); #endif #ifndef __EMX__ static int save_patterns __ARGS((int num_pat, char_u **pat, int *num_file, char_u ***file)); #endif #ifndef SIG_ERR # define SIG_ERR ((RETSIGTYPE (*)())-1) #endif /* volatile because it is used in signal handler sig_winch(). */ static volatile int do_resize = FALSE; #ifndef __EMX__ static char_u *extra_shell_arg = NULL; static int show_shell_mess = TRUE; #endif /* volatile because it is used in signal handler deathtrap(). */ static volatile int deadly_signal = 0; /* The signal we caught */ /* volatile because it is used in signal handler deathtrap(). */ static volatile int in_mch_delay = FALSE; /* sleeping in mch_delay() */ static int curr_tmode = TMODE_COOK; /* contains current terminal mode */ #ifdef USE_XSMP typedef struct { SmcConn smcconn; /* The SM connection ID */ IceConn iceconn; /* The ICE connection ID */ char *clientid; /* The client ID for the current smc session */ Bool save_yourself; /* If we're in the middle of a save_yourself */ Bool shutdown; /* If we're in shutdown mode */ } xsmp_config_T; static xsmp_config_T xsmp; #endif #ifdef SYS_SIGLIST_DECLARED /* * I have seen * extern char *_sys_siglist[NSIG]; * on Irix, Linux, NetBSD and Solaris. It contains a nice list of strings * that describe the signals. That is nearly what we want here. But * autoconf does only check for sys_siglist (without the underscore), I * do not want to change everything today.... jw. * This is why AC_DECL_SYS_SIGLIST is commented out in configure.in */ #endif static struct signalinfo { int sig; /* Signal number, eg. SIGSEGV etc */ char *name; /* Signal name (not char_u!). */ char deadly; /* Catch as a deadly signal? */ } signal_info[] = { #ifdef SIGHUP {SIGHUP, "HUP", TRUE}, #endif #ifdef SIGQUIT {SIGQUIT, "QUIT", TRUE}, #endif #ifdef SIGILL {SIGILL, "ILL", TRUE}, #endif #ifdef SIGTRAP {SIGTRAP, "TRAP", TRUE}, #endif #ifdef SIGABRT {SIGABRT, "ABRT", TRUE}, #endif #ifdef SIGEMT {SIGEMT, "EMT", TRUE}, #endif #ifdef SIGFPE {SIGFPE, "FPE", TRUE}, #endif #ifdef SIGBUS {SIGBUS, "BUS", TRUE}, #endif #ifdef SIGSEGV {SIGSEGV, "SEGV", TRUE}, #endif #ifdef SIGSYS {SIGSYS, "SYS", TRUE}, #endif #ifdef SIGALRM {SIGALRM, "ALRM", FALSE}, /* Perl's alarm() can trigger it */ #endif #ifdef SIGTERM {SIGTERM, "TERM", TRUE}, #endif #if defined(SIGVTALRM) && !defined(FEAT_RUBY) {SIGVTALRM, "VTALRM", TRUE}, #endif #if defined(SIGPROF) && !defined(FEAT_MZSCHEME) && !defined(WE_ARE_PROFILING) /* MzScheme uses SIGPROF for its own needs; On Linux with profiling * this makes Vim exit. WE_ARE_PROFILING is defined in Makefile. */ {SIGPROF, "PROF", TRUE}, #endif #ifdef SIGXCPU {SIGXCPU, "XCPU", TRUE}, #endif #ifdef SIGXFSZ {SIGXFSZ, "XFSZ", TRUE}, #endif #ifdef SIGUSR1 {SIGUSR1, "USR1", TRUE}, #endif #if defined(SIGUSR2) && !defined(FEAT_SYSMOUSE) /* Used for sysmouse handling */ {SIGUSR2, "USR2", TRUE}, #endif #ifdef SIGINT {SIGINT, "INT", FALSE}, #endif #ifdef SIGWINCH {SIGWINCH, "WINCH", FALSE}, #endif #ifdef SIGTSTP {SIGTSTP, "TSTP", FALSE}, #endif #ifdef SIGPIPE {SIGPIPE, "PIPE", FALSE}, #endif {-1, "Unknown!", FALSE} }; int mch_chdir(path) char *path; { if (p_verbose >= 5) { verbose_enter(); smsg((char_u *)"chdir(%s)", path); verbose_leave(); } # ifdef VMS return chdir(vms_fixfilename(path)); # else return chdir(path); # endif } /* * Write s[len] to the screen. */ void mch_write(s, len) char_u *s; int len; { ignored = (int)write(1, (char *)s, len); if (p_wd) /* Unix is too fast, slow down a bit more */ RealWaitForChar(read_cmd_fd, p_wd, NULL); } /* * mch_inchar(): low level input function. * Get a characters from the keyboard. * Return the number of characters that are available. * If wtime == 0 do not wait for characters. * If wtime == n wait a short time for characters. * If wtime == -1 wait forever for characters. */ int mch_inchar(buf, maxlen, wtime, tb_change_cnt) char_u *buf; int maxlen; long wtime; /* don't use "time", MIPS cannot handle it */ int tb_change_cnt; { int len; #ifdef FEAT_NETBEANS_INTG /* Process the queued netbeans messages. */ netbeans_parse_messages(); #endif /* Check if window changed size while we were busy, perhaps the ":set * columns=99" command was used. */ while (do_resize) handle_resize(); if (wtime >= 0) { while (WaitForChar(wtime) == 0) /* no character available */ { if (!do_resize) /* return if not interrupted by resize */ return 0; handle_resize(); #ifdef FEAT_NETBEANS_INTG /* Process the queued netbeans messages. */ netbeans_parse_messages(); #endif } } else /* wtime == -1 */ { /* * If there is no character available within 'updatetime' seconds * flush all the swap files to disk. * Also done when interrupted by SIGWINCH. */ if (WaitForChar(p_ut) == 0) { #ifdef FEAT_AUTOCMD if (trigger_cursorhold() && maxlen >= 3 && !typebuf_changed(tb_change_cnt)) { buf[0] = K_SPECIAL; buf[1] = KS_EXTRA; buf[2] = (int)KE_CURSORHOLD; return 3; } #endif before_blocking(); } } for (;;) /* repeat until we got a character */ { while (do_resize) /* window changed size */ handle_resize(); #ifdef FEAT_NETBEANS_INTG /* Process the queued netbeans messages. */ netbeans_parse_messages(); #endif #ifndef VMS /* VMS: must try reading, WaitForChar() does nothing. */ /* * We want to be interrupted by the winch signal * or by an event on the monitored file descriptors. */ if (WaitForChar(-1L) == 0) { if (do_resize) /* interrupted by SIGWINCH signal */ handle_resize(); return 0; } #endif /* If input was put directly in typeahead buffer bail out here. */ if (typebuf_changed(tb_change_cnt)) return 0; /* * For some terminals we only get one character at a time. * We want the get all available characters, so we could keep on * trying until none is available * For some other terminals this is quite slow, that's why we don't do * it. */ len = read_from_input_buf(buf, (long)maxlen); if (len > 0) { #ifdef OS2 int i; for (i = 0; i < len; i++) if (buf[i] == 0) buf[i] = K_NUL; #endif return len; } } } static void handle_resize() { do_resize = FALSE; shell_resized(); } /* * return non-zero if a character is available */ int mch_char_avail() { return WaitForChar(0L); } #if defined(HAVE_TOTAL_MEM) || defined(PROTO) # ifdef HAVE_SYS_RESOURCE_H # include <sys/resource.h> # endif # if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTL) # include <sys/sysctl.h> # endif # if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO) # include <sys/sysinfo.h> # endif /* * Return total amount of memory available in Kbyte. * Doesn't change when memory has been allocated. */ long_u mch_total_mem(special) int special UNUSED; { # ifdef __EMX__ return ulimit(3, 0L) >> 10; /* always 32MB? */ # else long_u mem = 0; long_u shiftright = 10; /* how much to shift "mem" right for Kbyte */ # ifdef HAVE_SYSCTL int mib[2], physmem; size_t len; /* BSD way of getting the amount of RAM available. */ mib[0] = CTL_HW; mib[1] = HW_USERMEM; len = sizeof(physmem); if (sysctl(mib, 2, &physmem, &len, NULL, 0) == 0) mem = (long_u)physmem; # endif # if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO) if (mem == 0) { struct sysinfo sinfo; /* Linux way of getting amount of RAM available */ if (sysinfo(&sinfo) == 0) { # ifdef HAVE_SYSINFO_MEM_UNIT /* avoid overflow as much as possible */ while (shiftright > 0 && (sinfo.mem_unit & 1) == 0) { sinfo.mem_unit = sinfo.mem_unit >> 1; --shiftright; } mem = sinfo.totalram * sinfo.mem_unit; # else mem = sinfo.totalram; # endif } } # endif # ifdef HAVE_SYSCONF if (mem == 0) { long pagesize, pagecount; /* Solaris way of getting amount of RAM available */ pagesize = sysconf(_SC_PAGESIZE); pagecount = sysconf(_SC_PHYS_PAGES); if (pagesize > 0 && pagecount > 0) { /* avoid overflow as much as possible */ while (shiftright > 0 && (pagesize & 1) == 0) { pagesize = (long_u)pagesize >> 1; --shiftright; } mem = (long_u)pagesize * pagecount; } } # endif /* Return the minimum of the physical memory and the user limit, because * using more than the user limit may cause Vim to be terminated. */ # if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT) { struct rlimit rlp; if (getrlimit(RLIMIT_DATA, &rlp) == 0 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1)) # ifdef RLIM_INFINITY && rlp.rlim_cur != RLIM_INFINITY # endif && ((long_u)rlp.rlim_cur >> 10) < (mem >> shiftright) ) { mem = (long_u)rlp.rlim_cur; shiftright = 10; } } # endif if (mem > 0) return mem >> shiftright; return (long_u)0x1fffff; # endif } #endif void mch_delay(msec, ignoreinput) long msec; int ignoreinput; { int old_tmode; #ifdef FEAT_MZSCHEME long total = msec; /* remember original value */ #endif if (ignoreinput) { /* Go to cooked mode without echo, to allow SIGINT interrupting us * here. But we don't want QUIT to kill us (CTRL-\ used in a * shell may produce SIGQUIT). */ in_mch_delay = TRUE; old_tmode = curr_tmode; if (curr_tmode == TMODE_RAW) settmode(TMODE_SLEEP); /* * Everybody sleeps in a different way... * Prefer nanosleep(), some versions of usleep() can only sleep up to * one second. */ #ifdef FEAT_MZSCHEME do { /* if total is large enough, wait by portions in p_mzq */ if (total > p_mzq) msec = p_mzq; else msec = total; total -= msec; #endif #ifdef HAVE_NANOSLEEP { struct timespec ts; ts.tv_sec = msec / 1000; ts.tv_nsec = (msec % 1000) * 1000000; (void)nanosleep(&ts, NULL); } #else # ifdef HAVE_USLEEP while (msec >= 1000) { usleep((unsigned int)(999 * 1000)); msec -= 999; } usleep((unsigned int)(msec * 1000)); # else # ifndef HAVE_SELECT poll(NULL, 0, (int)msec); # else # ifdef __EMX__ _sleep2(msec); # else { struct timeval tv; tv.tv_sec = msec / 1000; tv.tv_usec = (msec % 1000) * 1000; /* * NOTE: Solaris 2.6 has a bug that makes select() hang here. Get * a patch from Sun to fix this. Reported by Gunnar Pedersen. */ select(0, NULL, NULL, NULL, &tv); } # endif /* __EMX__ */ # endif /* HAVE_SELECT */ # endif /* HAVE_NANOSLEEP */ #endif /* HAVE_USLEEP */ #ifdef FEAT_MZSCHEME } while (total > 0); #endif settmode(old_tmode); in_mch_delay = FALSE; } else WaitForChar(msec); } #if defined(HAVE_STACK_LIMIT) \ || (!defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGSTACK)) # define HAVE_CHECK_STACK_GROWTH /* * Support for checking for an almost-out-of-stack-space situation. */ /* * Return a pointer to an item on the stack. Used to find out if the stack * grows up or down. */ static void check_stack_growth __ARGS((char *p)); static int stack_grows_downwards; /* * Find out if the stack grows upwards or downwards. * "p" points to a variable on the stack of the caller. */ static void check_stack_growth(p) char *p; { int i; stack_grows_downwards = (p > (char *)&i); } #endif #if defined(HAVE_STACK_LIMIT) || defined(PROTO) static char *stack_limit = NULL; #if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H) # include <pthread.h> # include <pthread_np.h> #endif /* * Find out until how var the stack can grow without getting into trouble. * Called when starting up and when switching to the signal stack in * deathtrap(). */ static void get_stack_limit() { struct rlimit rlp; int i; long lim; /* Set the stack limit to 15/16 of the allowable size. Skip this when the * limit doesn't fit in a long (rlim_cur might be "long long"). */ if (getrlimit(RLIMIT_STACK, &rlp) == 0 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1)) # ifdef RLIM_INFINITY && rlp.rlim_cur != RLIM_INFINITY # endif ) { lim = (long)rlp.rlim_cur; #if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H) { pthread_attr_t attr; size_t size; /* On FreeBSD the initial thread always has a fixed stack size, no * matter what the limits are set to. Normally it's 1 Mbyte. */ pthread_attr_init(&attr); if (pthread_attr_get_np(pthread_self(), &attr) == 0) { pthread_attr_getstacksize(&attr, &size); if (lim > (long)size) lim = (long)size; } pthread_attr_destroy(&attr); } #endif if (stack_grows_downwards) { stack_limit = (char *)((long)&i - (lim / 16L * 15L)); if (stack_limit >= (char *)&i) /* overflow, set to 1/16 of current stack position */ stack_limit = (char *)((long)&i / 16L); } else { stack_limit = (char *)((long)&i + (lim / 16L * 15L)); if (stack_limit <= (char *)&i) stack_limit = NULL; /* overflow */ } } } /* * Return FAIL when running out of stack space. * "p" must point to any variable local to the caller that's on the stack. */ int mch_stackcheck(p) char *p; { if (stack_limit != NULL) { if (stack_grows_downwards) { if (p < stack_limit) return FAIL; } else if (p > stack_limit) return FAIL; } return OK; } #endif #if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK) /* * Support for using the signal stack. * This helps when we run out of stack space, which causes a SIGSEGV. The * signal handler then must run on another stack, since the normal stack is * completely full. */ #ifndef SIGSTKSZ # define SIGSTKSZ 8000 /* just a guess of how much stack is needed... */ #endif # ifdef HAVE_SIGALTSTACK static stack_t sigstk; /* for sigaltstack() */ # else static struct sigstack sigstk; /* for sigstack() */ # endif static void init_signal_stack __ARGS((void)); static char *signal_stack; static void init_signal_stack() { if (signal_stack != NULL) { # ifdef HAVE_SIGALTSTACK # if defined(__APPLE__) && (!defined(MAC_OS_X_VERSION_MAX_ALLOWED) \ || MAC_OS_X_VERSION_MAX_ALLOWED <= 1040) /* missing prototype. Adding it to osdef?.h.in doesn't work, because * "struct sigaltstack" needs to be declared. */ extern int sigaltstack __ARGS((const struct sigaltstack *ss, struct sigaltstack *oss)); # endif # ifdef HAVE_SS_BASE sigstk.ss_base = signal_stack; # else sigstk.ss_sp = signal_stack; # endif sigstk.ss_size = SIGSTKSZ; sigstk.ss_flags = 0; (void)sigaltstack(&sigstk, NULL); # else sigstk.ss_sp = signal_stack; if (stack_grows_downwards) sigstk.ss_sp += SIGSTKSZ - 1; sigstk.ss_onstack = 0; (void)sigstack(&sigstk, NULL); # endif } } #endif /* * We need correct prototypes for a signal function, otherwise mean compilers * will barf when the second argument to signal() is ``wrong''. * Let me try it with a few tricky defines from my own osdef.h (jw). */ #if defined(SIGWINCH) static RETSIGTYPE sig_winch SIGDEFARG(sigarg) { /* this is not required on all systems, but it doesn't hurt anybody */ signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch); do_resize = TRUE; SIGRETURN; } #endif #if defined(SIGINT) static RETSIGTYPE catch_sigint SIGDEFARG(sigarg) { /* this is not required on all systems, but it doesn't hurt anybody */ signal(SIGINT, (RETSIGTYPE (*)())catch_sigint); got_int = TRUE; SIGRETURN; } #endif #if defined(SIGPWR) static RETSIGTYPE catch_sigpwr SIGDEFARG(sigarg) { /* this is not required on all systems, but it doesn't hurt anybody */ signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr); /* * I'm not sure we get the SIGPWR signal when the system is really going * down or when the batteries are almost empty. Just preserve the swap * files and don't exit, that can't do any harm. */ ml_sync_all(FALSE, FALSE); SIGRETURN; } #endif #ifdef SET_SIG_ALARM /* * signal function for alarm(). */ static RETSIGTYPE sig_alarm SIGDEFARG(sigarg) { /* doesn't do anything, just to break a system call */ sig_alarm_called = TRUE; SIGRETURN; } #endif #if (defined(HAVE_SETJMP_H) \ && ((defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) \ || defined(FEAT_LIBCALL))) \ || defined(PROTO) /* * A simplistic version of setjmp() that only allows one level of using. * Don't call twice before calling mch_endjmp()!. * Usage: * mch_startjmp(); * if (SETJMP(lc_jump_env) != 0) * { * mch_didjmp(); * EMSG("crash!"); * } * else * { * do_the_work; * mch_endjmp(); * } * Note: Can't move SETJMP() here, because a function calling setjmp() must * not return before the saved environment is used. * Returns OK for normal return, FAIL when the protected code caused a * problem and LONGJMP() was used. */ void mch_startjmp() { #ifdef SIGHASARG lc_signal = 0; #endif lc_active = TRUE; } void mch_endjmp() { lc_active = FALSE; } void mch_didjmp() { # if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK) /* On FreeBSD the signal stack has to be reset after using siglongjmp(), * otherwise catching the signal only works once. */ init_signal_stack(); # endif } #endif /* * This function handles deadly signals. * It tries to preserve any swap file and exit properly. * (partly from Elvis). */ static RETSIGTYPE deathtrap SIGDEFARG(sigarg) { static int entered = 0; /* count the number of times we got here. Note: when memory has been corrupted this may get an arbitrary value! */ #ifdef SIGHASARG int i; #endif #if defined(HAVE_SETJMP_H) /* * Catch a crash in protected code. * Restores the environment saved in lc_jump_env, which looks like * SETJMP() returns 1. */ if (lc_active) { # if defined(SIGHASARG) lc_signal = sigarg; # endif lc_active = FALSE; /* don't jump again */ LONGJMP(lc_jump_env, 1); /* NOTREACHED */ } #endif #ifdef SIGHASARG # ifdef SIGQUIT /* While in mch_delay() we go to cooked mode to allow a CTRL-C to * interrupt us. But in cooked mode we may also get SIGQUIT, e.g., when * pressing CTRL-\, but we don't want Vim to exit then. */ if (in_mch_delay && sigarg == SIGQUIT) SIGRETURN; # endif /* When SIGHUP, SIGQUIT, etc. are blocked: postpone the effect and return * here. This avoids that a non-reentrant function is interrupted, e.g., * free(). Calling free() again may then cause a crash. */ if (entered == 0 && (0 # ifdef SIGHUP || sigarg == SIGHUP # endif # ifdef SIGQUIT || sigarg == SIGQUIT # endif # ifdef SIGTERM || sigarg == SIGTERM # endif # ifdef SIGPWR || sigarg == SIGPWR # endif # ifdef SIGUSR1 || sigarg == SIGUSR1 # endif # ifdef SIGUSR2 || sigarg == SIGUSR2 # endif ) && !vim_handle_signal(sigarg)) SIGRETURN; #endif /* Remember how often we have been called. */ ++entered; #ifdef FEAT_EVAL /* Set the v:dying variable. */ set_vim_var_nr(VV_DYING, (long)entered); #endif #ifdef HAVE_STACK_LIMIT /* Since we are now using the signal stack, need to reset the stack * limit. Otherwise using a regexp will fail. */ get_stack_limit(); #endif #if 0 /* This is for opening gdb the moment Vim crashes. * You need to manually adjust the file name and Vim executable name. * Suggested by SungHyun Nam. */ { # define VI_GDB_FILE "/tmp/vimgdb" # define VIM_NAME "/usr/bin/vim" FILE *fp = fopen(VI_GDB_FILE, "w"); if (fp) { fprintf(fp, "file %s\n" "attach %d\n" "set height 1000\n" "bt full\n" , VIM_NAME, getpid()); fclose(fp); system("xterm -e gdb -x "VI_GDB_FILE); unlink(VI_GDB_FILE); } } #endif #ifdef SIGHASARG /* try to find the name of this signal */ for (i = 0; signal_info[i].sig != -1; i++) if (sigarg == signal_info[i].sig) break; deadly_signal = sigarg; #endif full_screen = FALSE; /* don't write message to the GUI, it might be * part of the problem... */ /* * If something goes wrong after entering here, we may get here again. * When this happens, give a message and try to exit nicely (resetting the * terminal mode, etc.) * When this happens twice, just exit, don't even try to give a message, * stack may be corrupt or something weird. * When this still happens again (or memory was corrupted in such a way * that "entered" was clobbered) use _exit(), don't try freeing resources. */ if (entered >= 3) { reset_signals(); /* don't catch any signals anymore */ may_core_dump(); if (entered >= 4) _exit(8); exit(7); } if (entered == 2) { OUT_STR(_("Vim: Double signal, exiting\n")); out_flush(); getout(1); } #ifdef SIGHASARG sprintf((char *)IObuff, _("Vim: Caught deadly signal %s\n"), signal_info[i].name); #else sprintf((char *)IObuff, _("Vim: Caught deadly signal\n")); #endif preserve_exit(); /* preserve files and exit */ #ifdef NBDEBUG reset_signals(); may_core_dump(); abort(); #endif SIGRETURN; } #if defined(_REENTRANT) && defined(SIGCONT) /* * On Solaris with multi-threading, suspending might not work immediately. * Catch the SIGCONT signal, which will be used as an indication whether the * suspending has been done or not. * * On Linux, signal is not always handled immediately either. * See https://bugs.launchpad.net/bugs/291373 * * volatile because it is used in signal handler sigcont_handler(). */ static volatile int sigcont_received; static RETSIGTYPE sigcont_handler __ARGS(SIGPROTOARG); /* * signal handler for SIGCONT */ static RETSIGTYPE sigcont_handler SIGDEFARG(sigarg) { sigcont_received = TRUE; SIGRETURN; } #endif # if defined(FEAT_CLIPBOARD) && defined(FEAT_X11) static void loose_clipboard __ARGS((void)); /* * Called when Vim is going to sleep or execute a shell command. * We can't respond to requests for the X selections. Lose them, otherwise * other applications will hang. But first copy the text to cut buffer 0. */ static void loose_clipboard() { if (clip_star.owned || clip_plus.owned) { x11_export_final_selection(); if (clip_star.owned) clip_lose_selection(&clip_star); if (clip_plus.owned) clip_lose_selection(&clip_plus); if (x11_display != NULL) XFlush(x11_display); } } #endif /* * If the machine has job control, use it to suspend the program, * otherwise fake it by starting a new shell. */ void mch_suspend() { /* BeOS does have SIGTSTP, but it doesn't work. */ #if defined(SIGTSTP) && !defined(__BEOS__) out_flush(); /* needed to make cursor visible on some systems */ settmode(TMODE_COOK); out_flush(); /* needed to disable mouse on some systems */ # if defined(FEAT_CLIPBOARD) && defined(FEAT_X11) loose_clipboard(); # endif # if defined(_REENTRANT) && defined(SIGCONT) sigcont_received = FALSE; # endif kill(0, SIGTSTP); /* send ourselves a STOP signal */ # if defined(_REENTRANT) && defined(SIGCONT) /* * Wait for the SIGCONT signal to be handled. It generally happens * immediately, but somehow not all the time. Do not call pause() * because there would be race condition which would hang Vim if * signal happened in between the test of sigcont_received and the * call to pause(). If signal is not yet received, call sleep(0) * to just yield CPU. Signal should then be received. If somehow * it's still not received, sleep 1, 2, 3 ms. Don't bother waiting * further if signal is not received after 1+2+3+4 ms (not expected * to happen). */ { long wait_time; for (wait_time = 0; !sigcont_received && wait_time <= 3L; wait_time++) /* Loop is not entered most of the time */ mch_delay(wait_time, FALSE); } # endif # ifdef FEAT_TITLE /* * Set oldtitle to NULL, so the current title is obtained again. */ vim_free(oldtitle); oldtitle = NULL; # endif settmode(TMODE_RAW); need_check_timestamps = TRUE; did_check_timestamps = FALSE; #else suspend_shell(); #endif } void mch_init() { Columns = 80; Rows = 24; out_flush(); set_signals(); #ifdef MACOS_CONVERT mac_conv_init(); #endif } static void set_signals() { #if defined(SIGWINCH) /* * WINDOW CHANGE signal is handled with sig_winch(). */ signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch); #endif /* * We want the STOP signal to work, to make mch_suspend() work. * For "rvim" the STOP signal is ignored. */ #ifdef SIGTSTP signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL); #endif #if defined(_REENTRANT) && defined(SIGCONT) signal(SIGCONT, sigcont_handler); #endif /* * We want to ignore breaking of PIPEs. */ #ifdef SIGPIPE signal(SIGPIPE, SIG_IGN); #endif #ifdef SIGINT catch_int_signal(); #endif /* * Ignore alarm signals (Perl's alarm() generates it). */ #ifdef SIGALRM signal(SIGALRM, SIG_IGN); #endif /* * Catch SIGPWR (power failure?) to preserve the swap files, so that no * work will be lost. */ #ifdef SIGPWR signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr); #endif /* * Arrange for other signals to gracefully shutdown Vim. */ catch_signals(deathtrap, SIG_ERR); #if defined(FEAT_GUI) && defined(SIGHUP) /* * When the GUI is running, ignore the hangup signal. */ if (gui.in_use) signal(SIGHUP, SIG_IGN); #endif } #if defined(SIGINT) || defined(PROTO) /* * Catch CTRL-C (only works while in Cooked mode). */ static void catch_int_signal() { signal(SIGINT, (RETSIGTYPE (*)())catch_sigint); } #endif void reset_signals() { catch_signals(SIG_DFL, SIG_DFL); #if defined(_REENTRANT) && defined(SIGCONT) /* SIGCONT isn't in the list, because its default action is ignore */ signal(SIGCONT, SIG_DFL); #endif } static void catch_signals(func_deadly, func_other) RETSIGTYPE (*func_deadly)(); RETSIGTYPE (*func_other)(); { int i; for (i = 0; signal_info[i].sig != -1; i++) if (signal_info[i].deadly) { #if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION) struct sigaction sa; /* Setup to use the alternate stack for the signal function. */ sa.sa_handler = func_deadly; sigemptyset(&sa.sa_mask); # if defined(__linux__) && defined(_REENTRANT) /* On Linux, with glibc compiled for kernel 2.2, there is a bug in * thread handling in combination with using the alternate stack: * pthread library functions try to use the stack pointer to * identify the current thread, causing a SEGV signal, which * recursively calls deathtrap() and hangs. */ sa.sa_flags = 0; # else sa.sa_flags = SA_ONSTACK; # endif sigaction(signal_info[i].sig, &sa, NULL); #else # if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGVEC) struct sigvec sv; /* Setup to use the alternate stack for the signal function. */ sv.sv_handler = func_deadly; sv.sv_mask = 0; sv.sv_flags = SV_ONSTACK; sigvec(signal_info[i].sig, &sv, NULL); # else signal(signal_info[i].sig, func_deadly); # endif #endif } else if (func_other != SIG_ERR) signal(signal_info[i].sig, func_other); } /* * Handling of SIGHUP, SIGQUIT and SIGTERM: * "when" == a signal: when busy, postpone and return FALSE, otherwise * return TRUE * "when" == SIGNAL_BLOCK: Going to be busy, block signals * "when" == SIGNAL_UNBLOCK: Going to wait, unblock signals, use postponed * signal * Returns TRUE when Vim should exit. */ int vim_handle_signal(sig) int sig; { static int got_signal = 0; static int blocked = TRUE; switch (sig) { case SIGNAL_BLOCK: blocked = TRUE; break; case SIGNAL_UNBLOCK: blocked = FALSE; if (got_signal != 0) { kill(getpid(), got_signal); got_signal = 0; } break; default: if (!blocked) return TRUE; /* exit! */ got_signal = sig; #ifdef SIGPWR if (sig != SIGPWR) #endif got_int = TRUE; /* break any loops */ break; } return FALSE; } /* * Check_win checks whether we have an interactive stdout. */ int mch_check_win(argc, argv) int argc UNUSED; char **argv UNUSED; { #ifdef OS2 /* * Store argv[0], may be used for $VIM. Only use it if it is an absolute * name, mostly it's just "vim" and found in the path, which is unusable. */ if (mch_isFullName(argv[0])) exe_name = vim_strsave((char_u *)argv[0]); #endif if (isatty(1)) return OK; return FAIL; } /* * Return TRUE if the input comes from a terminal, FALSE otherwise. */ int mch_input_isatty() { if (isatty(read_cmd_fd)) return TRUE; return FALSE; } #ifdef FEAT_X11 # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) \ && (defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE)) static void xopen_message __ARGS((struct timeval *tvp)); /* * Give a message about the elapsed time for opening the X window. */ static void xopen_message(tvp) struct timeval *tvp; /* must contain start time */ { struct timeval end_tv; /* Compute elapsed time. */ gettimeofday(&end_tv, NULL); smsg((char_u *)_("Opening the X display took %ld msec"), (end_tv.tv_sec - tvp->tv_sec) * 1000L + (end_tv.tv_usec - tvp->tv_usec) / 1000L); } # endif #endif #if defined(FEAT_X11) && (defined(FEAT_TITLE) || defined(FEAT_XCLIPBOARD)) /* * A few functions shared by X11 title and clipboard code. */ static int x_error_handler __ARGS((Display *dpy, XErrorEvent *error_event)); static int x_error_check __ARGS((Display *dpy, XErrorEvent *error_event)); static int x_connect_to_server __ARGS((void)); static int test_x11_window __ARGS((Display *dpy)); static int got_x_error = FALSE; /* * X Error handler, otherwise X just exits! (very rude) -- webb */ static int x_error_handler(dpy, error_event) Display *dpy; XErrorEvent *error_event; { XGetErrorText(dpy, error_event->error_code, (char *)IObuff, IOSIZE); STRCAT(IObuff, _("\nVim: Got X error\n")); /* We cannot print a message and continue, because no X calls are allowed * here (causes my system to hang). Silently continuing might be an * alternative... */ preserve_exit(); /* preserve files and exit */ return 0; /* NOTREACHED */ } /* * Another X Error handler, just used to check for errors. */ static int x_error_check(dpy, error_event) Display *dpy UNUSED; XErrorEvent *error_event UNUSED; { got_x_error = TRUE; return 0; } #if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD) # if defined(HAVE_SETJMP_H) /* * An X IO Error handler, used to catch error while opening the display. */ static int x_IOerror_check __ARGS((Display *dpy)); static int x_IOerror_check(dpy) Display *dpy UNUSED; { /* This function should not return, it causes exit(). Longjump instead. */ LONGJMP(lc_jump_env, 1); # ifdef VMS return 0; /* avoid the compiler complains about missing return value */ # endif } # endif /* * An X IO Error handler, used to catch terminal errors. */ static int x_IOerror_handler __ARGS((Display *dpy)); static int x_IOerror_handler(dpy) Display *dpy UNUSED; { xterm_dpy = NULL; x11_window = 0; x11_display = NULL; xterm_Shell = (Widget)0; /* This function should not return, it causes exit(). Longjump instead. */ LONGJMP(x_jump_env, 1); # ifdef VMS return 0; /* avoid the compiler complains about missing return value */ # endif } #endif /* * Return TRUE when connection to the X server is desired. */ static int x_connect_to_server() { regmatch_T regmatch; #if defined(FEAT_CLIENTSERVER) if (x_force_connect) return TRUE; #endif if (x_no_connect) return FALSE; /* Check for a match with "exclude:" from 'clipboard'. */ if (clip_exclude_prog != NULL) { regmatch.rm_ic = FALSE; /* Don't ignore case */ regmatch.regprog = clip_exclude_prog; if (vim_regexec(&regmatch, T_NAME, (colnr_T)0)) return FALSE; } return TRUE; } /* * Test if "dpy" and x11_window are valid by getting the window title. * I don't actually want it yet, so there may be a simpler call to use, but * this will cause the error handler x_error_check() to be called if anything * is wrong, such as the window pointer being invalid (as can happen when the * user changes his DISPLAY, but not his WINDOWID) -- webb */ static int test_x11_window(dpy) Display *dpy; { int (*old_handler)(); XTextProperty text_prop; old_handler = XSetErrorHandler(x_error_check); got_x_error = FALSE; if (XGetWMName(dpy, x11_window, &text_prop)) XFree((void *)text_prop.value); XSync(dpy, False); (void)XSetErrorHandler(old_handler); if (p_verbose > 0 && got_x_error) verb_msg((char_u *)_("Testing the X display failed")); return (got_x_error ? FAIL : OK); } #endif #ifdef FEAT_TITLE #ifdef FEAT_X11 static int get_x11_thing __ARGS((int get_title, int test_only)); /* * try to get x11 window and display * * return FAIL for failure, OK otherwise */ static int get_x11_windis() { char *winid; static int result = -1; #define XD_NONE 0 /* x11_display not set here */ #define XD_HERE 1 /* x11_display opened here */ #define XD_GUI 2 /* x11_display used from gui.dpy */ #define XD_XTERM 3 /* x11_display used from xterm_dpy */ static int x11_display_from = XD_NONE; static int did_set_error_handler = FALSE; if (!did_set_error_handler) { /* X just exits if it finds an error otherwise! */ (void)XSetErrorHandler(x_error_handler); did_set_error_handler = TRUE; } #if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK) if (gui.in_use) { /* * If the X11 display was opened here before, for the window where Vim * was started, close that one now to avoid a memory leak. */ if (x11_display_from == XD_HERE && x11_display != NULL) { XCloseDisplay(x11_display); x11_display_from = XD_NONE; } if (gui_get_x11_windis(&x11_window, &x11_display) == OK) { x11_display_from = XD_GUI; return OK; } x11_display = NULL; return FAIL; } else if (x11_display_from == XD_GUI) { /* GUI must have stopped somehow, clear x11_display */ x11_window = 0; x11_display = NULL; x11_display_from = XD_NONE; } #endif /* When started with the "-X" argument, don't try connecting. */ if (!x_connect_to_server()) return FAIL; /* * If WINDOWID not set, should try another method to find out * what the current window number is. The only code I know for * this is very complicated. * We assume that zero is invalid for WINDOWID. */ if (x11_window == 0 && (winid = getenv("WINDOWID")) != NULL) x11_window = (Window)atol(winid); #ifdef FEAT_XCLIPBOARD if (xterm_dpy != NULL && x11_window != 0) { /* We may have checked it already, but Gnome terminal can move us to * another window, so we need to check every time. */ if (x11_display_from != XD_XTERM) { /* * If the X11 display was opened here before, for the window where * Vim was started, close that one now to avoid a memory leak. */ if (x11_display_from == XD_HERE && x11_display != NULL) XCloseDisplay(x11_display); x11_display = xterm_dpy; x11_display_from = XD_XTERM; } if (test_x11_window(x11_display) == FAIL) { /* probably bad $WINDOWID */ x11_window = 0; x11_display = NULL; x11_display_from = XD_NONE; return FAIL; } return OK; } #endif if (x11_window == 0 || x11_display == NULL) result = -1; if (result != -1) /* Have already been here and set this */ return result; /* Don't do all these X calls again */ if (x11_window != 0 && x11_display == NULL) { #ifdef SET_SIG_ALARM RETSIGTYPE (*sig_save)(); #endif #if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) struct timeval start_tv; if (p_verbose > 0) gettimeofday(&start_tv, NULL); #endif #ifdef SET_SIG_ALARM /* * Opening the Display may hang if the DISPLAY setting is wrong, or * the network connection is bad. Set an alarm timer to get out. */ sig_alarm_called = FALSE; sig_save = (RETSIGTYPE (*)())signal(SIGALRM, (RETSIGTYPE (*)())sig_alarm); alarm(2); #endif x11_display = XOpenDisplay(NULL); #ifdef SET_SIG_ALARM alarm(0); signal(SIGALRM, (RETSIGTYPE (*)())sig_save); if (p_verbose > 0 && sig_alarm_called) verb_msg((char_u *)_("Opening the X display timed out")); #endif if (x11_display != NULL) { # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) if (p_verbose > 0) { verbose_enter(); xopen_message(&start_tv); verbose_leave(); } # endif if (test_x11_window(x11_display) == FAIL) { /* Maybe window id is bad */ x11_window = 0; XCloseDisplay(x11_display); x11_display = NULL; } else x11_display_from = XD_HERE; } } if (x11_window == 0 || x11_display == NULL) return (result = FAIL); # ifdef FEAT_EVAL set_vim_var_nr(VV_WINDOWID, (long)x11_window); # endif return (result = OK); } /* * Determine original x11 Window Title */ static int get_x11_title(test_only) int test_only; { return get_x11_thing(TRUE, test_only); } /* * Determine original x11 Window icon */ static int get_x11_icon(test_only) int test_only; { int retval = FALSE; retval = get_x11_thing(FALSE, test_only); /* could not get old icon, use terminal name */ if (oldicon == NULL && !test_only) { if (STRNCMP(T_NAME, "builtin_", 8) == 0) oldicon = vim_strsave(T_NAME + 8); else oldicon = vim_strsave(T_NAME); } return retval; } static int get_x11_thing(get_title, test_only) int get_title; /* get title string */ int test_only; { XTextProperty text_prop; int retval = FALSE; Status status; if (get_x11_windis() == OK) { /* Get window/icon name if any */ if (get_title) status = XGetWMName(x11_display, x11_window, &text_prop); else status = XGetWMIconName(x11_display, x11_window, &text_prop); /* * If terminal is xterm, then x11_window may be a child window of the * outer xterm window that actually contains the window/icon name, so * keep traversing up the tree until a window with a title/icon is * found. */ /* Previously this was only done for xterm and alikes. I don't see a * reason why it would fail for other terminal emulators. * if (term_is_xterm) */ { Window root; Window parent; Window win = x11_window; Window *children; unsigned int num_children; while (!status || text_prop.value == NULL) { if (!XQueryTree(x11_display, win, &root, &parent, &children, &num_children)) break; if (children) XFree((void *)children); if (parent == root || parent == 0) break; win = parent; if (get_title) status = XGetWMName(x11_display, win, &text_prop); else status = XGetWMIconName(x11_display, win, &text_prop); } } if (status && text_prop.value != NULL) { retval = TRUE; if (!test_only) { #if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE) if (text_prop.encoding == XA_STRING # ifdef FEAT_MBYTE && !has_mbyte # endif ) { #endif if (get_title) oldtitle = vim_strsave((char_u *)text_prop.value); else oldicon = vim_strsave((char_u *)text_prop.value); #if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE) } else { char **cl; Status transform_status; int n = 0; transform_status = XmbTextPropertyToTextList(x11_display, &text_prop, &cl, &n); if (transform_status >= Success && n > 0 && cl[0]) { if (get_title) oldtitle = vim_strsave((char_u *) cl[0]); else oldicon = vim_strsave((char_u *) cl[0]); XFreeStringList(cl); } else { if (get_title) oldtitle = vim_strsave((char_u *)text_prop.value); else oldicon = vim_strsave((char_u *)text_prop.value); } } #endif } XFree((void *)text_prop.value); } } return retval; } /* Are Xutf8 functions available? Avoid error from old compilers. */ #if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE) # if X_HAVE_UTF8_STRING # define USE_UTF8_STRING # endif #endif /* * Set x11 Window Title * * get_x11_windis() must be called before this and have returned OK */ static void set_x11_title(title) char_u *title; { /* XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING * when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't * supported everywhere and STRING doesn't work for multi-byte titles. */ #ifdef USE_UTF8_STRING if (enc_utf8) Xutf8SetWMProperties(x11_display, x11_window, (const char *)title, NULL, NULL, 0, NULL, NULL, NULL); else #endif { #if XtSpecificationRelease >= 4 # ifdef FEAT_XFONTSET XmbSetWMProperties(x11_display, x11_window, (const char *)title, NULL, NULL, 0, NULL, NULL, NULL); # else XTextProperty text_prop; char *c_title = (char *)title; /* directly from example 3-18 "basicwin" of Xlib Programming Manual */ (void)XStringListToTextProperty(&c_title, 1, &text_prop); XSetWMProperties(x11_display, x11_window, &text_prop, NULL, NULL, 0, NULL, NULL, NULL); # endif #else XStoreName(x11_display, x11_window, (char *)title); #endif } XFlush(x11_display); } /* * Set x11 Window icon * * get_x11_windis() must be called before this and have returned OK */ static void set_x11_icon(icon) char_u *icon; { /* See above for comments about using X*SetWMProperties(). */ #ifdef USE_UTF8_STRING if (enc_utf8) Xutf8SetWMProperties(x11_display, x11_window, NULL, (const char *)icon, NULL, 0, NULL, NULL, NULL); else #endif { #if XtSpecificationRelease >= 4 # ifdef FEAT_XFONTSET XmbSetWMProperties(x11_display, x11_window, NULL, (const char *)icon, NULL, 0, NULL, NULL, NULL); # else XTextProperty text_prop; char *c_icon = (char *)icon; (void)XStringListToTextProperty(&c_icon, 1, &text_prop); XSetWMProperties(x11_display, x11_window, NULL, &text_prop, NULL, 0, NULL, NULL, NULL); # endif #else XSetIconName(x11_display, x11_window, (char *)icon); #endif } XFlush(x11_display); } #else /* FEAT_X11 */ static int get_x11_title(test_only) int test_only UNUSED; { return FALSE; } static int get_x11_icon(test_only) int test_only; { if (!test_only) { if (STRNCMP(T_NAME, "builtin_", 8) == 0) oldicon = vim_strsave(T_NAME + 8); else oldicon = vim_strsave(T_NAME); } return FALSE; } #endif /* FEAT_X11 */ int mch_can_restore_title() { return get_x11_title(TRUE); } int mch_can_restore_icon() { return get_x11_icon(TRUE); } /* * Set the window title and icon. */ void mch_settitle(title, icon) char_u *title; char_u *icon; { int type = 0; static int recursive = 0; if (T_NAME == NULL) /* no terminal name (yet) */ return; if (title == NULL && icon == NULL) /* nothing to do */ return; /* When one of the X11 functions causes a deadly signal, we get here again * recursively. Avoid hanging then (something is probably locked). */ if (recursive) return; ++recursive; /* * if the window ID and the display is known, we may use X11 calls */ #ifdef FEAT_X11 if (get_x11_windis() == OK) type = 1; #else # if defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_GTK) if (gui.in_use) type = 1; # endif #endif /* * Note: if "t_ts" is set, title is set with escape sequence rather * than x11 calls, because the x11 calls don't always work */ if ((type || *T_TS != NUL) && title != NULL) { if (oldtitle == NULL #ifdef FEAT_GUI && !gui.in_use #endif ) /* first call but not in GUI, save title */ (void)get_x11_title(FALSE); if (*T_TS != NUL) /* it's OK if t_fs is empty */ term_settitle(title); #ifdef FEAT_X11 else # ifdef FEAT_GUI_GTK if (!gui.in_use) /* don't do this if GTK+ is running */ # endif set_x11_title(title); /* x11 */ #endif #if defined(FEAT_GUI_GTK) \ || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) else gui_mch_settitle(title, icon); #endif did_set_title = TRUE; } if ((type || *T_CIS != NUL) && icon != NULL) { if (oldicon == NULL #ifdef FEAT_GUI && !gui.in_use #endif ) /* first call, save icon */ get_x11_icon(FALSE); if (*T_CIS != NUL) { out_str(T_CIS); /* set icon start */ out_str_nf(icon); out_str(T_CIE); /* set icon end */ out_flush(); } #ifdef FEAT_X11 else # ifdef FEAT_GUI_GTK if (!gui.in_use) /* don't do this if GTK+ is running */ # endif set_x11_icon(icon); /* x11 */ #endif did_set_icon = TRUE; } --recursive; } /* * Restore the window/icon title. * "which" is one of: * 1 only restore title * 2 only restore icon * 3 restore title and icon */ void mch_restore_title(which) int which; { /* only restore the title or icon when it has been set */ mch_settitle(((which & 1) && did_set_title) ? (oldtitle ? oldtitle : p_titleold) : NULL, ((which & 2) && did_set_icon) ? oldicon : NULL); } #endif /* FEAT_TITLE */ /* * Return TRUE if "name" looks like some xterm name. * Seiichi Sato mentioned that "mlterm" works like xterm. */ int vim_is_xterm(name) char_u *name; { if (name == NULL) return FALSE; return (STRNICMP(name, "xterm", 5) == 0 || STRNICMP(name, "nxterm", 6) == 0 || STRNICMP(name, "kterm", 5) == 0 || STRNICMP(name, "mlterm", 6) == 0 || STRNICMP(name, "rxvt", 4) == 0 || STRCMP(name, "builtin_xterm") == 0); } #if defined(FEAT_MOUSE_XTERM) || defined(PROTO) /* * Return TRUE if "name" appears to be that of a terminal * known to support the xterm-style mouse protocol. * Relies on term_is_xterm having been set to its correct value. */ int use_xterm_like_mouse(name) char_u *name; { return (name != NULL && (term_is_xterm || STRNICMP(name, "screen", 6) == 0)); } #endif #if defined(FEAT_MOUSE_TTY) || defined(PROTO) /* * Return non-zero when using an xterm mouse, according to 'ttymouse'. * Return 1 for "xterm". * Return 2 for "xterm2". * Return 3 for "urxvt". */ int use_xterm_mouse() { if (ttym_flags == TTYM_URXVT) return 3; if (ttym_flags == TTYM_XTERM2) return 2; if (ttym_flags == TTYM_XTERM) return 1; return 0; } #endif int vim_is_iris(name) char_u *name; { if (name == NULL) return FALSE; return (STRNICMP(name, "iris-ansi", 9) == 0 || STRCMP(name, "builtin_iris-ansi") == 0); } int vim_is_vt300(name) char_u *name; { if (name == NULL) return FALSE; /* actually all ANSI comp. terminals should be here */ /* catch VT100 - VT5xx */ return ((STRNICMP(name, "vt", 2) == 0 && vim_strchr((char_u *)"12345", name[2]) != NULL) || STRCMP(name, "builtin_vt320") == 0); } /* * Return TRUE if "name" is a terminal for which 'ttyfast' should be set. * This should include all windowed terminal emulators. */ int vim_is_fastterm(name) char_u *name; { if (name == NULL) return FALSE; if (vim_is_xterm(name) || vim_is_vt300(name) || vim_is_iris(name)) return TRUE; return ( STRNICMP(name, "hpterm", 6) == 0 || STRNICMP(name, "sun-cmd", 7) == 0 || STRNICMP(name, "screen", 6) == 0 || STRNICMP(name, "dtterm", 6) == 0); } /* * Insert user name in s[len]. * Return OK if a name found. */ int mch_get_user_name(s, len) char_u *s; int len; { #ifdef VMS vim_strncpy(s, (char_u *)cuserid(NULL), len - 1); return OK; #else return mch_get_uname(getuid(), s, len); #endif } /* * Insert user name for "uid" in s[len]. * Return OK if a name found. */ int mch_get_uname(uid, s, len) uid_t uid; char_u *s; int len; { #if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID) struct passwd *pw; if ((pw = getpwuid(uid)) != NULL && pw->pw_name != NULL && *(pw->pw_name) != NUL) { vim_strncpy(s, (char_u *)pw->pw_name, len - 1); return OK; } #endif sprintf((char *)s, "%d", (int)uid); /* assumes s is long enough */ return FAIL; /* a number is not a name */ } /* * Insert host name is s[len]. */ #ifdef HAVE_SYS_UTSNAME_H void mch_get_host_name(s, len) char_u *s; int len; { struct utsname vutsname; if (uname(&vutsname) < 0) *s = NUL; else vim_strncpy(s, (char_u *)vutsname.nodename, len - 1); } #else /* HAVE_SYS_UTSNAME_H */ # ifdef HAVE_SYS_SYSTEMINFO_H # define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len) # endif void mch_get_host_name(s, len) char_u *s; int len; { # ifdef VAXC vaxc$gethostname((char *)s, len); # else gethostname((char *)s, len); # endif s[len - 1] = NUL; /* make sure it's terminated */ } #endif /* HAVE_SYS_UTSNAME_H */ /* * return process ID */ long mch_get_pid() { return (long)getpid(); } #if !defined(HAVE_STRERROR) && defined(USE_GETCWD) static char *strerror __ARGS((int)); static char * strerror(err) int err; { extern int sys_nerr; extern char *sys_errlist[]; static char er[20]; if (err > 0 && err < sys_nerr) return (sys_errlist[err]); sprintf(er, "Error %d", err); return er; } #endif /* * Get name of current directory into buffer 'buf' of length 'len' bytes. * Return OK for success, FAIL for failure. */ int mch_dirname(buf, len) char_u *buf; int len; { #if defined(USE_GETCWD) if (getcwd((char *)buf, len) == NULL) { STRCPY(buf, strerror(errno)); return FAIL; } return OK; #else return (getwd((char *)buf) != NULL ? OK : FAIL); #endif } #if defined(OS2) || defined(PROTO) /* * Replace all slashes by backslashes. * When 'shellslash' set do it the other way around. */ void slash_adjust(p) char_u *p; { while (*p) { if (*p == psepcN) *p = psepc; mb_ptr_adv(p); } } #endif /* * Get absolute file name into "buf[len]". * * return FAIL for failure, OK for success */ int mch_FullName(fname, buf, len, force) char_u *fname, *buf; int len; int force; /* also expand when already absolute path */ { int l; #ifdef OS2 int only_drive; /* file name is only a drive letter */ #endif #ifdef HAVE_FCHDIR int fd = -1; static int dont_fchdir = FALSE; /* TRUE when fchdir() doesn't work */ #endif char_u olddir[MAXPATHL]; char_u *p; int retval = OK; #ifdef __CYGWIN__ char_u posix_fname[MAXPATHL]; /* Cygwin docs mention MAX_PATH, but it's not always defined */ #endif #ifdef VMS fname = vms_fixfilename(fname); #endif #ifdef __CYGWIN__ /* * This helps for when "/etc/hosts" is a symlink to "c:/something/hosts". */ # if CYGWIN_VERSION_DLL_MAJOR >= 1007 cygwin_conv_path(CCP_WIN_A_TO_POSIX, fname, posix_fname, MAXPATHL); # else cygwin_conv_to_posix_path(fname, posix_fname); # endif fname = posix_fname; #endif /* expand it if forced or not an absolute path */ if (force || !mch_isFullName(fname)) { /* * If the file name has a path, change to that directory for a moment, * and then do the getwd() (and get back to where we were). * This will get the correct path name with "../" things. */ #ifdef OS2 only_drive = 0; if (((p = vim_strrchr(fname, '/')) != NULL) || ((p = vim_strrchr(fname, '\\')) != NULL) || (((p = vim_strchr(fname, ':')) != NULL) && ++only_drive)) #else if ((p = vim_strrchr(fname, '/')) != NULL) #endif { #ifdef HAVE_FCHDIR /* * Use fchdir() if possible, it's said to be faster and more * reliable. But on SunOS 4 it might not work. Check this by * doing a fchdir() right now. */ if (!dont_fchdir) { fd = open(".", O_RDONLY | O_EXTRA, 0); if (fd >= 0 && fchdir(fd) < 0) { close(fd); fd = -1; dont_fchdir = TRUE; /* don't try again */ } } #endif /* Only change directory when we are sure we can return to where * we are now. After doing "su" chdir(".") might not work. */ if ( #ifdef HAVE_FCHDIR fd < 0 && #endif (mch_dirname(olddir, MAXPATHL) == FAIL || mch_chdir((char *)olddir) != 0)) { p = NULL; /* can't get current dir: don't chdir */ retval = FAIL; } else { #ifdef OS2 /* * compensate for case where ':' from "D:" was the only * path separator detected in the file name; the _next_ * character has to be removed, and then restored later. */ if (only_drive) p++; #endif /* The directory is copied into buf[], to be able to remove * the file name without changing it (could be a string in * read-only memory) */ if (p - fname >= len) retval = FAIL; else { vim_strncpy(buf, fname, p - fname); if (mch_chdir((char *)buf)) retval = FAIL; else fname = p + 1; *buf = NUL; } #ifdef OS2 if (only_drive) { p--; if (retval != FAIL) fname--; } #endif } } if (mch_dirname(buf, len) == FAIL) { retval = FAIL; *buf = NUL; } if (p != NULL) { #ifdef HAVE_FCHDIR if (fd >= 0) { if (p_verbose >= 5) { verbose_enter(); MSG("fchdir() to previous dir"); verbose_leave(); } l = fchdir(fd); close(fd); } else #endif l = mch_chdir((char *)olddir); if (l != 0) EMSG(_(e_prev_dir)); } l = STRLEN(buf); if (l >= len) retval = FAIL; #ifndef VMS else { if (l > 0 && buf[l - 1] != '/' && *fname != NUL && STRCMP(fname, ".") != 0) STRCAT(buf, "/"); } #endif } /* Catch file names which are too long. */ if (retval == FAIL || (int)(STRLEN(buf) + STRLEN(fname)) >= len) return FAIL; /* Do not append ".", "/dir/." is equal to "/dir". */ if (STRCMP(fname, ".") != 0) STRCAT(buf, fname); return OK; } /* * Return TRUE if "fname" does not depend on the current directory. */ int mch_isFullName(fname) char_u *fname; { #ifdef __EMX__ return _fnisabs(fname); #else # ifdef VMS return ( fname[0] == '/' || fname[0] == '.' || strchr((char *)fname,':') || strchr((char *)fname,'"') || (strchr((char *)fname,'[') && strchr((char *)fname,']'))|| (strchr((char *)fname,'<') && strchr((char *)fname,'>')) ); # else return (*fname == '/' || *fname == '~'); # endif #endif } #if defined(USE_FNAME_CASE) || defined(PROTO) /* * Set the case of the file name, if it already exists. This will cause the * file name to remain exactly the same. * Only required for file systems where case is ignored and preserved. */ void fname_case(name, len) char_u *name; int len UNUSED; /* buffer size, only used when name gets longer */ { struct stat st; char_u *slash, *tail; DIR *dirp; struct dirent *dp; if (lstat((char *)name, &st) >= 0) { /* Open the directory where the file is located. */ slash = vim_strrchr(name, '/'); if (slash == NULL) { dirp = opendir("."); tail = name; } else { *slash = NUL; dirp = opendir((char *)name); *slash = '/'; tail = slash + 1; } if (dirp != NULL) { while ((dp = readdir(dirp)) != NULL) { /* Only accept names that differ in case and are the same byte * length. TODO: accept different length name. */ if (STRICMP(tail, dp->d_name) == 0 && STRLEN(tail) == STRLEN(dp->d_name)) { char_u newname[MAXPATHL + 1]; struct stat st2; /* Verify the inode is equal. */ vim_strncpy(newname, name, MAXPATHL); vim_strncpy(newname + (tail - name), (char_u *)dp->d_name, MAXPATHL - (tail - name)); if (lstat((char *)newname, &st2) >= 0 && st.st_ino == st2.st_ino && st.st_dev == st2.st_dev) { STRCPY(tail, dp->d_name); break; } } } closedir(dirp); } } } #endif /* * Get file permissions for 'name'. * Returns -1 when it doesn't exist. */ long mch_getperm(name) char_u *name; { struct stat statb; /* Keep the #ifdef outside of stat(), it may be a macro. */ #ifdef VMS if (stat((char *)vms_fixfilename(name), &statb)) #else if (stat((char *)name, &statb)) #endif return -1; #ifdef __INTERIX /* The top bit makes the value negative, which means the file doesn't * exist. Remove the bit, we don't use it. */ return statb.st_mode & ~S_ADDACE; #else return statb.st_mode; #endif } /* * set file permission for 'name' to 'perm' * * return FAIL for failure, OK otherwise */ int mch_setperm(name, perm) char_u *name; long perm; { return (chmod((char *) #ifdef VMS vms_fixfilename(name), #else name, #endif (mode_t)perm) == 0 ? OK : FAIL); } #if defined(HAVE_ACL) || defined(PROTO) # ifdef HAVE_SYS_ACL_H # include <sys/acl.h> # endif # ifdef HAVE_SYS_ACCESS_H # include <sys/access.h> # endif # ifdef HAVE_SOLARIS_ACL typedef struct vim_acl_solaris_T { int acl_cnt; aclent_t *acl_entry; } vim_acl_solaris_T; # endif #if defined(HAVE_SELINUX) || defined(PROTO) /* * Copy security info from "from_file" to "to_file". */ void mch_copy_sec(from_file, to_file) char_u *from_file; char_u *to_file; { if (from_file == NULL) return; if (selinux_enabled == -1) selinux_enabled = is_selinux_enabled(); if (selinux_enabled > 0) { security_context_t from_context = NULL; security_context_t to_context = NULL; if (getfilecon((char *)from_file, &from_context) < 0) { /* If the filesystem doesn't support extended attributes, the original had no special security context and the target cannot have one either. */ if (errno == EOPNOTSUPP) return; MSG_PUTS(_("\nCould not get security context for ")); msg_outtrans(from_file); msg_putchar('\n'); return; } if (getfilecon((char *)to_file, &to_context) < 0) { MSG_PUTS(_("\nCould not get security context for ")); msg_outtrans(to_file); msg_putchar('\n'); freecon (from_context); return ; } if (strcmp(from_context, to_context) != 0) { if (setfilecon((char *)to_file, from_context) < 0) { MSG_PUTS(_("\nCould not set security context for ")); msg_outtrans(to_file); msg_putchar('\n'); } } freecon(to_context); freecon(from_context); } } #endif /* HAVE_SELINUX */ /* * Return a pointer to the ACL of file "fname" in allocated memory. * Return NULL if the ACL is not available for whatever reason. */ vim_acl_T mch_get_acl(fname) char_u *fname UNUSED; { vim_acl_T ret = NULL; #ifdef HAVE_POSIX_ACL ret = (vim_acl_T)acl_get_file((char *)fname, ACL_TYPE_ACCESS); #else #ifdef HAVE_SOLARIS_ZFS_ACL acl_t *aclent; if (acl_get((char *)fname, 0, &aclent) < 0) return NULL; ret = (vim_acl_T)aclent; #else #ifdef HAVE_SOLARIS_ACL vim_acl_solaris_T *aclent; aclent = malloc(sizeof(vim_acl_solaris_T)); if ((aclent->acl_cnt = acl((char *)fname, GETACLCNT, 0, NULL)) < 0) { free(aclent); return NULL; } aclent->acl_entry = malloc(aclent->acl_cnt * sizeof(aclent_t)); if (acl((char *)fname, GETACL, aclent->acl_cnt, aclent->acl_entry) < 0) { free(aclent->acl_entry); free(aclent); return NULL; } ret = (vim_acl_T)aclent; #else #if defined(HAVE_AIX_ACL) int aclsize; struct acl *aclent; aclsize = sizeof(struct acl); aclent = malloc(aclsize); if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0) { if (errno == ENOSPC) { aclsize = aclent->acl_len; aclent = realloc(aclent, aclsize); if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0) { free(aclent); return NULL; } } else { free(aclent); return NULL; } } ret = (vim_acl_T)aclent; #endif /* HAVE_AIX_ACL */ #endif /* HAVE_SOLARIS_ACL */ #endif /* HAVE_SOLARIS_ZFS_ACL */ #endif /* HAVE_POSIX_ACL */ return ret; } /* * Set the ACL of file "fname" to "acl" (unless it's NULL). */ void mch_set_acl(fname, aclent) char_u *fname UNUSED; vim_acl_T aclent; { if (aclent == NULL) return; #ifdef HAVE_POSIX_ACL acl_set_file((char *)fname, ACL_TYPE_ACCESS, (acl_t)aclent); #else #ifdef HAVE_SOLARIS_ZFS_ACL acl_set((char *)fname, (acl_t *)aclent); #else #ifdef HAVE_SOLARIS_ACL acl((char *)fname, SETACL, ((vim_acl_solaris_T *)aclent)->acl_cnt, ((vim_acl_solaris_T *)aclent)->acl_entry); #else #ifdef HAVE_AIX_ACL chacl((char *)fname, aclent, ((struct acl *)aclent)->acl_len); #endif /* HAVE_AIX_ACL */ #endif /* HAVE_SOLARIS_ACL */ #endif /* HAVE_SOLARIS_ZFS_ACL */ #endif /* HAVE_POSIX_ACL */ } void mch_free_acl(aclent) vim_acl_T aclent; { if (aclent == NULL) return; #ifdef HAVE_POSIX_ACL acl_free((acl_t)aclent); #else #ifdef HAVE_SOLARIS_ZFS_ACL acl_free((acl_t *)aclent); #else #ifdef HAVE_SOLARIS_ACL free(((vim_acl_solaris_T *)aclent)->acl_entry); free(aclent); #else #ifdef HAVE_AIX_ACL free(aclent); #endif /* HAVE_AIX_ACL */ #endif /* HAVE_SOLARIS_ACL */ #endif /* HAVE_SOLARIS_ZFS_ACL */ #endif /* HAVE_POSIX_ACL */ } #endif /* * Set hidden flag for "name". */ void mch_hide(name) char_u *name UNUSED; { /* can't hide a file */ } /* * return TRUE if "name" is a directory * return FALSE if "name" is not a directory * return FALSE for error */ int mch_isdir(name) char_u *name; { struct stat statb; if (*name == NUL) /* Some stat()s don't flag "" as an error. */ return FALSE; if (stat((char *)name, &statb)) return FALSE; #ifdef _POSIX_SOURCE return (S_ISDIR(statb.st_mode) ? TRUE : FALSE); #else return ((statb.st_mode & S_IFMT) == S_IFDIR ? TRUE : FALSE); #endif } static int executable_file __ARGS((char_u *name)); /* * Return 1 if "name" is an executable file, 0 if not or it doesn't exist. */ static int executable_file(name) char_u *name; { struct stat st; if (stat((char *)name, &st)) return 0; return S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0; } /* * Return 1 if "name" can be found in $PATH and executed, 0 if not. * Return -1 if unknown. */ int mch_can_exe(name) char_u *name; { char_u *buf; char_u *p, *e; int retval; /* If it's an absolute or relative path don't need to use $PATH. */ if (mch_isFullName(name) || (name[0] == '.' && (name[1] == '/' || (name[1] == '.' && name[2] == '/')))) return executable_file(name); p = (char_u *)getenv("PATH"); if (p == NULL || *p == NUL) return -1; buf = alloc((unsigned)(STRLEN(name) + STRLEN(p) + 2)); if (buf == NULL) return -1; /* * Walk through all entries in $PATH to check if "name" exists there and * is an executable file. */ for (;;) { e = (char_u *)strchr((char *)p, ':'); if (e == NULL) e = p + STRLEN(p); if (e - p <= 1) /* empty entry means current dir */ STRCPY(buf, "./"); else { vim_strncpy(buf, p, e - p); add_pathsep(buf); } STRCAT(buf, name); retval = executable_file(buf); if (retval == 1) break; if (*e != ':') break; p = e + 1; } vim_free(buf); return retval; } /* * Check what "name" is: * NODE_NORMAL: file or directory (or doesn't exist) * NODE_WRITABLE: writable device, socket, fifo, etc. * NODE_OTHER: non-writable things */ int mch_nodetype(name) char_u *name; { struct stat st; if (stat((char *)name, &st)) return NODE_NORMAL; if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode)) return NODE_NORMAL; #ifndef OS2 if (S_ISBLK(st.st_mode)) /* block device isn't writable */ return NODE_OTHER; #endif /* Everything else is writable? */ return NODE_WRITABLE; } void mch_early_init() { #ifdef HAVE_CHECK_STACK_GROWTH int i; check_stack_growth((char *)&i); # ifdef HAVE_STACK_LIMIT get_stack_limit(); # endif #endif /* * Setup an alternative stack for signals. Helps to catch signals when * running out of stack space. * Use of sigaltstack() is preferred, it's more portable. * Ignore any errors. */ #if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK) signal_stack = (char *)alloc(SIGSTKSZ); init_signal_stack(); #endif } #if defined(EXITFREE) || defined(PROTO) void mch_free_mem() { # if defined(FEAT_CLIPBOARD) && defined(FEAT_X11) if (clip_star.owned) clip_lose_selection(&clip_star); if (clip_plus.owned) clip_lose_selection(&clip_plus); # endif # if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD) if (xterm_Shell != (Widget)0) XtDestroyWidget(xterm_Shell); # ifndef LESSTIF_VERSION /* Lesstif crashes here, lose some memory */ if (xterm_dpy != NULL) XtCloseDisplay(xterm_dpy); if (app_context != (XtAppContext)NULL) { XtDestroyApplicationContext(app_context); # ifdef FEAT_X11 x11_display = NULL; /* freed by XtDestroyApplicationContext() */ # endif } # endif # endif # if defined(FEAT_X11) if (x11_display != NULL # ifdef FEAT_XCLIPBOARD && x11_display != xterm_dpy # endif ) XCloseDisplay(x11_display); # endif # if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK) vim_free(signal_stack); signal_stack = NULL; # endif # ifdef FEAT_TITLE vim_free(oldtitle); vim_free(oldicon); # endif } #endif static void exit_scroll __ARGS((void)); /* * Output a newline when exiting. * Make sure the newline goes to the same stream as the text. */ static void exit_scroll() { if (silent_mode) return; if (newline_on_exit || msg_didout) { if (msg_use_printf()) { if (info_message) mch_msg("\n"); else mch_errmsg("\r\n"); } else out_char('\n'); } else { restore_cterm_colors(); /* get original colors back */ msg_clr_eos_force(); /* clear the rest of the display */ windgoto((int)Rows - 1, 0); /* may have moved the cursor */ } } void mch_exit(r) int r; { exiting = TRUE; #if defined(FEAT_X11) && defined(FEAT_CLIPBOARD) x11_export_final_selection(); #endif #ifdef FEAT_GUI if (!gui.in_use) #endif { settmode(TMODE_COOK); #ifdef FEAT_TITLE mch_restore_title(3); /* restore xterm title and icon name */ #endif /* * When t_ti is not empty but it doesn't cause swapping terminal * pages, need to output a newline when msg_didout is set. But when * t_ti does swap pages it should not go to the shell page. Do this * before stoptermcap(). */ if (swapping_screen() && !newline_on_exit) exit_scroll(); /* Stop termcap: May need to check for T_CRV response, which * requires RAW mode. */ stoptermcap(); /* * A newline is only required after a message in the alternate screen. * This is set to TRUE by wait_return(). */ if (!swapping_screen() || newline_on_exit) exit_scroll(); /* Cursor may have been switched off without calling starttermcap() * when doing "vim -u vimrc" and vimrc contains ":q". */ if (full_screen) cursor_on(); } out_flush(); ml_close_all(TRUE); /* remove all memfiles */ may_core_dump(); #ifdef FEAT_GUI if (gui.in_use) gui_exit(r); #endif #ifdef MACOS_CONVERT mac_conv_cleanup(); #endif #ifdef __QNX__ /* A core dump won't be created if the signal handler * doesn't return, so we can't call exit() */ if (deadly_signal != 0) return; #endif #ifdef FEAT_NETBEANS_INTG netbeans_send_disconnect(); #endif #ifdef EXITFREE free_all_mem(); #endif exit(r); } static void may_core_dump() { if (deadly_signal != 0) { signal(deadly_signal, SIG_DFL); kill(getpid(), deadly_signal); /* Die using the signal we caught */ } } #ifndef VMS void mch_settmode(tmode) int tmode; { static int first = TRUE; /* Why is NeXT excluded here (and not in os_unixx.h)? */ #if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__) /* * for "new" tty systems */ # ifdef HAVE_TERMIOS_H static struct termios told; struct termios tnew; # else static struct termio told; struct termio tnew; # endif if (first) { first = FALSE; # if defined(HAVE_TERMIOS_H) tcgetattr(read_cmd_fd, &told); # else ioctl(read_cmd_fd, TCGETA, &told); # endif } tnew = told; if (tmode == TMODE_RAW) { /* * ~ICRNL enables typing ^V^M */ tnew.c_iflag &= ~ICRNL; tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE # if defined(IEXTEN) && !defined(__MINT__) | IEXTEN /* IEXTEN enables typing ^V on SOLARIS */ /* but it breaks function keys on MINT */ # endif ); # ifdef ONLCR /* don't map NL -> CR NL, we do it ourselves */ tnew.c_oflag &= ~ONLCR; # endif tnew.c_cc[VMIN] = 1; /* return after 1 char */ tnew.c_cc[VTIME] = 0; /* don't wait */ } else if (tmode == TMODE_SLEEP) tnew.c_lflag &= ~(ECHO); # if defined(HAVE_TERMIOS_H) { int n = 10; /* A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a * few times. */ while (tcsetattr(read_cmd_fd, TCSANOW, &tnew) == -1 && errno == EINTR && n > 0) --n; } # else ioctl(read_cmd_fd, TCSETA, &tnew); # endif #else /* * for "old" tty systems */ # ifndef TIOCSETN # define TIOCSETN TIOCSETP /* for hpux 9.0 */ # endif static struct sgttyb ttybold; struct sgttyb ttybnew; if (first) { first = FALSE; ioctl(read_cmd_fd, TIOCGETP, &ttybold); } ttybnew = ttybold; if (tmode == TMODE_RAW) { ttybnew.sg_flags &= ~(CRMOD | ECHO); ttybnew.sg_flags |= RAW; } else if (tmode == TMODE_SLEEP) ttybnew.sg_flags &= ~(ECHO); ioctl(read_cmd_fd, TIOCSETN, &ttybnew); #endif curr_tmode = tmode; } /* * Try to get the code for "t_kb" from the stty setting * * Even if termcap claims a backspace key, the user's setting *should* * prevail. stty knows more about reality than termcap does, and if * somebody's usual erase key is DEL (which, for most BSD users, it will * be), they're going to get really annoyed if their erase key starts * doing forward deletes for no reason. (Eric Fischer) */ void get_stty() { char_u buf[2]; char_u *p; /* Why is NeXT excluded here (and not in os_unixx.h)? */ #if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__) /* for "new" tty systems */ # ifdef HAVE_TERMIOS_H struct termios keys; # else struct termio keys; # endif # if defined(HAVE_TERMIOS_H) if (tcgetattr(read_cmd_fd, &keys) != -1) # else if (ioctl(read_cmd_fd, TCGETA, &keys) != -1) # endif { buf[0] = keys.c_cc[VERASE]; intr_char = keys.c_cc[VINTR]; #else /* for "old" tty systems */ struct sgttyb keys; if (ioctl(read_cmd_fd, TIOCGETP, &keys) != -1) { buf[0] = keys.sg_erase; intr_char = keys.sg_kill; #endif buf[1] = NUL; add_termcode((char_u *)"kb", buf, FALSE); /* * If <BS> and <DEL> are now the same, redefine <DEL>. */ p = find_termcode((char_u *)"kD"); if (p != NULL && p[0] == buf[0] && p[1] == buf[1]) do_fixdel(NULL); } #if 0 } /* to keep cindent happy */ #endif } #endif /* VMS */ #if defined(FEAT_MOUSE_TTY) || defined(PROTO) /* * Set mouse clicks on or off. */ void mch_setmouse(on) int on; { static int ison = FALSE; int xterm_mouse_vers; if (on == ison) /* return quickly if nothing to do */ return; xterm_mouse_vers = use_xterm_mouse(); # ifdef FEAT_MOUSE_URXVT if (ttym_flags == TTYM_URXVT) { out_str_nf((char_u *) (on ? IF_EB("\033[?1015h", ESC_STR "[?1015h") : IF_EB("\033[?1015l", ESC_STR "[?1015l"))); ison = on; } # endif if (xterm_mouse_vers > 0) { if (on) /* enable mouse events, use mouse tracking if available */ out_str_nf((char_u *) (xterm_mouse_vers > 1 ? IF_EB("\033[?1002h", ESC_STR "[?1002h") : IF_EB("\033[?1000h", ESC_STR "[?1000h"))); else /* disable mouse events, could probably always send the same */ out_str_nf((char_u *) (xterm_mouse_vers > 1 ? IF_EB("\033[?1002l", ESC_STR "[?1002l") : IF_EB("\033[?1000l", ESC_STR "[?1000l"))); ison = on; } # ifdef FEAT_MOUSE_DEC else if (ttym_flags == TTYM_DEC) { if (on) /* enable mouse events */ out_str_nf((char_u *)"\033[1;2'z\033[1;3'{"); else /* disable mouse events */ out_str_nf((char_u *)"\033['z"); ison = on; } # endif # ifdef FEAT_MOUSE_GPM else { if (on) { if (gpm_open()) ison = TRUE; } else { gpm_close(); ison = FALSE; } } # endif # ifdef FEAT_SYSMOUSE else { if (on) { if (sysmouse_open() == OK) ison = TRUE; } else { sysmouse_close(); ison = FALSE; } } # endif # ifdef FEAT_MOUSE_JSB else { if (on) { /* D - Enable Mouse up/down messages * L - Enable Left Button Reporting * M - Enable Middle Button Reporting * R - Enable Right Button Reporting * K - Enable SHIFT and CTRL key Reporting * + - Enable Advanced messaging of mouse moves and up/down messages * Q - Quiet No Ack * # - Numeric value of mouse pointer required * 0 = Multiview 2000 cursor, used as standard * 1 = Windows Arrow * 2 = Windows I Beam * 3 = Windows Hour Glass * 4 = Windows Cross Hair * 5 = Windows UP Arrow */ #ifdef JSBTERM_MOUSE_NONADVANCED /* Disables full feedback of pointer movements */ out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK1Q\033\\", ESC_STR "[0~ZwLMRK1Q" ESC_STR "\\")); #else out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK+1Q\033\\", ESC_STR "[0~ZwLMRK+1Q" ESC_STR "\\")); #endif ison = TRUE; } else { out_str_nf((char_u *)IF_EB("\033[0~ZwQ\033\\", ESC_STR "[0~ZwQ" ESC_STR "\\")); ison = FALSE; } } # endif # ifdef FEAT_MOUSE_PTERM else { /* 1 = button press, 6 = release, 7 = drag, 1h...9l = right button */ if (on) out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l"); else out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h"); ison = on; } # endif } /* * Set the mouse termcode, depending on the 'term' and 'ttymouse' options. */ void check_mouse_termcode() { # ifdef FEAT_MOUSE_XTERM if (use_xterm_mouse() # ifdef FEAT_MOUSE_URXVT && use_xterm_mouse() != 3 # endif # ifdef FEAT_GUI && !gui.in_use # endif ) { set_mouse_termcode(KS_MOUSE, (char_u *)(term_is_8bit(T_NAME) ? IF_EB("\233M", CSI_STR "M") : IF_EB("\033[M", ESC_STR "[M"))); if (*p_mouse != NUL) { /* force mouse off and maybe on to send possibly new mouse * activation sequence to the xterm, with(out) drag tracing. */ mch_setmouse(FALSE); setmouse(); } } else del_mouse_termcode(KS_MOUSE); # endif # ifdef FEAT_MOUSE_GPM if (!use_xterm_mouse() # ifdef FEAT_GUI && !gui.in_use # endif ) set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MG", ESC_STR "MG")); # endif # ifdef FEAT_SYSMOUSE if (!use_xterm_mouse() # ifdef FEAT_GUI && !gui.in_use # endif ) set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MS", ESC_STR "MS")); # endif # ifdef FEAT_MOUSE_JSB /* conflicts with xterm mouse: "\033[" and "\033[M" ??? */ if (!use_xterm_mouse() # ifdef FEAT_GUI && !gui.in_use # endif ) set_mouse_termcode(KS_JSBTERM_MOUSE, (char_u *)IF_EB("\033[0~zw", ESC_STR "[0~zw")); else del_mouse_termcode(KS_JSBTERM_MOUSE); # endif # ifdef FEAT_MOUSE_NET /* There is no conflict, but one may type "ESC }" from Insert mode. Don't * define it in the GUI or when using an xterm. */ if (!use_xterm_mouse() # ifdef FEAT_GUI && !gui.in_use # endif ) set_mouse_termcode(KS_NETTERM_MOUSE, (char_u *)IF_EB("\033}", ESC_STR "}")); else del_mouse_termcode(KS_NETTERM_MOUSE); # endif # ifdef FEAT_MOUSE_DEC /* conflicts with xterm mouse: "\033[" and "\033[M" */ if (!use_xterm_mouse() # ifdef FEAT_GUI && !gui.in_use # endif ) set_mouse_termcode(KS_DEC_MOUSE, (char_u *)(term_is_8bit(T_NAME) ? IF_EB("\233", CSI_STR) : IF_EB("\033[", ESC_STR "["))); else del_mouse_termcode(KS_DEC_MOUSE); # endif # ifdef FEAT_MOUSE_PTERM /* same as the dec mouse */ if (!use_xterm_mouse() # ifdef FEAT_GUI && !gui.in_use # endif ) set_mouse_termcode(KS_PTERM_MOUSE, (char_u *) IF_EB("\033[", ESC_STR "[")); else del_mouse_termcode(KS_PTERM_MOUSE); # endif # ifdef FEAT_MOUSE_URXVT /* same as the dec mouse */ if (use_xterm_mouse() == 3 # ifdef FEAT_GUI && !gui.in_use # endif ) { set_mouse_termcode(KS_URXVT_MOUSE, (char_u *)(term_is_8bit(T_NAME) ? IF_EB("\233", CSI_STR) : IF_EB("\033[", ESC_STR "["))); if (*p_mouse != NUL) { mch_setmouse(FALSE); setmouse(); } } else del_mouse_termcode(KS_URXVT_MOUSE); # endif } #endif /* * set screen mode, always fails. */ int mch_screenmode(arg) char_u *arg UNUSED; { EMSG(_(e_screenmode)); return FAIL; } #ifndef VMS /* * Try to get the current window size: * 1. with an ioctl(), most accurate method * 2. from the environment variables LINES and COLUMNS * 3. from the termcap * 4. keep using the old values * Return OK when size could be determined, FAIL otherwise. */ int mch_get_shellsize() { long rows = 0; long columns = 0; char_u *p; /* * For OS/2 use _scrsize(). */ # ifdef __EMX__ { int s[2]; _scrsize(s); columns = s[0]; rows = s[1]; } # endif /* * 1. try using an ioctl. It is the most accurate method. * * Try using TIOCGWINSZ first, some systems that have it also define * TIOCGSIZE but don't have a struct ttysize. */ # ifdef TIOCGWINSZ { struct winsize ws; int fd = 1; /* When stdout is not a tty, use stdin for the ioctl(). */ if (!isatty(fd) && isatty(read_cmd_fd)) fd = read_cmd_fd; if (ioctl(fd, TIOCGWINSZ, &ws) == 0) { columns = ws.ws_col; rows = ws.ws_row; } } # else /* TIOCGWINSZ */ # ifdef TIOCGSIZE { struct ttysize ts; int fd = 1; /* When stdout is not a tty, use stdin for the ioctl(). */ if (!isatty(fd) && isatty(read_cmd_fd)) fd = read_cmd_fd; if (ioctl(fd, TIOCGSIZE, &ts) == 0) { columns = ts.ts_cols; rows = ts.ts_lines; } } # endif /* TIOCGSIZE */ # endif /* TIOCGWINSZ */ /* * 2. get size from environment * When being POSIX compliant ('|' flag in 'cpoptions') this overrules * the ioctl() values! */ if (columns == 0 || rows == 0 || vim_strchr(p_cpo, CPO_TSIZE) != NULL) { if ((p = (char_u *)getenv("LINES"))) rows = atoi((char *)p); if ((p = (char_u *)getenv("COLUMNS"))) columns = atoi((char *)p); } #ifdef HAVE_TGETENT /* * 3. try reading "co" and "li" entries from termcap */ if (columns == 0 || rows == 0) getlinecol(&columns, &rows); #endif /* * 4. If everything fails, use the old values */ if (columns <= 0 || rows <= 0) return FAIL; Rows = rows; Columns = columns; return OK; } /* * Try to set the window size to Rows and Columns. */ void mch_set_shellsize() { if (*T_CWS) { /* * NOTE: if you get an error here that term_set_winsize() is * undefined, check the output of configure. It could probably not * find a ncurses, termcap or termlib library. */ term_set_winsize((int)Rows, (int)Columns); out_flush(); screen_start(); /* don't know where cursor is now */ } } #endif /* VMS */ /* * Rows and/or Columns has changed. */ void mch_new_shellsize() { /* Nothing to do. */ } /* * Wait for process "child" to end. * Return "child" if it exited properly, <= 0 on error. */ static pid_t wait4pid(child, status) pid_t child; waitstatus *status; { pid_t wait_pid = 0; while (wait_pid != child) { /* When compiled with Python threads are probably used, in which case * wait() sometimes hangs for no obvious reason. Use waitpid() * instead and loop (like the GUI). Also needed for other interfaces, * they might call system(). */ # ifdef __NeXT__ wait_pid = wait4(child, status, WNOHANG, (struct rusage *)0); # else wait_pid = waitpid(child, status, WNOHANG); # endif if (wait_pid == 0) { /* Wait for 1/100 sec before trying again. */ mch_delay(10L, TRUE); continue; } if (wait_pid <= 0 # ifdef ECHILD && errno == ECHILD # endif ) break; } return wait_pid; } int mch_call_shell(cmd, options) char_u *cmd; int options; /* SHELL_*, see vim.h */ { #ifdef VMS char *ifn = NULL; char *ofn = NULL; #endif int tmode = cur_tmode; #ifdef USE_SYSTEM /* use system() to start the shell: simple but slow */ int x; # ifndef __EMX__ char_u *newcmd; /* only needed for unix */ # else /* * Set the preferred shell in the EMXSHELL environment variable (but * only if it is different from what is already in the environment). * Emx then takes care of whether to use "/c" or "-c" in an * intelligent way. Simply pass the whole thing to emx's system() call. * Emx also starts an interactive shell if system() is passed an empty * string. */ char_u *p, *old; if (((old = (char_u *)getenv("EMXSHELL")) == NULL) || STRCMP(old, p_sh)) { /* should check HAVE_SETENV, but I know we don't have it. */ p = alloc(10 + strlen(p_sh)); if (p) { sprintf((char *)p, "EMXSHELL=%s", p_sh); putenv((char *)p); /* don't free the pointer! */ } } # endif out_flush(); if (options & SHELL_COOKED) settmode(TMODE_COOK); /* set to normal mode */ # if defined(FEAT_CLIPBOARD) && defined(FEAT_X11) loose_clipboard(); # endif # ifdef __EMX__ if (cmd == NULL) x = system(""); /* this starts an interactive shell in emx */ else x = system((char *)cmd); /* system() returns -1 when error occurs in starting shell */ if (x == -1 && !emsg_silent) { MSG_PUTS(_("\nCannot execute shell ")); msg_outtrans(p_sh); msg_putchar('\n'); } # else /* not __EMX__ */ if (cmd == NULL) x = system((char *)p_sh); else { # ifdef VMS if (ofn = strchr((char *)cmd, '>')) *ofn++ = '\0'; if (ifn = strchr((char *)cmd, '<')) { char *p; *ifn++ = '\0'; p = strchr(ifn,' '); /* chop off any trailing spaces */ if (p) *p = '\0'; } if (ofn) x = vms_sys((char *)cmd, ofn, ifn); else x = system((char *)cmd); # else newcmd = lalloc(STRLEN(p_sh) + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg)) + STRLEN(p_shcf) + STRLEN(cmd) + 4, TRUE); if (newcmd == NULL) x = 0; else { sprintf((char *)newcmd, "%s %s %s %s", p_sh, extra_shell_arg == NULL ? "" : (char *)extra_shell_arg, (char *)p_shcf, (char *)cmd); x = system((char *)newcmd); vim_free(newcmd); } # endif } # ifdef VMS x = vms_sys_status(x); # endif if (emsg_silent) ; else if (x == 127) MSG_PUTS(_("\nCannot execute shell sh\n")); # endif /* __EMX__ */ else if (x && !(options & SHELL_SILENT)) { MSG_PUTS(_("\nshell returned ")); msg_outnum((long)x); msg_putchar('\n'); } if (tmode == TMODE_RAW) settmode(TMODE_RAW); /* set to raw mode */ # ifdef FEAT_TITLE resettitle(); # endif return x; #else /* USE_SYSTEM */ /* don't use system(), use fork()/exec() */ # define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use 127, some shells use that already */ char_u *newcmd = NULL; pid_t pid; pid_t wpid = 0; pid_t wait_pid = 0; # ifdef HAVE_UNION_WAIT union wait status; # else int status = -1; # endif int retval = -1; char **argv = NULL; int argc; char_u *p_shcf_copy = NULL; int i; char_u *p; int inquote; int pty_master_fd = -1; /* for pty's */ # ifdef FEAT_GUI int pty_slave_fd = -1; char *tty_name; # endif int fd_toshell[2]; /* for pipes */ int fd_fromshell[2]; int pipe_error = FALSE; # ifdef HAVE_SETENV char envbuf[50]; # else static char envbuf_Rows[20]; static char envbuf_Columns[20]; # endif int did_settmode = FALSE; /* settmode(TMODE_RAW) called */ newcmd = vim_strsave(p_sh); if (newcmd == NULL) /* out of memory */ goto error; out_flush(); if (options & SHELL_COOKED) settmode(TMODE_COOK); /* set to normal mode */ # if defined(FEAT_CLIPBOARD) && defined(FEAT_X11) loose_clipboard(); # endif /* * Do this loop twice: * 1: find number of arguments * 2: separate them and build argv[] */ for (i = 0; i < 2; ++i) { p = newcmd; inquote = FALSE; argc = 0; for (;;) { if (i == 1) argv[argc] = (char *)p; ++argc; while (*p && (inquote || (*p != ' ' && *p != TAB))) { if (*p == '"') inquote = !inquote; ++p; } if (*p == NUL) break; if (i == 1) *p++ = NUL; p = skipwhite(p); } if (argv == NULL) { /* * Account for possible multiple args in p_shcf. */ p = p_shcf; for (;;) { p = skiptowhite(p); if (*p == NUL) break; ++argc; p = skipwhite(p); } argv = (char **)alloc((unsigned)((argc + 4) * sizeof(char *))); if (argv == NULL) /* out of memory */ goto error; } } if (cmd != NULL) { char_u *s; if (extra_shell_arg != NULL) argv[argc++] = (char *)extra_shell_arg; /* Break 'shellcmdflag' into white separated parts. This doesn't * handle quoted strings, they are very unlikely to appear. */ p_shcf_copy = alloc((unsigned)STRLEN(p_shcf) + 1); if (p_shcf_copy == NULL) /* out of memory */ goto error; s = p_shcf_copy; p = p_shcf; while (*p != NUL) { argv[argc++] = (char *)s; while (*p && *p != ' ' && *p != TAB) *s++ = *p++; *s++ = NUL; p = skipwhite(p); } argv[argc++] = (char *)cmd; } argv[argc] = NULL; /* * For the GUI, when writing the output into the buffer and when reading * input from the buffer: Try using a pseudo-tty to get the stdin/stdout * of the executed command into the Vim window. Or use a pipe. */ if ((options & (SHELL_READ|SHELL_WRITE)) # ifdef FEAT_GUI || (gui.in_use && show_shell_mess) # endif ) { # ifdef FEAT_GUI /* * Try to open a master pty. * If this works, open the slave pty. * If the slave can't be opened, close the master pty. */ if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE))) { pty_master_fd = OpenPTY(&tty_name); /* open pty */ if (pty_master_fd >= 0) { /* Leaving out O_NOCTTY may lead to waitpid() always returning * 0 on Mac OS X 10.7 thereby causing freezes. Let's assume * adding O_NOCTTY always works when defined. */ #ifdef O_NOCTTY pty_slave_fd = open(tty_name, O_RDWR | O_NOCTTY | O_EXTRA, 0); #else pty_slave_fd = open(tty_name, O_RDWR | O_EXTRA, 0); #endif if (pty_slave_fd < 0) { close(pty_master_fd); pty_master_fd = -1; } } } /* * If not opening a pty or it didn't work, try using pipes. */ if (pty_master_fd < 0) # endif { pipe_error = (pipe(fd_toshell) < 0); if (!pipe_error) /* pipe create OK */ { pipe_error = (pipe(fd_fromshell) < 0); if (pipe_error) /* pipe create failed */ { close(fd_toshell[0]); close(fd_toshell[1]); } } if (pipe_error) { MSG_PUTS(_("\nCannot create pipes\n")); out_flush(); } } } if (!pipe_error) /* pty or pipe opened or not used */ { # ifdef __BEOS__ beos_cleanup_read_thread(); # endif if ((pid = fork()) == -1) /* maybe we should use vfork() */ { MSG_PUTS(_("\nCannot fork\n")); if ((options & (SHELL_READ|SHELL_WRITE)) # ifdef FEAT_GUI || (gui.in_use && show_shell_mess) # endif ) { # ifdef FEAT_GUI if (pty_master_fd >= 0) /* close the pseudo tty */ { close(pty_master_fd); close(pty_slave_fd); } else /* close the pipes */ # endif { close(fd_toshell[0]); close(fd_toshell[1]); close(fd_fromshell[0]); close(fd_fromshell[1]); } } } else if (pid == 0) /* child */ { reset_signals(); /* handle signals normally */ if (!show_shell_mess || (options & SHELL_EXPAND)) { int fd; /* * Don't want to show any message from the shell. Can't just * close stdout and stderr though, because some systems will * break if you try to write to them after that, so we must * use dup() to replace them with something else -- webb * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang, * waiting for input. */ fd = open("/dev/null", O_RDWR | O_EXTRA, 0); fclose(stdin); fclose(stdout); fclose(stderr); /* * If any of these open()'s and dup()'s fail, we just continue * anyway. It's not fatal, and on most systems it will make * no difference at all. On a few it will cause the execvp() * to exit with a non-zero status even when the completion * could be done, which is nothing too serious. If the open() * or dup() failed we'd just do the same thing ourselves * anyway -- webb */ if (fd >= 0) { ignored = dup(fd); /* To replace stdin (fd 0) */ ignored = dup(fd); /* To replace stdout (fd 1) */ ignored = dup(fd); /* To replace stderr (fd 2) */ /* Don't need this now that we've duplicated it */ close(fd); } } else if ((options & (SHELL_READ|SHELL_WRITE)) # ifdef FEAT_GUI || gui.in_use # endif ) { # ifdef HAVE_SETSID /* Create our own process group, so that the child and all its * children can be kill()ed. Don't do this when using pipes, * because stdin is not a tty, we would lose /dev/tty. */ if (p_stmp) { (void)setsid(); # if defined(SIGHUP) /* When doing "!xterm&" and 'shell' is bash: the shell * will exit and send SIGHUP to all processes in its * group, killing the just started process. Ignore SIGHUP * to avoid that. (suggested by Simon Schubert) */ signal(SIGHUP, SIG_IGN); # endif } # endif # ifdef FEAT_GUI if (pty_slave_fd >= 0) { /* push stream discipline modules */ if (options & SHELL_COOKED) SetupSlavePTY(pty_slave_fd); # ifdef TIOCSCTTY /* Try to become controlling tty (probably doesn't work, * unless run by root) */ ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL); # endif } # endif /* Simulate to have a dumb terminal (for now) */ # ifdef HAVE_SETENV setenv("TERM", "dumb", 1); sprintf((char *)envbuf, "%ld", Rows); setenv("ROWS", (char *)envbuf, 1); sprintf((char *)envbuf, "%ld", Rows); setenv("LINES", (char *)envbuf, 1); sprintf((char *)envbuf, "%ld", Columns); setenv("COLUMNS", (char *)envbuf, 1); # else /* * Putenv does not copy the string, it has to remain valid. * Use a static array to avoid losing allocated memory. */ putenv("TERM=dumb"); sprintf(envbuf_Rows, "ROWS=%ld", Rows); putenv(envbuf_Rows); sprintf(envbuf_Rows, "LINES=%ld", Rows); putenv(envbuf_Rows); sprintf(envbuf_Columns, "COLUMNS=%ld", Columns); putenv(envbuf_Columns); # endif /* * stderr is only redirected when using the GUI, so that a * program like gpg can still access the terminal to get a * passphrase using stderr. */ # ifdef FEAT_GUI if (pty_master_fd >= 0) { close(pty_master_fd); /* close master side of pty */ /* set up stdin/stdout/stderr for the child */ close(0); ignored = dup(pty_slave_fd); close(1); ignored = dup(pty_slave_fd); if (gui.in_use) { close(2); ignored = dup(pty_slave_fd); } close(pty_slave_fd); /* has been dupped, close it now */ } else # endif { /* set up stdin for the child */ close(fd_toshell[1]); close(0); ignored = dup(fd_toshell[0]); close(fd_toshell[0]); /* set up stdout for the child */ close(fd_fromshell[0]); close(1); ignored = dup(fd_fromshell[1]); close(fd_fromshell[1]); # ifdef FEAT_GUI if (gui.in_use) { /* set up stderr for the child */ close(2); ignored = dup(1); } # endif } } /* * There is no type cast for the argv, because the type may be * different on different machines. This may cause a warning * message with strict compilers, don't worry about it. * Call _exit() instead of exit() to avoid closing the connection * to the X server (esp. with GTK, which uses atexit()). */ execvp(argv[0], argv); _exit(EXEC_FAILED); /* exec failed, return failure code */ } else /* parent */ { /* * While child is running, ignore terminating signals. * Do catch CTRL-C, so that "got_int" is set. */ catch_signals(SIG_IGN, SIG_ERR); catch_int_signal(); /* * For the GUI we redirect stdin, stdout and stderr to our window. * This is also used to pipe stdin/stdout to/from the external * command. */ if ((options & (SHELL_READ|SHELL_WRITE)) # ifdef FEAT_GUI || (gui.in_use && show_shell_mess) # endif ) { # define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */ char_u buffer[BUFLEN + 1]; # ifdef FEAT_MBYTE int buffer_off = 0; /* valid bytes in buffer[] */ # endif char_u ta_buf[BUFLEN + 1]; /* TypeAHead */ int ta_len = 0; /* valid bytes in ta_buf[] */ int len; int p_more_save; int old_State; int c; int toshell_fd; int fromshell_fd; garray_T ga; int noread_cnt; # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) struct timeval start_tv; # endif # ifdef FEAT_GUI if (pty_master_fd >= 0) { fromshell_fd = pty_master_fd; toshell_fd = dup(pty_master_fd); } else # endif { close(fd_toshell[0]); close(fd_fromshell[1]); toshell_fd = fd_toshell[1]; fromshell_fd = fd_fromshell[0]; } /* * Write to the child if there are typed characters. * Read from the child if there are characters available. * Repeat the reading a few times if more characters are * available. Need to check for typed keys now and then, but * not too often (delays when no chars are available). * This loop is quit if no characters can be read from the pty * (WaitForChar detected special condition), or there are no * characters available and the child has exited. * Only check if the child has exited when there is no more * output. The child may exit before all the output has * been printed. * * Currently this busy loops! * This can probably dead-lock when the write blocks! */ p_more_save = p_more; p_more = FALSE; old_State = State; State = EXTERNCMD; /* don't redraw at window resize */ if ((options & SHELL_WRITE) && toshell_fd >= 0) { /* Fork a process that will write the lines to the * external program. */ if ((wpid = fork()) == -1) { MSG_PUTS(_("\nCannot fork\n")); } else if (wpid == 0) /* child */ { linenr_T lnum = curbuf->b_op_start.lnum; int written = 0; char_u *lp = ml_get(lnum); size_t l; close(fromshell_fd); for (;;) { l = STRLEN(lp + written); if (l == 0) len = 0; else if (lp[written] == NL) /* NL -> NUL translation */ len = write(toshell_fd, "", (size_t)1); else { char_u *s = vim_strchr(lp + written, NL); len = write(toshell_fd, (char *)lp + written, s == NULL ? l : (size_t)(s - (lp + written))); } if (len == (int)l) { /* Finished a line, add a NL, unless this line * should not have one. */ if (lnum != curbuf->b_op_end.lnum || !curbuf->b_p_bin || (lnum != curbuf->b_no_eol_lnum && (lnum != curbuf->b_ml.ml_line_count || curbuf->b_p_eol))) ignored = write(toshell_fd, "\n", (size_t)1); ++lnum; if (lnum > curbuf->b_op_end.lnum) { /* finished all the lines, close pipe */ close(toshell_fd); toshell_fd = -1; break; } lp = ml_get(lnum); written = 0; } else if (len > 0) written += len; } _exit(0); } else /* parent */ { close(toshell_fd); toshell_fd = -1; } } if (options & SHELL_READ) ga_init2(&ga, 1, BUFLEN); noread_cnt = 0; # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) gettimeofday(&start_tv, NULL); # endif for (;;) { /* * Check if keys have been typed, write them to the child * if there are any. * Don't do this if we are expanding wild cards (would eat * typeahead). * Don't do this when filtering and terminal is in cooked * mode, the shell command will handle the I/O. Avoids * that a typed password is echoed for ssh or gpg command. * Don't get characters when the child has already * finished (wait_pid == 0). * Don't read characters unless we didn't get output for a * while (noread_cnt > 4), avoids that ":r !ls" eats * typeahead. */ len = 0; if (!(options & SHELL_EXPAND) && ((options & (SHELL_READ|SHELL_WRITE|SHELL_COOKED)) != (SHELL_READ|SHELL_WRITE|SHELL_COOKED) # ifdef FEAT_GUI || gui.in_use # endif ) && wait_pid == 0 && (ta_len > 0 || noread_cnt > 4)) { if (ta_len == 0) { /* Get extra characters when we don't have any. * Reset the counter and timer. */ noread_cnt = 0; # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) gettimeofday(&start_tv, NULL); # endif len = ui_inchar(ta_buf, BUFLEN, 10L, 0); } if (ta_len > 0 || len > 0) { /* * For pipes: * Check for CTRL-C: send interrupt signal to child. * Check for CTRL-D: EOF, close pipe to child. */ if (len == 1 && (pty_master_fd < 0 || cmd != NULL)) { # ifdef SIGINT /* * Send SIGINT to the child's group or all * processes in our group. */ if (ta_buf[ta_len] == Ctrl_C || ta_buf[ta_len] == intr_char) { # ifdef HAVE_SETSID kill(-pid, SIGINT); # else kill(0, SIGINT); # endif if (wpid > 0) kill(wpid, SIGINT); } # endif if (pty_master_fd < 0 && toshell_fd >= 0 && ta_buf[ta_len] == Ctrl_D) { close(toshell_fd); toshell_fd = -1; } } /* replace K_BS by <BS> and K_DEL by <DEL> */ for (i = ta_len; i < ta_len + len; ++i) { if (ta_buf[i] == CSI && len - i > 2) { c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]); if (c == K_DEL || c == K_KDEL || c == K_BS) { mch_memmove(ta_buf + i + 1, ta_buf + i + 3, (size_t)(len - i - 2)); if (c == K_DEL || c == K_KDEL) ta_buf[i] = DEL; else ta_buf[i] = Ctrl_H; len -= 2; } } else if (ta_buf[i] == '\r') ta_buf[i] = '\n'; # ifdef FEAT_MBYTE if (has_mbyte) i += (*mb_ptr2len_len)(ta_buf + i, ta_len + len - i) - 1; # endif } /* * For pipes: echo the typed characters. * For a pty this does not seem to work. */ if (pty_master_fd < 0) { for (i = ta_len; i < ta_len + len; ++i) { if (ta_buf[i] == '\n' || ta_buf[i] == '\b') msg_putchar(ta_buf[i]); # ifdef FEAT_MBYTE else if (has_mbyte) { int l = (*mb_ptr2len)(ta_buf + i); msg_outtrans_len(ta_buf + i, l); i += l - 1; } # endif else msg_outtrans_len(ta_buf + i, 1); } windgoto(msg_row, msg_col); out_flush(); } ta_len += len; /* * Write the characters to the child, unless EOF has * been typed for pipes. Write one character at a * time, to avoid losing too much typeahead. * When writing buffer lines, drop the typed * characters (only check for CTRL-C). */ if (options & SHELL_WRITE) ta_len = 0; else if (toshell_fd >= 0) { len = write(toshell_fd, (char *)ta_buf, (size_t)1); if (len > 0) { ta_len -= len; mch_memmove(ta_buf, ta_buf + len, ta_len); } } } } if (got_int) { /* CTRL-C sends a signal to the child, we ignore it * ourselves */ # ifdef HAVE_SETSID kill(-pid, SIGINT); # else kill(0, SIGINT); # endif if (wpid > 0) kill(wpid, SIGINT); got_int = FALSE; } /* * Check if the child has any characters to be printed. * Read them and write them to our window. Repeat this as * long as there is something to do, avoid the 10ms wait * for mch_inchar(), or sending typeahead characters to * the external process. * TODO: This should handle escape sequences, compatible * to some terminal (vt52?). */ ++noread_cnt; while (RealWaitForChar(fromshell_fd, 10L, NULL)) { len = read_eintr(fromshell_fd, buffer # ifdef FEAT_MBYTE + buffer_off, (size_t)(BUFLEN - buffer_off) # else , (size_t)BUFLEN # endif ); if (len <= 0) /* end of file or error */ goto finished; noread_cnt = 0; if (options & SHELL_READ) { /* Do NUL -> NL translation, append NL separated * lines to the current buffer. */ for (i = 0; i < len; ++i) { if (buffer[i] == NL) append_ga_line(&ga); else if (buffer[i] == NUL) ga_append(&ga, NL); else ga_append(&ga, buffer[i]); } } # ifdef FEAT_MBYTE else if (has_mbyte) { int l; len += buffer_off; buffer[len] = NUL; /* Check if the last character in buffer[] is * incomplete, keep these bytes for the next * round. */ for (p = buffer; p < buffer + len; p += l) { l = mb_cptr2len(p); if (l == 0) l = 1; /* NUL byte? */ else if (MB_BYTE2LEN(*p) != l) break; } if (p == buffer) /* no complete character */ { /* avoid getting stuck at an illegal byte */ if (len >= 12) ++p; else { buffer_off = len; continue; } } c = *p; *p = NUL; msg_puts(buffer); if (p < buffer + len) { *p = c; buffer_off = (buffer + len) - p; mch_memmove(buffer, p, buffer_off); continue; } buffer_off = 0; } # endif /* FEAT_MBYTE */ else { buffer[len] = NUL; msg_puts(buffer); } windgoto(msg_row, msg_col); cursor_on(); out_flush(); if (got_int) break; # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) { struct timeval now_tv; long msec; /* Avoid that we keep looping here without * checking for a CTRL-C for a long time. Don't * break out too often to avoid losing typeahead. */ gettimeofday(&now_tv, NULL); msec = (now_tv.tv_sec - start_tv.tv_sec) * 1000L + (now_tv.tv_usec - start_tv.tv_usec) / 1000L; if (msec > 2000) { noread_cnt = 5; break; } } # endif } /* If we already detected the child has finished break the * loop now. */ if (wait_pid == pid) break; /* * Check if the child still exists, before checking for * typed characters (otherwise we would lose typeahead). */ # ifdef __NeXT__ wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0); # else wait_pid = waitpid(pid, &status, WNOHANG); # endif if ((wait_pid == (pid_t)-1 && errno == ECHILD) || (wait_pid == pid && WIFEXITED(status))) { /* Don't break the loop yet, try reading more * characters from "fromshell_fd" first. When using * pipes there might still be something to read and * then we'll break the loop at the "break" above. */ wait_pid = pid; } else wait_pid = 0; } finished: p_more = p_more_save; if (options & SHELL_READ) { if (ga.ga_len > 0) { append_ga_line(&ga); /* remember that the NL was missing */ curbuf->b_no_eol_lnum = curwin->w_cursor.lnum; } else curbuf->b_no_eol_lnum = 0; ga_clear(&ga); } /* * Give all typeahead that wasn't used back to ui_inchar(). */ if (ta_len) ui_inchar_undo(ta_buf, ta_len); State = old_State; if (toshell_fd >= 0) close(toshell_fd); close(fromshell_fd); } /* * Wait until our child has exited. * Ignore wait() returning pids of other children and returning * because of some signal like SIGWINCH. * Don't wait if wait_pid was already set above, indicating the * child already exited. */ if (wait_pid != pid) wait_pid = wait4pid(pid, &status); # ifdef FEAT_GUI /* Close slave side of pty. Only do this after the child has * exited, otherwise the child may hang when it tries to write on * the pty. */ if (pty_master_fd >= 0) close(pty_slave_fd); # endif /* Make sure the child that writes to the external program is * dead. */ if (wpid > 0) { kill(wpid, SIGKILL); wait4pid(wpid, NULL); } /* * Set to raw mode right now, otherwise a CTRL-C after * catch_signals() will kill Vim. */ if (tmode == TMODE_RAW) settmode(TMODE_RAW); did_settmode = TRUE; set_signals(); if (WIFEXITED(status)) { /* LINTED avoid "bitwise operation on signed value" */ retval = WEXITSTATUS(status); if (retval && !emsg_silent) { if (retval == EXEC_FAILED) { MSG_PUTS(_("\nCannot execute shell ")); msg_outtrans(p_sh); msg_putchar('\n'); } else if (!(options & SHELL_SILENT)) { MSG_PUTS(_("\nshell returned ")); msg_outnum((long)retval); msg_putchar('\n'); } } } else MSG_PUTS(_("\nCommand terminated\n")); } } vim_free(argv); vim_free(p_shcf_copy); error: if (!did_settmode) if (tmode == TMODE_RAW) settmode(TMODE_RAW); /* set to raw mode */ # ifdef FEAT_TITLE resettitle(); # endif vim_free(newcmd); return retval; #endif /* USE_SYSTEM */ } /* * Check for CTRL-C typed by reading all available characters. * In cooked mode we should get SIGINT, no need to check. */ void mch_breakcheck() { if (curr_tmode == TMODE_RAW && RealWaitForChar(read_cmd_fd, 0L, NULL)) fill_input_buf(FALSE); } /* * Wait "msec" msec until a character is available from the keyboard or from * inbuf[]. msec == -1 will block forever. * When a GUI is being used, this will never get called -- webb */ static int WaitForChar(msec) long msec; { #ifdef FEAT_MOUSE_GPM int gpm_process_wanted; #endif #ifdef FEAT_XCLIPBOARD int rest; #endif int avail; if (input_available()) /* something in inbuf[] */ return 1; #if defined(FEAT_MOUSE_DEC) /* May need to query the mouse position. */ if (WantQueryMouse) { WantQueryMouse = FALSE; mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5); } #endif /* * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse * events. This is a bit complicated, because they might both be defined. */ #if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD) # ifdef FEAT_XCLIPBOARD rest = 0; if (do_xterm_trace()) rest = msec; # endif do { # ifdef FEAT_XCLIPBOARD if (rest != 0) { msec = XT_TRACE_DELAY; if (rest >= 0 && rest < XT_TRACE_DELAY) msec = rest; if (rest >= 0) rest -= msec; } # endif # ifdef FEAT_MOUSE_GPM gpm_process_wanted = 0; avail = RealWaitForChar(read_cmd_fd, msec, &gpm_process_wanted); # else avail = RealWaitForChar(read_cmd_fd, msec, NULL); # endif if (!avail) { if (input_available()) return 1; # ifdef FEAT_XCLIPBOARD if (rest == 0 || !do_xterm_trace()) # endif break; } } while (FALSE # ifdef FEAT_MOUSE_GPM || (gpm_process_wanted && mch_gpm_process() == 0) # endif # ifdef FEAT_XCLIPBOARD || (!avail && rest != 0) # endif ); #else avail = RealWaitForChar(read_cmd_fd, msec, NULL); #endif return avail; } /* * Wait "msec" msec until a character is available from file descriptor "fd". * "msec" == 0 will check for characters once. * "msec" == -1 will block until a character is available. * When a GUI is being used, this will not be used for input -- webb * Returns also, when a request from Sniff is waiting -- toni. * Or when a Linux GPM mouse event is waiting. */ #if defined(__BEOS__) int #else static int #endif RealWaitForChar(fd, msec, check_for_gpm) int fd; long msec; int *check_for_gpm UNUSED; { int ret; #ifdef FEAT_NETBEANS_INTG int nb_fd = netbeans_filedesc(); #endif #if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME) static int busy = FALSE; /* May retry getting characters after an event was handled. */ # define MAY_LOOP # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) /* Remember at what time we started, so that we know how much longer we * should wait after being interrupted. */ # define USE_START_TV struct timeval start_tv; if (msec > 0 && ( # ifdef FEAT_XCLIPBOARD xterm_Shell != (Widget)0 # if defined(USE_XSMP) || defined(FEAT_MZSCHEME) || # endif # endif # ifdef USE_XSMP xsmp_icefd != -1 # ifdef FEAT_MZSCHEME || # endif # endif # ifdef FEAT_MZSCHEME (mzthreads_allowed() && p_mzq > 0) # endif )) gettimeofday(&start_tv, NULL); # endif /* Handle being called recursively. This may happen for the session * manager stuff, it may save the file, which does a breakcheck. */ if (busy) return 0; #endif #ifdef MAY_LOOP for (;;) #endif { #ifdef MAY_LOOP int finished = TRUE; /* default is to 'loop' just once */ # ifdef FEAT_MZSCHEME int mzquantum_used = FALSE; # endif #endif #ifndef HAVE_SELECT struct pollfd fds[6]; int nfd; # ifdef FEAT_XCLIPBOARD int xterm_idx = -1; # endif # ifdef FEAT_MOUSE_GPM int gpm_idx = -1; # endif # ifdef USE_XSMP int xsmp_idx = -1; # endif # ifdef FEAT_NETBEANS_INTG int nb_idx = -1; # endif int towait = (int)msec; # ifdef FEAT_MZSCHEME mzvim_check_threads(); if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq)) { towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */ mzquantum_used = TRUE; } # endif fds[0].fd = fd; fds[0].events = POLLIN; nfd = 1; # ifdef FEAT_SNIFF # define SNIFF_IDX 1 if (want_sniff_request) { fds[SNIFF_IDX].fd = fd_from_sniff; fds[SNIFF_IDX].events = POLLIN; nfd++; } # endif # ifdef FEAT_XCLIPBOARD if (xterm_Shell != (Widget)0) { xterm_idx = nfd; fds[nfd].fd = ConnectionNumber(xterm_dpy); fds[nfd].events = POLLIN; nfd++; } # endif # ifdef FEAT_MOUSE_GPM if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0) { gpm_idx = nfd; fds[nfd].fd = gpm_fd; fds[nfd].events = POLLIN; nfd++; } # endif # ifdef USE_XSMP if (xsmp_icefd != -1) { xsmp_idx = nfd; fds[nfd].fd = xsmp_icefd; fds[nfd].events = POLLIN; nfd++; } # endif #ifdef FEAT_NETBEANS_INTG if (nb_fd != -1) { nb_idx = nfd; fds[nfd].fd = nb_fd; fds[nfd].events = POLLIN; nfd++; } #endif ret = poll(fds, nfd, towait); # ifdef FEAT_MZSCHEME if (ret == 0 && mzquantum_used) /* MzThreads scheduling is required and timeout occurred */ finished = FALSE; # endif # ifdef FEAT_SNIFF if (ret < 0) sniff_disconnect(1); else if (want_sniff_request) { if (fds[SNIFF_IDX].revents & POLLHUP) sniff_disconnect(1); if (fds[SNIFF_IDX].revents & POLLIN) sniff_request_waiting = 1; } # endif # ifdef FEAT_XCLIPBOARD if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN)) { xterm_update(); /* Maybe we should hand out clipboard */ if (--ret == 0 && !input_available()) /* Try again */ finished = FALSE; } # endif # ifdef FEAT_MOUSE_GPM if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN)) { *check_for_gpm = 1; } # endif # ifdef USE_XSMP if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP))) { if (fds[xsmp_idx].revents & POLLIN) { busy = TRUE; xsmp_handle_requests(); busy = FALSE; } else if (fds[xsmp_idx].revents & POLLHUP) { if (p_verbose > 0) verb_msg((char_u *)_("XSMP lost ICE connection")); xsmp_close(); } if (--ret == 0) finished = FALSE; /* Try again */ } # endif #ifdef FEAT_NETBEANS_INTG if (ret > 0 && nb_idx != -1 && fds[nb_idx].revents & POLLIN) { netbeans_read(); --ret; } #endif #else /* HAVE_SELECT */ struct timeval tv; struct timeval *tvp; fd_set rfds, efds; int maxfd; long towait = msec; # ifdef FEAT_MZSCHEME mzvim_check_threads(); if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq)) { towait = p_mzq; /* don't wait longer than 'mzquantum' */ mzquantum_used = TRUE; } # endif # ifdef __EMX__ /* don't check for incoming chars if not in raw mode, because select() * always returns TRUE then (in some version of emx.dll) */ if (curr_tmode != TMODE_RAW) return 0; # endif if (towait >= 0) { tv.tv_sec = towait / 1000; tv.tv_usec = (towait % 1000) * (1000000/1000); tvp = &tv; } else tvp = NULL; /* * Select on ready for reading and exceptional condition (end of file). */ select_eintr: FD_ZERO(&rfds); FD_ZERO(&efds); FD_SET(fd, &rfds); # if !defined(__QNX__) && !defined(__CYGWIN32__) /* For QNX select() always returns 1 if this is set. Why? */ FD_SET(fd, &efds); # endif maxfd = fd; # ifdef FEAT_SNIFF if (want_sniff_request) { FD_SET(fd_from_sniff, &rfds); FD_SET(fd_from_sniff, &efds); if (maxfd < fd_from_sniff) maxfd = fd_from_sniff; } # endif # ifdef FEAT_XCLIPBOARD if (xterm_Shell != (Widget)0) { FD_SET(ConnectionNumber(xterm_dpy), &rfds); if (maxfd < ConnectionNumber(xterm_dpy)) maxfd = ConnectionNumber(xterm_dpy); } # endif # ifdef FEAT_MOUSE_GPM if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0) { FD_SET(gpm_fd, &rfds); FD_SET(gpm_fd, &efds); if (maxfd < gpm_fd) maxfd = gpm_fd; } # endif # ifdef USE_XSMP if (xsmp_icefd != -1) { FD_SET(xsmp_icefd, &rfds); FD_SET(xsmp_icefd, &efds); if (maxfd < xsmp_icefd) maxfd = xsmp_icefd; } # endif #ifdef FEAT_NETBEANS_INTG if (nb_fd != -1) { FD_SET(nb_fd, &rfds); if (maxfd < nb_fd) maxfd = nb_fd; } #endif # ifdef OLD_VMS /* Old VMS as v6.2 and older have broken select(). It waits more than * required. Should not be used */ ret = 0; # else ret = select(maxfd + 1, &rfds, NULL, &efds, tvp); # endif # ifdef EINTR if (ret == -1 && errno == EINTR) { /* Check whether window has been resized, EINTR may be caused by * SIGWINCH. */ if (do_resize) handle_resize(); /* Interrupted by a signal, need to try again. We ignore msec * here, because we do want to check even after a timeout if * characters are available. Needed for reading output of an * external command after the process has finished. */ goto select_eintr; } # endif # ifdef __TANDEM if (ret == -1 && errno == ENOTSUP) { FD_ZERO(&rfds); FD_ZERO(&efds); ret = 0; } # endif # ifdef FEAT_MZSCHEME if (ret == 0 && mzquantum_used) /* loop if MzThreads must be scheduled and timeout occurred */ finished = FALSE; # endif # ifdef FEAT_SNIFF if (ret < 0 ) sniff_disconnect(1); else if (ret > 0 && want_sniff_request) { if (FD_ISSET(fd_from_sniff, &efds)) sniff_disconnect(1); if (FD_ISSET(fd_from_sniff, &rfds)) sniff_request_waiting = 1; } # endif # ifdef FEAT_XCLIPBOARD if (ret > 0 && xterm_Shell != (Widget)0 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds)) { xterm_update(); /* Maybe we should hand out clipboard */ /* continue looping when we only got the X event and the input * buffer is empty */ if (--ret == 0 && !input_available()) { /* Try again */ finished = FALSE; } } # endif # ifdef FEAT_MOUSE_GPM if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0) { if (FD_ISSET(gpm_fd, &efds)) gpm_close(); else if (FD_ISSET(gpm_fd, &rfds)) *check_for_gpm = 1; } # endif # ifdef USE_XSMP if (ret > 0 && xsmp_icefd != -1) { if (FD_ISSET(xsmp_icefd, &efds)) { if (p_verbose > 0) verb_msg((char_u *)_("XSMP lost ICE connection")); xsmp_close(); if (--ret == 0) finished = FALSE; /* keep going if event was only one */ } else if (FD_ISSET(xsmp_icefd, &rfds)) { busy = TRUE; xsmp_handle_requests(); busy = FALSE; if (--ret == 0) finished = FALSE; /* keep going if event was only one */ } } # endif #ifdef FEAT_NETBEANS_INTG if (ret > 0 && nb_fd != -1 && FD_ISSET(nb_fd, &rfds)) { netbeans_read(); --ret; } #endif #endif /* HAVE_SELECT */ #ifdef MAY_LOOP if (finished || msec == 0) break; /* We're going to loop around again, find out for how long */ if (msec > 0) { # ifdef USE_START_TV struct timeval mtv; /* Compute remaining wait time. */ gettimeofday(&mtv, NULL); msec -= (mtv.tv_sec - start_tv.tv_sec) * 1000L + (mtv.tv_usec - start_tv.tv_usec) / 1000L; # else /* Guess we got interrupted halfway. */ msec = msec / 2; # endif if (msec <= 0) break; /* waited long enough */ } #endif } return (ret > 0); } #ifndef VMS #ifndef NO_EXPANDPATH /* * Expand a path into all matching files and/or directories. Handles "*", * "?", "[a-z]", "**", etc. * "path" has backslashes before chars that are not to be expanded. * Returns the number of matches found. */ int mch_expandpath(gap, path, flags) garray_T *gap; char_u *path; int flags; /* EW_* flags */ { return unix_expandpath(gap, path, 0, flags, FALSE); } #endif /* * mch_expand_wildcards() - this code does wild-card pattern matching using * the shell * * return OK for success, FAIL for error (you may lose some memory) and put * an error message in *file. * * num_pat is number of input patterns * pat is array of pointers to input patterns * num_file is pointer to number of matched file names * file is pointer to array of pointers to matched file names */ #ifndef SEEK_SET # define SEEK_SET 0 #endif #ifndef SEEK_END # define SEEK_END 2 #endif #define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|" int mch_expand_wildcards(num_pat, pat, num_file, file, flags) int num_pat; char_u **pat; int *num_file; char_u ***file; int flags; /* EW_* flags */ { int i; size_t len; char_u *p; int dir; #ifdef __EMX__ /* * This is the OS/2 implementation. */ # define EXPL_ALLOC_INC 16 char_u **expl_files; size_t files_alloced, files_free; char_u *buf; int has_wildcard; *num_file = 0; /* default: no files found */ files_alloced = EXPL_ALLOC_INC; /* how much space is allocated */ files_free = EXPL_ALLOC_INC; /* how much space is not used */ *file = (char_u **)alloc(sizeof(char_u **) * files_alloced); if (*file == NULL) return FAIL; for (; num_pat > 0; num_pat--, pat++) { expl_files = NULL; if (vim_strchr(*pat, '$') || vim_strchr(*pat, '~')) /* expand environment var or home dir */ buf = expand_env_save(*pat); else buf = vim_strsave(*pat); expl_files = NULL; has_wildcard = mch_has_exp_wildcard(buf); /* (still) wildcards? */ if (has_wildcard) /* yes, so expand them */ expl_files = (char_u **)_fnexplode(buf); /* * return value of buf if no wildcards left, * OR if no match AND EW_NOTFOUND is set. */ if ((!has_wildcard && ((flags & EW_NOTFOUND) || mch_getperm(buf) >= 0)) || (expl_files == NULL && (flags & EW_NOTFOUND))) { /* simply save the current contents of *buf */ expl_files = (char_u **)alloc(sizeof(char_u **) * 2); if (expl_files != NULL) { expl_files[0] = vim_strsave(buf); expl_files[1] = NULL; } } vim_free(buf); /* * Count number of names resulting from expansion, * At the same time add a backslash to the end of names that happen to * be directories, and replace slashes with backslashes. */ if (expl_files) { for (i = 0; (p = expl_files[i]) != NULL; i++) { dir = mch_isdir(p); /* If we don't want dirs and this is one, skip it */ if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE))) continue; /* Skip files that are not executable if we check for that. */ if (!dir && (flags & EW_EXEC) && !mch_can_exe(p)) continue; if (--files_free == 0) { /* need more room in table of pointers */ files_alloced += EXPL_ALLOC_INC; *file = (char_u **)vim_realloc(*file, sizeof(char_u **) * files_alloced); if (*file == NULL) { EMSG(_(e_outofmem)); *num_file = 0; return FAIL; } files_free = EXPL_ALLOC_INC; } slash_adjust(p); if (dir) { /* For a directory we add a '/', unless it's already * there. */ len = STRLEN(p); if (((*file)[*num_file] = alloc(len + 2)) != NULL) { STRCPY((*file)[*num_file], p); if (!after_pathsep((*file)[*num_file], (*file)[*num_file] + len)) { (*file)[*num_file][len] = psepc; (*file)[*num_file][len + 1] = NUL; } } } else { (*file)[*num_file] = vim_strsave(p); } /* * Error message already given by either alloc or vim_strsave. * Should return FAIL, but returning OK works also. */ if ((*file)[*num_file] == NULL) break; (*num_file)++; } _fnexplodefree((char **)expl_files); } } return OK; #else /* __EMX__ */ /* * This is the non-OS/2 implementation (really Unix). */ int j; char_u *tempname; char_u *command; FILE *fd; char_u *buffer; #define STYLE_ECHO 0 /* use "echo", the default */ #define STYLE_GLOB 1 /* use "glob", for csh */ #define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */ #define STYLE_PRINT 3 /* use "print -N", for zsh */ #define STYLE_BT 4 /* `cmd` expansion, execute the pattern * directly */ int shell_style = STYLE_ECHO; int check_spaces; static int did_find_nul = FALSE; int ampersent = FALSE; /* vimglob() function to define for Posix shell */ static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >"; *num_file = 0; /* default: no files found */ *file = NULL; /* * If there are no wildcards, just copy the names to allocated memory. * Saves a lot of time, because we don't have to start a new shell. */ if (!have_wildcard(num_pat, pat)) return save_patterns(num_pat, pat, num_file, file); # ifdef HAVE_SANDBOX /* Don't allow any shell command in the sandbox. */ if (sandbox != 0 && check_secure()) return FAIL; # endif /* * Don't allow the use of backticks in secure and restricted mode. */ if (secure || restricted) for (i = 0; i < num_pat; ++i) if (vim_strchr(pat[i], '`') != NULL && (check_restricted() || check_secure())) return FAIL; /* * get a name for the temp file */ if ((tempname = vim_tempname('o')) == NULL) { EMSG(_(e_notmp)); return FAIL; } /* * Let the shell expand the patterns and write the result into the temp * file. * STYLE_BT: NL separated * If expanding `cmd` execute it directly. * STYLE_GLOB: NUL separated * If we use *csh, "glob" will work better than "echo". * STYLE_PRINT: NL or NUL separated * If we use *zsh, "print -N" will work better than "glob". * STYLE_VIMGLOB: NL separated * If we use *sh*, we define "vimglob()". * STYLE_ECHO: space separated. * A shell we don't know, stay safe and use "echo". */ if (num_pat == 1 && *pat[0] == '`' && (len = STRLEN(pat[0])) > 2 && *(pat[0] + len - 1) == '`') shell_style = STYLE_BT; else if ((len = STRLEN(p_sh)) >= 3) { if (STRCMP(p_sh + len - 3, "csh") == 0) shell_style = STYLE_GLOB; else if (STRCMP(p_sh + len - 3, "zsh") == 0) shell_style = STYLE_PRINT; } if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh), "sh") != NULL) shell_style = STYLE_VIMGLOB; /* Compute the length of the command. We need 2 extra bytes: for the * optional '&' and for the NUL. * Worst case: "unset nonomatch; print -N >" plus two is 29 */ len = STRLEN(tempname) + 29; if (shell_style == STYLE_VIMGLOB) len += STRLEN(sh_vimglob_func); for (i = 0; i < num_pat; ++i) { /* Count the length of the patterns in the same way as they are put in * "command" below. */ #ifdef USE_SYSTEM len += STRLEN(pat[i]) + 3; /* add space and two quotes */ #else ++len; /* add space */ for (j = 0; pat[i][j] != NUL; ++j) { if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL) ++len; /* may add a backslash */ ++len; } #endif } command = alloc(len); if (command == NULL) { /* out of memory */ vim_free(tempname); return FAIL; } /* * Build the shell command: * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell * recognizes this). * - Add the shell command to print the expanded names. * - Add the temp file name. * - Add the file name patterns. */ if (shell_style == STYLE_BT) { /* change `command; command& ` to (command; command ) */ STRCPY(command, "("); STRCAT(command, pat[0] + 1); /* exclude first backtick */ p = command + STRLEN(command) - 1; *p-- = ')'; /* remove last backtick */ while (p > command && vim_iswhite(*p)) --p; if (*p == '&') /* remove trailing '&' */ { ampersent = TRUE; *p = ' '; } STRCAT(command, ">"); } else { if (flags & EW_NOTFOUND) STRCPY(command, "set nonomatch; "); else STRCPY(command, "unset nonomatch; "); if (shell_style == STYLE_GLOB) STRCAT(command, "glob >"); else if (shell_style == STYLE_PRINT) STRCAT(command, "print -N >"); else if (shell_style == STYLE_VIMGLOB) STRCAT(command, sh_vimglob_func); else STRCAT(command, "echo >"); } STRCAT(command, tempname); if (shell_style != STYLE_BT) for (i = 0; i < num_pat; ++i) { /* When using system() always add extra quotes, because the shell * is started twice. Otherwise put a backslash before special * characters, except inside ``. */ #ifdef USE_SYSTEM STRCAT(command, " \""); STRCAT(command, pat[i]); STRCAT(command, "\""); #else int intick = FALSE; p = command + STRLEN(command); *p++ = ' '; for (j = 0; pat[i][j] != NUL; ++j) { if (pat[i][j] == '`') intick = !intick; else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL) { /* Remove a backslash, take char literally. But keep * backslash inside backticks, before a special character * and before a backtick. */ if (intick || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL || pat[i][j + 1] == '`') *p++ = '\\'; ++j; } else if (!intick && vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL) /* Put a backslash before a special character, but not * when inside ``. */ *p++ = '\\'; /* Copy one character. */ *p++ = pat[i][j]; } *p = NUL; #endif } if (flags & EW_SILENT) show_shell_mess = FALSE; if (ampersent) STRCAT(command, "&"); /* put the '&' after the redirection */ /* * Using zsh -G: If a pattern has no matches, it is just deleted from * the argument list, otherwise zsh gives an error message and doesn't * expand any other pattern. */ if (shell_style == STYLE_PRINT) extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */ /* * If we use -f then shell variables set in .cshrc won't get expanded. * vi can do it, so we will too, but it is only necessary if there is a "$" * in one of the patterns, otherwise we can still use the fast option. */ else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat)) extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */ /* * execute the shell command */ i = call_shell(command, SHELL_EXPAND | SHELL_SILENT); /* When running in the background, give it some time to create the temp * file, but don't wait for it to finish. */ if (ampersent) mch_delay(10L, TRUE); extra_shell_arg = NULL; /* cleanup */ show_shell_mess = TRUE; vim_free(command); if (i != 0) /* mch_call_shell() failed */ { mch_remove(tempname); vim_free(tempname); /* * With interactive completion, the error message is not printed. * However with USE_SYSTEM, I don't know how to turn off error messages * from the shell, so screen may still get messed up -- webb. */ #ifndef USE_SYSTEM if (!(flags & EW_SILENT)) #endif { redraw_later_clear(); /* probably messed up screen */ msg_putchar('\n'); /* clear bottom line quickly */ cmdline_row = Rows - 1; /* continue on last line */ #ifdef USE_SYSTEM if (!(flags & EW_SILENT)) #endif { MSG(_(e_wildexpand)); msg_start(); /* don't overwrite this message */ } } /* If a `cmd` expansion failed, don't list `cmd` as a match, even when * EW_NOTFOUND is given */ if (shell_style == STYLE_BT) return FAIL; goto notfound; } /* * read the names from the file into memory */ fd = fopen((char *)tempname, READBIN); if (fd == NULL) { /* Something went wrong, perhaps a file name with a special char. */ if (!(flags & EW_SILENT)) { MSG(_(e_wildexpand)); msg_start(); /* don't overwrite this message */ } vim_free(tempname); goto notfound; } fseek(fd, 0L, SEEK_END); len = ftell(fd); /* get size of temp file */ fseek(fd, 0L, SEEK_SET); buffer = alloc(len + 1); if (buffer == NULL) { /* out of memory */ mch_remove(tempname); vim_free(tempname); fclose(fd); return FAIL; } i = fread((char *)buffer, 1, len, fd); fclose(fd); mch_remove(tempname); if (i != (int)len) { /* unexpected read error */ EMSG2(_(e_notread), tempname); vim_free(tempname); vim_free(buffer); return FAIL; } vim_free(tempname); # if defined(__CYGWIN__) || defined(__CYGWIN32__) /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */ p = buffer; for (i = 0; i < len; ++i) if (!(buffer[i] == CAR && buffer[i + 1] == NL)) *p++ = buffer[i]; len = p - buffer; # endif /* file names are separated with Space */ if (shell_style == STYLE_ECHO) { buffer[len] = '\n'; /* make sure the buffer ends in NL */ p = buffer; for (i = 0; *p != '\n'; ++i) /* count number of entries */ { while (*p != ' ' && *p != '\n') ++p; p = skipwhite(p); /* skip to next entry */ } } /* file names are separated with NL */ else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB) { buffer[len] = NUL; /* make sure the buffer ends in NUL */ p = buffer; for (i = 0; *p != NUL; ++i) /* count number of entries */ { while (*p != '\n' && *p != NUL) ++p; if (*p != NUL) ++p; p = skipwhite(p); /* skip leading white space */ } } /* file names are separated with NUL */ else { /* * Some versions of zsh use spaces instead of NULs to separate * results. Only do this when there is no NUL before the end of the * buffer, otherwise we would never be able to use file names with * embedded spaces when zsh does use NULs. * When we found a NUL once, we know zsh is OK, set did_find_nul and * don't check for spaces again. */ check_spaces = FALSE; if (shell_style == STYLE_PRINT && !did_find_nul) { /* If there is a NUL, set did_find_nul, else set check_spaces */ buffer[len] = NUL; if (len && (int)STRLEN(buffer) < (int)len - 1) did_find_nul = TRUE; else check_spaces = TRUE; } /* * Make sure the buffer ends with a NUL. For STYLE_PRINT there * already is one, for STYLE_GLOB it needs to be added. */ if (len && buffer[len - 1] == NUL) --len; else buffer[len] = NUL; i = 0; for (p = buffer; p < buffer + len; ++p) if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */ { ++i; *p = NUL; } if (len) ++i; /* count last entry */ } if (i == 0) { /* * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I". * /bin/sh will happily expand it to nothing rather than returning an * error; and hey, it's good to check anyway -- webb. */ vim_free(buffer); goto notfound; } *num_file = i; *file = (char_u **)alloc(sizeof(char_u *) * i); if (*file == NULL) { /* out of memory */ vim_free(buffer); return FAIL; } /* * Isolate the individual file names. */ p = buffer; for (i = 0; i < *num_file; ++i) { (*file)[i] = p; /* Space or NL separates */ if (shell_style == STYLE_ECHO || shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB) { while (!(shell_style == STYLE_ECHO && *p == ' ') && *p != '\n' && *p != NUL) ++p; if (p == buffer + len) /* last entry */ *p = NUL; else { *p++ = NUL; p = skipwhite(p); /* skip to next entry */ } } else /* NUL separates */ { while (*p && p < buffer + len) /* skip entry */ ++p; ++p; /* skip NUL */ } } /* * Move the file names to allocated memory. */ for (j = 0, i = 0; i < *num_file; ++i) { /* Require the files to exist. Helps when using /bin/sh */ if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0) continue; /* check if this entry should be included */ dir = (mch_isdir((*file)[i])); if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE))) continue; /* Skip files that are not executable if we check for that. */ if (!dir && (flags & EW_EXEC) && !mch_can_exe((*file)[i])) continue; p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir)); if (p) { STRCPY(p, (*file)[i]); if (dir) add_pathsep(p); /* add '/' to a directory name */ (*file)[j++] = p; } } vim_free(buffer); *num_file = j; if (*num_file == 0) /* rejected all entries */ { vim_free(*file); *file = NULL; goto notfound; } return OK; notfound: if (flags & EW_NOTFOUND) return save_patterns(num_pat, pat, num_file, file); return FAIL; #endif /* __EMX__ */ } #endif /* VMS */ #ifndef __EMX__ static int save_patterns(num_pat, pat, num_file, file) int num_pat; char_u **pat; int *num_file; char_u ***file; { int i; char_u *s; *file = (char_u **)alloc(num_pat * sizeof(char_u *)); if (*file == NULL) return FAIL; for (i = 0; i < num_pat; i++) { s = vim_strsave(pat[i]); if (s != NULL) /* Be compatible with expand_filename(): halve the number of * backslashes. */ backslash_halve(s); (*file)[i] = s; } *num_file = num_pat; return OK; } #endif /* * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can * expand. */ int mch_has_exp_wildcard(p) char_u *p; { for ( ; *p; mb_ptr_adv(p)) { #ifndef OS2 if (*p == '\\' && p[1] != NUL) ++p; else #endif if (vim_strchr((char_u *) #ifdef VMS "*?%" #else # ifdef OS2 "*?" # else "*?[{'" # endif #endif , *p) != NULL) return TRUE; } return FALSE; } /* * Return TRUE if the string "p" contains a wildcard. * Don't recognize '~' at the end as a wildcard. */ int mch_has_wildcard(p) char_u *p; { for ( ; *p; mb_ptr_adv(p)) { #ifndef OS2 if (*p == '\\' && p[1] != NUL) ++p; else #endif if (vim_strchr((char_u *) #ifdef VMS "*?%$" #else # ifdef OS2 # ifdef VIM_BACKTICK "*?$`" # else "*?$" # endif # else "*?[{`'$" # endif #endif , *p) != NULL || (*p == '~' && p[1] != NUL)) return TRUE; } return FALSE; } #ifndef __EMX__ static int have_wildcard(num, file) int num; char_u **file; { int i; for (i = 0; i < num; i++) if (mch_has_wildcard(file[i])) return 1; return 0; } static int have_dollars(num, file) int num; char_u **file; { int i; for (i = 0; i < num; i++) if (vim_strchr(file[i], '$') != NULL) return TRUE; return FALSE; } #endif /* ifndef __EMX__ */ #ifndef HAVE_RENAME /* * Scaled-down version of rename(), which is missing in Xenix. * This version can only move regular files and will fail if the * destination exists. */ int mch_rename(src, dest) const char *src, *dest; { struct stat st; if (stat(dest, &st) >= 0) /* fail if destination exists */ return -1; if (link(src, dest) != 0) /* link file to new name */ return -1; if (mch_remove(src) == 0) /* delete link to old name */ return 0; return -1; } #endif /* !HAVE_RENAME */ #ifdef FEAT_MOUSE_GPM /* * Initializes connection with gpm (if it isn't already opened) * Return 1 if succeeded (or connection already opened), 0 if failed */ static int gpm_open() { static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */ if (!gpm_flag) { gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN); gpm_connect.defaultMask = ~GPM_HARD; /* Default handling for mouse move*/ gpm_connect.minMod = 0; /* Handle any modifier keys */ gpm_connect.maxMod = 0xffff; if (Gpm_Open(&gpm_connect, 0) > 0) { /* gpm library tries to handling TSTP causes * problems. Anyways, we close connection to Gpm whenever * we are going to suspend or starting an external process * so we shouldn't have problem with this */ # ifdef SIGTSTP signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL); # endif return 1; /* succeed */ } if (gpm_fd == -2) Gpm_Close(); /* We don't want to talk to xterm via gpm */ return 0; } return 1; /* already open */ } /* * Closes connection to gpm */ static void gpm_close() { if (gpm_flag && gpm_fd >= 0) /* if Open */ Gpm_Close(); } /* Reads gpm event and adds special keys to input buf. Returns length of * generated key sequence. * This function is made after gui_send_mouse_event */ static int mch_gpm_process() { int button; static Gpm_Event gpm_event; char_u string[6]; int_u vim_modifiers; int row,col; unsigned char buttons_mask; unsigned char gpm_modifiers; static unsigned char old_buttons = 0; Gpm_GetEvent(&gpm_event); #ifdef FEAT_GUI /* Don't put events in the input queue now. */ if (hold_gui_events) return 0; #endif row = gpm_event.y - 1; col = gpm_event.x - 1; string[0] = ESC; /* Our termcode */ string[1] = 'M'; string[2] = 'G'; switch (GPM_BARE_EVENTS(gpm_event.type)) { case GPM_DRAG: string[3] = MOUSE_DRAG; break; case GPM_DOWN: buttons_mask = gpm_event.buttons & ~old_buttons; old_buttons = gpm_event.buttons; switch (buttons_mask) { case GPM_B_LEFT: button = MOUSE_LEFT; break; case GPM_B_MIDDLE: button = MOUSE_MIDDLE; break; case GPM_B_RIGHT: button = MOUSE_RIGHT; break; default: return 0; /*Don't know what to do. Can more than one button be * reported in one event? */ } string[3] = (char_u)(button | 0x20); SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1); break; case GPM_UP: string[3] = MOUSE_RELEASE; old_buttons &= ~gpm_event.buttons; break; default: return 0; } /*This code is based on gui_x11_mouse_cb in gui_x11.c */ gpm_modifiers = gpm_event.modifiers; vim_modifiers = 0x0; /* I ignore capslock stats. Aren't we all just hate capslock mixing with * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and * K_CAPSSHIFT is defined 8, so it probably isn't even reported */ if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL))) vim_modifiers |= MOUSE_SHIFT; if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL))) vim_modifiers |= MOUSE_CTRL; if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR))) vim_modifiers |= MOUSE_ALT; string[3] |= vim_modifiers; string[4] = (char_u)(col + ' ' + 1); string[5] = (char_u)(row + ' ' + 1); add_to_input_buf(string, 6); return 6; } #endif /* FEAT_MOUSE_GPM */ #ifdef FEAT_SYSMOUSE /* * Initialize connection with sysmouse. * Let virtual console inform us with SIGUSR2 for pending sysmouse * output, any sysmouse output than will be processed via sig_sysmouse(). * Return OK if succeeded, FAIL if failed. */ static int sysmouse_open() { struct mouse_info mouse; mouse.operation = MOUSE_MODE; mouse.u.mode.mode = 0; mouse.u.mode.signal = SIGUSR2; if (ioctl(1, CONS_MOUSECTL, &mouse) != -1) { signal(SIGUSR2, (RETSIGTYPE (*)())sig_sysmouse); mouse.operation = MOUSE_SHOW; ioctl(1, CONS_MOUSECTL, &mouse); return OK; } return FAIL; } /* * Stop processing SIGUSR2 signals, and also make sure that * virtual console do not send us any sysmouse related signal. */ static void sysmouse_close() { struct mouse_info mouse; signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL); mouse.operation = MOUSE_MODE; mouse.u.mode.mode = 0; mouse.u.mode.signal = 0; ioctl(1, CONS_MOUSECTL, &mouse); } /* * Gets info from sysmouse and adds special keys to input buf. */ static RETSIGTYPE sig_sysmouse SIGDEFARG(sigarg) { struct mouse_info mouse; struct video_info video; char_u string[6]; int row, col; int button; int buttons; static int oldbuttons = 0; #ifdef FEAT_GUI /* Don't put events in the input queue now. */ if (hold_gui_events) return; #endif mouse.operation = MOUSE_GETINFO; if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1 && ioctl(1, FBIO_MODEINFO, &video) != -1 && ioctl(1, CONS_MOUSECTL, &mouse) != -1 && video.vi_cheight > 0 && video.vi_cwidth > 0) { row = mouse.u.data.y / video.vi_cheight; col = mouse.u.data.x / video.vi_cwidth; buttons = mouse.u.data.buttons; string[0] = ESC; /* Our termcode */ string[1] = 'M'; string[2] = 'S'; if (oldbuttons == buttons && buttons != 0) { button = MOUSE_DRAG; } else { switch (buttons) { case 0: button = MOUSE_RELEASE; break; case 1: button = MOUSE_LEFT; break; case 2: button = MOUSE_MIDDLE; break; case 4: button = MOUSE_RIGHT; break; default: return; } oldbuttons = buttons; } string[3] = (char_u)(button); string[4] = (char_u)(col + ' ' + 1); string[5] = (char_u)(row + ' ' + 1); add_to_input_buf(string, 6); } return; } #endif /* FEAT_SYSMOUSE */ #if defined(FEAT_LIBCALL) || defined(PROTO) typedef char_u * (*STRPROCSTR)__ARGS((char_u *)); typedef char_u * (*INTPROCSTR)__ARGS((int)); typedef int (*STRPROCINT)__ARGS((char_u *)); typedef int (*INTPROCINT)__ARGS((int)); /* * Call a DLL routine which takes either a string or int param * and returns an allocated string. */ int mch_libcall(libname, funcname, argstring, argint, string_result, number_result) char_u *libname; char_u *funcname; char_u *argstring; /* NULL when using a argint */ int argint; char_u **string_result;/* NULL when using number_result */ int *number_result; { # if defined(USE_DLOPEN) void *hinstLib; char *dlerr = NULL; # else shl_t hinstLib; # endif STRPROCSTR ProcAdd; INTPROCSTR ProcAddI; char_u *retval_str = NULL; int retval_int = 0; int success = FALSE; /* * Get a handle to the DLL module. */ # if defined(USE_DLOPEN) /* First clear any error, it's not cleared by the dlopen() call. */ (void)dlerror(); hinstLib = dlopen((char *)libname, RTLD_LAZY # ifdef RTLD_LOCAL | RTLD_LOCAL # endif ); if (hinstLib == NULL) { /* "dlerr" must be used before dlclose() */ dlerr = (char *)dlerror(); if (dlerr != NULL) EMSG2(_("dlerror = \"%s\""), dlerr); } # else hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L); # endif /* If the handle is valid, try to get the function address. */ if (hinstLib != NULL) { # ifdef HAVE_SETJMP_H /* * Catch a crash when calling the library function. For example when * using a number where a string pointer is expected. */ mch_startjmp(); if (SETJMP(lc_jump_env) != 0) { success = FALSE; # if defined(USE_DLOPEN) dlerr = NULL; # endif mch_didjmp(); } else # endif { retval_str = NULL; retval_int = 0; if (argstring != NULL) { # if defined(USE_DLOPEN) ProcAdd = (STRPROCSTR)dlsym(hinstLib, (const char *)funcname); dlerr = (char *)dlerror(); # else if (shl_findsym(&hinstLib, (const char *)funcname, TYPE_PROCEDURE, (void *)&ProcAdd) < 0) ProcAdd = NULL; # endif if ((success = (ProcAdd != NULL # if defined(USE_DLOPEN) && dlerr == NULL # endif ))) { if (string_result == NULL) retval_int = ((STRPROCINT)ProcAdd)(argstring); else retval_str = (ProcAdd)(argstring); } } else { # if defined(USE_DLOPEN) ProcAddI = (INTPROCSTR)dlsym(hinstLib, (const char *)funcname); dlerr = (char *)dlerror(); # else if (shl_findsym(&hinstLib, (const char *)funcname, TYPE_PROCEDURE, (void *)&ProcAddI) < 0) ProcAddI = NULL; # endif if ((success = (ProcAddI != NULL # if defined(USE_DLOPEN) && dlerr == NULL # endif ))) { if (string_result == NULL) retval_int = ((INTPROCINT)ProcAddI)(argint); else retval_str = (ProcAddI)(argint); } } /* Save the string before we free the library. */ /* Assume that a "1" or "-1" result is an illegal pointer. */ if (string_result == NULL) *number_result = retval_int; else if (retval_str != NULL && retval_str != (char_u *)1 && retval_str != (char_u *)-1) *string_result = vim_strsave(retval_str); } # ifdef HAVE_SETJMP_H mch_endjmp(); # ifdef SIGHASARG if (lc_signal != 0) { int i; /* try to find the name of this signal */ for (i = 0; signal_info[i].sig != -1; i++) if (lc_signal == signal_info[i].sig) break; EMSG2("E368: got SIG%s in libcall()", signal_info[i].name); } # endif # endif # if defined(USE_DLOPEN) /* "dlerr" must be used before dlclose() */ if (dlerr != NULL) EMSG2(_("dlerror = \"%s\""), dlerr); /* Free the DLL module. */ (void)dlclose(hinstLib); # else (void)shl_unload(hinstLib); # endif } if (!success) { EMSG2(_(e_libcall), funcname); return FAIL; } return OK; } #endif #if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO) static int xterm_trace = -1; /* default: disabled */ static int xterm_button; /* * Setup a dummy window for X selections in a terminal. */ void setup_term_clip() { int z = 0; char *strp = ""; Widget AppShell; if (!x_connect_to_server()) return; open_app_context(); if (app_context != NULL && xterm_Shell == (Widget)0) { int (*oldhandler)(); #if defined(HAVE_SETJMP_H) int (*oldIOhandler)(); #endif # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) struct timeval start_tv; if (p_verbose > 0) gettimeofday(&start_tv, NULL); # endif /* Ignore X errors while opening the display */ oldhandler = XSetErrorHandler(x_error_check); #if defined(HAVE_SETJMP_H) /* Ignore X IO errors while opening the display */ oldIOhandler = XSetIOErrorHandler(x_IOerror_check); mch_startjmp(); if (SETJMP(lc_jump_env) != 0) { mch_didjmp(); xterm_dpy = NULL; } else #endif { xterm_dpy = XtOpenDisplay(app_context, xterm_display, "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp); #if defined(HAVE_SETJMP_H) mch_endjmp(); #endif } #if defined(HAVE_SETJMP_H) /* Now handle X IO errors normally. */ (void)XSetIOErrorHandler(oldIOhandler); #endif /* Now handle X errors normally. */ (void)XSetErrorHandler(oldhandler); if (xterm_dpy == NULL) { if (p_verbose > 0) verb_msg((char_u *)_("Opening the X display failed")); return; } /* Catch terminating error of the X server connection. */ (void)XSetIOErrorHandler(x_IOerror_handler); # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) if (p_verbose > 0) { verbose_enter(); xopen_message(&start_tv); verbose_leave(); } # endif /* Create a Shell to make converters work. */ AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm", applicationShellWidgetClass, xterm_dpy, NULL); if (AppShell == (Widget)0) return; xterm_Shell = XtVaCreatePopupShell("VIM", topLevelShellWidgetClass, AppShell, XtNmappedWhenManaged, 0, XtNwidth, 1, XtNheight, 1, NULL); if (xterm_Shell == (Widget)0) return; x11_setup_atoms(xterm_dpy); x11_setup_selection(xterm_Shell); if (x11_display == NULL) x11_display = xterm_dpy; XtRealizeWidget(xterm_Shell); XSync(xterm_dpy, False); xterm_update(); } if (xterm_Shell != (Widget)0) { clip_init(TRUE); if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL) x11_window = (Window)atol(strp); /* Check if $WINDOWID is valid. */ if (test_x11_window(xterm_dpy) == FAIL) x11_window = 0; if (x11_window != 0) xterm_trace = 0; } } void start_xterm_trace(button) int button; { if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0) return; xterm_trace = 1; xterm_button = button; do_xterm_trace(); } void stop_xterm_trace() { if (xterm_trace < 0) return; xterm_trace = 0; } /* * Query the xterm pointer and generate mouse termcodes if necessary * return TRUE if dragging is active, else FALSE */ static int do_xterm_trace() { Window root, child; int root_x, root_y; int win_x, win_y; int row, col; int_u mask_return; char_u buf[50]; char_u *strp; long got_hints; static char_u *mouse_code; static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER}; static int prev_row = 0, prev_col = 0; static XSizeHints xterm_hints; if (xterm_trace <= 0) return FALSE; if (xterm_trace == 1) { /* Get the hints just before tracking starts. The font size might * have changed recently. */ if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints) || !(got_hints & PResizeInc) || xterm_hints.width_inc <= 1 || xterm_hints.height_inc <= 1) { xterm_trace = -1; /* Not enough data -- disable tracing */ return FALSE; } /* Rely on the same mouse code for the duration of this */ mouse_code = find_termcode(mouse_name); prev_row = mouse_row; prev_row = mouse_col; xterm_trace = 2; /* Find the offset of the chars, there might be a scrollbar on the * left of the window and/or a menu on the top (eterm etc.) */ XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y, &win_x, &win_y, &mask_return); xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row) - (xterm_hints.height_inc / 2); if (xterm_hints.y <= xterm_hints.height_inc / 2) xterm_hints.y = 2; xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col) - (xterm_hints.width_inc / 2); if (xterm_hints.x <= xterm_hints.width_inc / 2) xterm_hints.x = 2; return TRUE; } if (mouse_code == NULL || STRLEN(mouse_code) > 45) { xterm_trace = 0; return FALSE; } XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y, &win_x, &win_y, &mask_return); row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc); col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc); if (row == prev_row && col == prev_col) return TRUE; STRCPY(buf, mouse_code); strp = buf + STRLEN(buf); *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20; *strp++ = (char_u)(col + ' ' + 1); *strp++ = (char_u)(row + ' ' + 1); *strp = 0; add_to_input_buf(buf, STRLEN(buf)); prev_row = row; prev_col = col; return TRUE; } # if defined(FEAT_GUI) || defined(PROTO) /* * Destroy the display, window and app_context. Required for GTK. */ void clear_xterm_clip() { if (xterm_Shell != (Widget)0) { XtDestroyWidget(xterm_Shell); xterm_Shell = (Widget)0; } if (xterm_dpy != NULL) { # if 0 /* Lesstif and Solaris crash here, lose some memory */ XtCloseDisplay(xterm_dpy); # endif if (x11_display == xterm_dpy) x11_display = NULL; xterm_dpy = NULL; } # if 0 if (app_context != (XtAppContext)NULL) { /* Lesstif and Solaris crash here, lose some memory */ XtDestroyApplicationContext(app_context); app_context = (XtAppContext)NULL; } # endif } # endif /* * Catch up with any queued X events. This may put keyboard input into the * input buffer, call resize call-backs, trigger timers etc. If there is * nothing in the X event queue (& no timers pending), then we return * immediately. */ static void xterm_update() { XEvent event; while (XtAppPending(app_context) && !vim_is_input_buf_full()) { XtAppNextEvent(app_context, &event); #ifdef FEAT_CLIENTSERVER { XPropertyEvent *e = (XPropertyEvent *)&event; if (e->type == PropertyNotify && e->window == commWindow && e->atom == commProperty && e->state == PropertyNewValue) serverEventProc(xterm_dpy, &event); } #endif XtDispatchEvent(&event); } } int clip_xterm_own_selection(cbd) VimClipboard *cbd; { if (xterm_Shell != (Widget)0) return clip_x11_own_selection(xterm_Shell, cbd); return FAIL; } void clip_xterm_lose_selection(cbd) VimClipboard *cbd; { if (xterm_Shell != (Widget)0) clip_x11_lose_selection(xterm_Shell, cbd); } void clip_xterm_request_selection(cbd) VimClipboard *cbd; { if (xterm_Shell != (Widget)0) clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd); } void clip_xterm_set_selection(cbd) VimClipboard *cbd; { clip_x11_set_selection(cbd); } #endif #if defined(USE_XSMP) || defined(PROTO) /* * Code for X Session Management Protocol. */ static void xsmp_handle_save_yourself __ARGS((SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast)); static void xsmp_die __ARGS((SmcConn smc_conn, SmPointer client_data)); static void xsmp_save_complete __ARGS((SmcConn smc_conn, SmPointer client_data)); static void xsmp_shutdown_cancelled __ARGS((SmcConn smc_conn, SmPointer client_data)); static void xsmp_ice_connection __ARGS((IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData)); # if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT) static void xsmp_handle_interaction __ARGS((SmcConn smc_conn, SmPointer client_data)); /* * This is our chance to ask the user if they want to save, * or abort the logout */ static void xsmp_handle_interaction(smc_conn, client_data) SmcConn smc_conn; SmPointer client_data UNUSED; { cmdmod_T save_cmdmod; int cancel_shutdown = False; save_cmdmod = cmdmod; cmdmod.confirm = TRUE; if (check_changed_any(FALSE)) /* Mustn't logout */ cancel_shutdown = True; cmdmod = save_cmdmod; setcursor(); /* position cursor */ out_flush(); /* Done interaction */ SmcInteractDone(smc_conn, cancel_shutdown); /* Finish off * Only end save-yourself here if we're not cancelling shutdown; * we'll get a cancelled callback later in which we'll end it. * Hopefully get around glitchy SMs (like GNOME-1) */ if (!cancel_shutdown) { xsmp.save_yourself = False; SmcSaveYourselfDone(smc_conn, True); } } # endif /* * Callback that starts save-yourself. */ static void xsmp_handle_save_yourself(smc_conn, client_data, save_type, shutdown, interact_style, fast) SmcConn smc_conn; SmPointer client_data UNUSED; int save_type UNUSED; Bool shutdown; int interact_style UNUSED; Bool fast UNUSED; { /* Handle already being in saveyourself */ if (xsmp.save_yourself) SmcSaveYourselfDone(smc_conn, True); xsmp.save_yourself = True; xsmp.shutdown = shutdown; /* First up, preserve all files */ out_flush(); ml_sync_all(FALSE, FALSE); /* preserve all swap files */ if (p_verbose > 0) verb_msg((char_u *)_("XSMP handling save-yourself request")); # if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT) /* Now see if we can ask about unsaved files */ if (shutdown && !fast && gui.in_use) /* Need to interact with user, but need SM's permission */ SmcInteractRequest(smc_conn, SmDialogError, xsmp_handle_interaction, client_data); else # endif { /* Can stop the cycle here */ SmcSaveYourselfDone(smc_conn, True); xsmp.save_yourself = False; } } /* * Callback to warn us of imminent death. */ static void xsmp_die(smc_conn, client_data) SmcConn smc_conn UNUSED; SmPointer client_data UNUSED; { xsmp_close(); /* quit quickly leaving swapfiles for modified buffers behind */ getout_preserve_modified(0); } /* * Callback to tell us that save-yourself has completed. */ static void xsmp_save_complete(smc_conn, client_data) SmcConn smc_conn UNUSED; SmPointer client_data UNUSED; { xsmp.save_yourself = False; } /* * Callback to tell us that an instigated shutdown was cancelled * (maybe even by us) */ static void xsmp_shutdown_cancelled(smc_conn, client_data) SmcConn smc_conn; SmPointer client_data UNUSED; { if (xsmp.save_yourself) SmcSaveYourselfDone(smc_conn, True); xsmp.save_yourself = False; xsmp.shutdown = False; } /* * Callback to tell us that a new ICE connection has been established. */ static void xsmp_ice_connection(iceConn, clientData, opening, watchData) IceConn iceConn; IcePointer clientData UNUSED; Bool opening; IcePointer *watchData UNUSED; { /* Intercept creation of ICE connection fd */ if (opening) { xsmp_icefd = IceConnectionNumber(iceConn); IceRemoveConnectionWatch(xsmp_ice_connection, NULL); } } /* Handle any ICE processing that's required; return FAIL if SM lost */ int xsmp_handle_requests() { Bool rep; if (IceProcessMessages(xsmp.iceconn, NULL, &rep) == IceProcessMessagesIOError) { /* Lost ICE */ if (p_verbose > 0) verb_msg((char_u *)_("XSMP lost ICE connection")); xsmp_close(); return FAIL; } else return OK; } static int dummy; /* Set up X Session Management Protocol */ void xsmp_init(void) { char errorstring[80]; SmcCallbacks smcallbacks; #if 0 SmPropValue smname; SmProp smnameprop; SmProp *smprops[1]; #endif if (p_verbose > 0) verb_msg((char_u *)_("XSMP opening connection")); xsmp.save_yourself = xsmp.shutdown = False; /* Set up SM callbacks - must have all, even if they're not used */ smcallbacks.save_yourself.callback = xsmp_handle_save_yourself; smcallbacks.save_yourself.client_data = NULL; smcallbacks.die.callback = xsmp_die; smcallbacks.die.client_data = NULL; smcallbacks.save_complete.callback = xsmp_save_complete; smcallbacks.save_complete.client_data = NULL; smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled; smcallbacks.shutdown_cancelled.client_data = NULL; /* Set up a watch on ICE connection creations. The "dummy" argument is * apparently required for FreeBSD (we get a BUS error when using NULL). */ if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0) { if (p_verbose > 0) verb_msg((char_u *)_("XSMP ICE connection watch failed")); return; } /* Create an SM connection */ xsmp.smcconn = SmcOpenConnection( NULL, NULL, SmProtoMajor, SmProtoMinor, SmcSaveYourselfProcMask | SmcDieProcMask | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask, &smcallbacks, NULL, &xsmp.clientid, sizeof(errorstring), errorstring); if (xsmp.smcconn == NULL) { char errorreport[132]; if (p_verbose > 0) { vim_snprintf(errorreport, sizeof(errorreport), _("XSMP SmcOpenConnection failed: %s"), errorstring); verb_msg((char_u *)errorreport); } return; } xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn); #if 0 /* ID ourselves */ smname.value = "vim"; smname.length = 3; smnameprop.name = "SmProgram"; smnameprop.type = "SmARRAY8"; smnameprop.num_vals = 1; smnameprop.vals = &smname; smprops[0] = &smnameprop; SmcSetProperties(xsmp.smcconn, 1, smprops); #endif } /* Shut down XSMP comms. */ void xsmp_close() { if (xsmp_icefd != -1) { SmcCloseConnection(xsmp.smcconn, 0, NULL); if (xsmp.clientid != NULL) free(xsmp.clientid); xsmp.clientid = NULL; xsmp_icefd = -1; } } #endif /* USE_XSMP */ #ifdef EBCDIC /* Translate character to its CTRL- value */ char CtrlTable[] = { /* 00 - 5E */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* ^ */ 0x1E, /* - */ 0x1F, /* 61 - 6C */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* _ */ 0x1F, /* 6E - 80 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* a */ 0x01, /* b */ 0x02, /* c */ 0x03, /* d */ 0x37, /* e */ 0x2D, /* f */ 0x2E, /* g */ 0x2F, /* h */ 0x16, /* i */ 0x05, /* 8A - 90 */ 0, 0, 0, 0, 0, 0, 0, /* j */ 0x15, /* k */ 0x0B, /* l */ 0x0C, /* m */ 0x0D, /* n */ 0x0E, /* o */ 0x0F, /* p */ 0x10, /* q */ 0x11, /* r */ 0x12, /* 9A - A1 */ 0, 0, 0, 0, 0, 0, 0, 0, /* s */ 0x13, /* t */ 0x3C, /* u */ 0x3D, /* v */ 0x32, /* w */ 0x26, /* x */ 0x18, /* y */ 0x19, /* z */ 0x3F, /* AA - AC */ 0, 0, 0, /* [ */ 0x27, /* AE - BC */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* ] */ 0x1D, /* BE - C0 */ 0, 0, 0, /* A */ 0x01, /* B */ 0x02, /* C */ 0x03, /* D */ 0x37, /* E */ 0x2D, /* F */ 0x2E, /* G */ 0x2F, /* H */ 0x16, /* I */ 0x05, /* CA - D0 */ 0, 0, 0, 0, 0, 0, 0, /* J */ 0x15, /* K */ 0x0B, /* L */ 0x0C, /* M */ 0x0D, /* N */ 0x0E, /* O */ 0x0F, /* P */ 0x10, /* Q */ 0x11, /* R */ 0x12, /* DA - DF */ 0, 0, 0, 0, 0, 0, /* \ */ 0x1C, /* E1 */ 0, /* S */ 0x13, /* T */ 0x3C, /* U */ 0x3D, /* V */ 0x32, /* W */ 0x26, /* X */ 0x18, /* Y */ 0x19, /* Z */ 0x3F, /* EA - FF*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; char MetaCharTable[]= {/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0, 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0, '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0, 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0 }; /* TODO: Use characters NOT numbers!!! */ char CtrlCharTable[]= {/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214, 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109, 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199, 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233, }; #endif
zyz2011-vim
src/os_unix.c
C
gpl2
169,708
/* os_os2_cfg.h */ /* vi:set ts=8 sts=4 sw=4: */ #define CASE_INSENSITIVE_FILENAME /* ignore case when comparing file names */ #define SPACE_IN_FILENAME #define BACKSLASH_IN_FILENAME #define BINARY_FILE_IO #define USE_CRNL /* lines end in CR-NL instead of NL */ #define NO_EXPANDPATH /* always call mch_expand_wildcards */ #define USE_EXE_NAME /* use argv[0] for $VIM */ #define USE_TERM_CONSOLE #define HAVE_DUP /* have dup() */ #define FNAME_ILLEGAL "\"*?><|" /* illegal characters in a file name */ /* * The rest is manually generated from configure.in by Paul Slootman. */ /* Define unless no X support found */ #undef HAVE_X11 /* Define when terminfo support found */ #undef TERMINFO /* Define when termcap.h contains ospeed */ #define HAVE_OSPEED 1 #define HAVE_STRICMP #define HAVE_STRNICMP /* Define when ospeed can be extern */ #define OSPEED_EXTERN /* Define when termcap.h contains UP, BC and PC */ #define HAVE_UP_BC_PC 1 /* Define when UP, BC and PC can be extern */ #define UP_BC_PC_EXTERN /* Define when termcap.h defines outfuntype */ #undef HAVE_OUTFUNTYPE /* Define when __DATE__ " " __TIME__ can be used */ #define HAVE_DATE_TIME 1 #undef UNIX /* define always by current configure script */ /* Defined to the size of an int */ #define SIZEOF_INT 4 /* * If we cannot trust one of the following from the libraries, we use our * own safe but probably slower mch_memmove(). */ #define USEBCOPY 1 #undef USEMEMMOVE #undef USEMEMCPY /* Define to empty if the keyword does not work. */ #undef const /* Define to `int' if <sys/types.h> doesn't define. */ #undef mode_t /* Define to `long' if <sys/types.h> doesn't define. */ #undef off_t /* Define to `long' if <sys/types.h> doesn't define. */ #undef pid_t /* Define to `unsigned' if <sys/types.h> doesn't define. */ #undef size_t /* Define to `int' if <sys/types.h> doesn't define. */ #undef uid_t /* Define to `int' if <sys/types.h> doesn't define. */ #undef gid_t /* Define if you can safely include both <sys/time.h> and <time.h>. */ #define TIME_WITH_SYS_TIME 1 /* Define if you can safely include both <sys/time.h> and <sys/select.h>. */ #define SYS_SELECT_WITH_SYS_TIME 1 /* Define as the return type of signal handlers (int or void). */ #define RETSIGTYPE void /* Define as the command at the end of signal handlers ("" or "return 0;"). */ #define SIGRETURN /* Define if toupper/tolower only work on lower/uppercase characters */ #undef BROKEN_TOUPPER /* Define if tgetstr() has a second argument that is (char *) */ #undef TGETSTR_CHAR_P /* Define if you have the sigset() function. */ #undef HAVE_SIGSET /* Define if the getcwd() function should not be used. */ #undef BAD_GETCWD /* Define if you have the getcwd() function. */ #define HAVE_GETCWD 1 /* Define if you have the getwd() function. */ #define HAVE_GETWD 1 /* Define if you have the select() function. */ #define HAVE_SELECT 1 /* Define if you have the strcspn() function. */ #define HAVE_STRCSPN 1 /* Define if you have the strtol() function. */ #define HAVE_STRTOL 1 /* Define if you have the tgetent() function. */ #define HAVE_TGETENT 1 #define HAVE_STRFTIME /* guessed */ /* Define if you have the memset() function. */ #define HAVE_MEMSET 1 /* Define if you have the strerror() function. */ #define HAVE_STRERROR 1 /* Define if you have the strcasecmp() function. */ #undef HAVE_STRCASECMP /* Define if you have the fchown() function. */ #undef HAVE_FCHOWN /* Define if you have the rename() function. */ #define HAVE_RENAME 1 /* Define if you have the fsync() function. */ #undef HAVE_FSYNC /* exists, but apparently Bad Things happen when used */ /* Define if you have the fchdir() function. */ #undef HAVE_FCHDIR /* Define if you have the setenv() function. */ #undef HAVE_SETENV /* Define if you have the putenv() function. */ #define HAVE_PUTENV 1 /* Define if you have the gettimeofday() function. */ #undef HAVE_GETTIMEOFDAY /* Define if you have the getpwuid() function. */ #undef HAVE_GETPWUID /* Define if you have the getpwnam() function. */ #undef HAVE_GETPWNAM /* Define if you have the qsort() function. */ #define HAVE_QSORT 1 /* Define if you have the <dirent.h> header file. */ #define HAVE_DIRENT_H 1 /* Define if you have the <sys/ndir.h> header file. */ #undef HAVE_SYS_NDIR_H /* Define if you have the <sys/dir.h> header file. */ #undef HAVE_SYS_DIR_H /* Define if you have the <ndir.h> header file. */ #undef HAVE_NDIR_H /* Define if you have <sys/wait.h> that is POSIX.1 compatible. */ #define HAVE_SYS_WAIT_H 1 /* Define if you have a <sys/wait.h> that is not POSIX.1 compatible. */ #undef HAVE_UNION_WAIT /* This is currently unused in vim: */ /* Define if you have the ANSI C header files. */ /* #undef STDC_HEADERS */ /* added by David Sanders */ #define HAVE_STDARG_H 1 /* instead, we check a few STDC things ourselves */ #define HAVE_STDLIB_H 1 #undef HAVE_STRING_H /* On EMX it is better to use strings.h */ /* Define if you have the <sys/select.h> header file. */ #undef HAVE_SYS_SELECT_H /* Define if you have the <sys/utsname.h> header file. */ #define HAVE_SYS_UTSNAME_H 1 /* Define if you have the <termcap.h> header file. */ #define HAVE_TERMCAP_H 1 /* Define if you have the <fcntl.h> header file. */ #define HAVE_FCNTL_H 1 /* Define if you have the <sgtty.h> header file. */ #define HAVE_SGTTY_H 1 /* Define if you have the <sys/ioctl.h> header file. */ #define HAVE_SYS_IOCTL_H 1 /* Define if you have the <sys/time.h> header file. */ #define HAVE_SYS_TIME_H /* Define if you have the <termio.h> header file. */ #undef HAVE_TERMIO_H /* Define if you have the <unistd.h> header file. */ #define HAVE_UNISTD_H 1 /* Define if you have the <stropts.h> header file. */ #undef HAVE_STROPTS_H /* Define if you have the <errno.h> header file. */ #define HAVE_ERRNO_H 1 /* Define if you have the <strings.h> header file. */ #define HAVE_STRINGS_H 1 /* Define if you have the <sys/systeminfo.h> header file. */ #undef HAVE_SYS_SYSTEMINFO_H /* Define if you have the <locale.h> header file. */ #define HAVE_LOCALE_H 1 /* Define if you have the <sys/stream.h> header file. */ #undef HAVE_SYS_STREAM_H /* Define if you have the <sys/ptem.h> header file. */ #undef HAVE_SYS_PTEM_H /* Define if you have the <termios.h> header file. */ #define HAVE_TERMIOS_H 1 /* Define if you have the <libc.h> header file. */ #undef HAVE_LIBC_H /* Define if you have the <sys/statfs.h> header file. */ #undef HAVE_SYS_STATFS_H /* Define if you have the <sys/poll.h> header file. */ #undef HAVE_SYS_POLL_H /* Define if you have the <pwd.h> header file. */ #undef HAVE_PWD_H
zyz2011-vim
src/os_os2_cfg.h
C
gpl2
6,651
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * Code to handle user-settable options. This is all pretty much table- * driven. Checklist for adding a new option: * - Put it in the options array below (copy an existing entry). * - For a global option: Add a variable for it in option.h. * - For a buffer or window local option: * - Add a PV_XX entry to the enum below. * - Add a variable to the window or buffer struct in structs.h. * - For a window option, add some code to copy_winopt(). * - For a buffer option, add some code to buf_copy_options(). * - For a buffer string option, add code to check_buf_options(). * - If it's a numeric option, add any necessary bounds checks to do_set(). * - If it's a list of flags, add some code in do_set(), search for WW_ALL. * - When adding an option with expansion (P_EXPAND), but with a different * default for Vi and Vim (no P_VI_DEF), add some code at VIMEXP. * - Add documentation! One line in doc/help.txt, full description in * options.txt, and any other related places. * - Add an entry in runtime/optwin.vim. * When making changes: * - Adjust the help for the option in doc/option.txt. * - When an entry has the P_VIM flag, or is lacking the P_VI_DEF flag, add a * comment at the help for the 'compatible' option. */ #define IN_OPTION_C #include "vim.h" /* * The options that are local to a window or buffer have "indir" set to one of * these values. Special values: * PV_NONE: global option. * PV_WIN is added: window-local option * PV_BUF is added: buffer-local option * PV_BOTH is added: global option which also has a local value. */ #define PV_BOTH 0x1000 #define PV_WIN 0x2000 #define PV_BUF 0x4000 #define PV_MASK 0x0fff #define OPT_WIN(x) (idopt_T)(PV_WIN + (int)(x)) #define OPT_BUF(x) (idopt_T)(PV_BUF + (int)(x)) #define OPT_BOTH(x) (idopt_T)(PV_BOTH + (int)(x)) /* * Definition of the PV_ values for buffer-local options. * The BV_ values are defined in option.h. */ #define PV_AI OPT_BUF(BV_AI) #define PV_AR OPT_BOTH(OPT_BUF(BV_AR)) #ifdef FEAT_QUICKFIX # define PV_BH OPT_BUF(BV_BH) # define PV_BT OPT_BUF(BV_BT) # define PV_EFM OPT_BOTH(OPT_BUF(BV_EFM)) # define PV_GP OPT_BOTH(OPT_BUF(BV_GP)) # define PV_MP OPT_BOTH(OPT_BUF(BV_MP)) #endif #define PV_BIN OPT_BUF(BV_BIN) #define PV_BL OPT_BUF(BV_BL) #ifdef FEAT_MBYTE # define PV_BOMB OPT_BUF(BV_BOMB) #endif #define PV_CI OPT_BUF(BV_CI) #ifdef FEAT_CINDENT # define PV_CIN OPT_BUF(BV_CIN) # define PV_CINK OPT_BUF(BV_CINK) # define PV_CINO OPT_BUF(BV_CINO) #endif #if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT) # define PV_CINW OPT_BUF(BV_CINW) #endif #define PV_CM OPT_BOTH(OPT_BUF(BV_CM)) #ifdef FEAT_FOLDING # define PV_CMS OPT_BUF(BV_CMS) #endif #ifdef FEAT_COMMENTS # define PV_COM OPT_BUF(BV_COM) #endif #ifdef FEAT_INS_EXPAND # define PV_CPT OPT_BUF(BV_CPT) # define PV_DICT OPT_BOTH(OPT_BUF(BV_DICT)) # define PV_TSR OPT_BOTH(OPT_BUF(BV_TSR)) #endif #ifdef FEAT_COMPL_FUNC # define PV_CFU OPT_BUF(BV_CFU) #endif #ifdef FEAT_FIND_ID # define PV_DEF OPT_BOTH(OPT_BUF(BV_DEF)) # define PV_INC OPT_BOTH(OPT_BUF(BV_INC)) #endif #define PV_EOL OPT_BUF(BV_EOL) #define PV_EP OPT_BOTH(OPT_BUF(BV_EP)) #define PV_ET OPT_BUF(BV_ET) #ifdef FEAT_MBYTE # define PV_FENC OPT_BUF(BV_FENC) #endif #if defined(FEAT_BEVAL) && defined(FEAT_EVAL) # define PV_BEXPR OPT_BOTH(OPT_BUF(BV_BEXPR)) #endif #ifdef FEAT_EVAL # define PV_FEX OPT_BUF(BV_FEX) #endif #define PV_FF OPT_BUF(BV_FF) #define PV_FLP OPT_BUF(BV_FLP) #define PV_FO OPT_BUF(BV_FO) #ifdef FEAT_AUTOCMD # define PV_FT OPT_BUF(BV_FT) #endif #define PV_IMI OPT_BUF(BV_IMI) #define PV_IMS OPT_BUF(BV_IMS) #if defined(FEAT_CINDENT) && defined(FEAT_EVAL) # define PV_INDE OPT_BUF(BV_INDE) # define PV_INDK OPT_BUF(BV_INDK) #endif #if defined(FEAT_FIND_ID) && defined(FEAT_EVAL) # define PV_INEX OPT_BUF(BV_INEX) #endif #define PV_INF OPT_BUF(BV_INF) #define PV_ISK OPT_BUF(BV_ISK) #ifdef FEAT_CRYPT # define PV_KEY OPT_BUF(BV_KEY) #endif #ifdef FEAT_KEYMAP # define PV_KMAP OPT_BUF(BV_KMAP) #endif #define PV_KP OPT_BOTH(OPT_BUF(BV_KP)) #ifdef FEAT_LISP # define PV_LISP OPT_BUF(BV_LISP) #endif #define PV_MA OPT_BUF(BV_MA) #define PV_ML OPT_BUF(BV_ML) #define PV_MOD OPT_BUF(BV_MOD) #define PV_MPS OPT_BUF(BV_MPS) #define PV_NF OPT_BUF(BV_NF) #ifdef FEAT_COMPL_FUNC # define PV_OFU OPT_BUF(BV_OFU) #endif #define PV_PATH OPT_BOTH(OPT_BUF(BV_PATH)) #define PV_PI OPT_BUF(BV_PI) #ifdef FEAT_TEXTOBJ # define PV_QE OPT_BUF(BV_QE) #endif #define PV_RO OPT_BUF(BV_RO) #ifdef FEAT_SMARTINDENT # define PV_SI OPT_BUF(BV_SI) #endif #ifndef SHORT_FNAME # define PV_SN OPT_BUF(BV_SN) #endif #ifdef FEAT_SYN_HL # define PV_SMC OPT_BUF(BV_SMC) # define PV_SYN OPT_BUF(BV_SYN) #endif #ifdef FEAT_SPELL # define PV_SPC OPT_BUF(BV_SPC) # define PV_SPF OPT_BUF(BV_SPF) # define PV_SPL OPT_BUF(BV_SPL) #endif #define PV_STS OPT_BUF(BV_STS) #ifdef FEAT_SEARCHPATH # define PV_SUA OPT_BUF(BV_SUA) #endif #define PV_SW OPT_BUF(BV_SW) #define PV_SWF OPT_BUF(BV_SWF) #define PV_TAGS OPT_BOTH(OPT_BUF(BV_TAGS)) #define PV_TS OPT_BUF(BV_TS) #define PV_TW OPT_BUF(BV_TW) #define PV_TX OPT_BUF(BV_TX) #ifdef FEAT_PERSISTENT_UNDO # define PV_UDF OPT_BUF(BV_UDF) #endif #define PV_WM OPT_BUF(BV_WM) /* * Definition of the PV_ values for window-local options. * The WV_ values are defined in option.h. */ #define PV_LIST OPT_WIN(WV_LIST) #ifdef FEAT_ARABIC # define PV_ARAB OPT_WIN(WV_ARAB) #endif #ifdef FEAT_DIFF # define PV_DIFF OPT_WIN(WV_DIFF) #endif #ifdef FEAT_FOLDING # define PV_FDC OPT_WIN(WV_FDC) # define PV_FEN OPT_WIN(WV_FEN) # define PV_FDI OPT_WIN(WV_FDI) # define PV_FDL OPT_WIN(WV_FDL) # define PV_FDM OPT_WIN(WV_FDM) # define PV_FML OPT_WIN(WV_FML) # define PV_FDN OPT_WIN(WV_FDN) # ifdef FEAT_EVAL # define PV_FDE OPT_WIN(WV_FDE) # define PV_FDT OPT_WIN(WV_FDT) # endif # define PV_FMR OPT_WIN(WV_FMR) #endif #ifdef FEAT_LINEBREAK # define PV_LBR OPT_WIN(WV_LBR) #endif #define PV_NU OPT_WIN(WV_NU) #define PV_RNU OPT_WIN(WV_RNU) #ifdef FEAT_LINEBREAK # define PV_NUW OPT_WIN(WV_NUW) #endif #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX) # define PV_PVW OPT_WIN(WV_PVW) #endif #ifdef FEAT_RIGHTLEFT # define PV_RL OPT_WIN(WV_RL) # define PV_RLC OPT_WIN(WV_RLC) #endif #ifdef FEAT_SCROLLBIND # define PV_SCBIND OPT_WIN(WV_SCBIND) #endif #define PV_SCROLL OPT_WIN(WV_SCROLL) #ifdef FEAT_SPELL # define PV_SPELL OPT_WIN(WV_SPELL) #endif #ifdef FEAT_SYN_HL # define PV_CUC OPT_WIN(WV_CUC) # define PV_CUL OPT_WIN(WV_CUL) # define PV_CC OPT_WIN(WV_CC) #endif #ifdef FEAT_STL_OPT # define PV_STL OPT_BOTH(OPT_WIN(WV_STL)) #endif #ifdef FEAT_WINDOWS # define PV_WFH OPT_WIN(WV_WFH) #endif #ifdef FEAT_VERTSPLIT # define PV_WFW OPT_WIN(WV_WFW) #endif #define PV_WRAP OPT_WIN(WV_WRAP) #ifdef FEAT_CURSORBIND # define PV_CRBIND OPT_WIN(WV_CRBIND) #endif #ifdef FEAT_CONCEAL # define PV_COCU OPT_WIN(WV_COCU) # define PV_COLE OPT_WIN(WV_COLE) #endif /* WV_ and BV_ values get typecasted to this for the "indir" field */ typedef enum { PV_NONE = 0, PV_MAXVAL = 0xffff /* to avoid warnings for value out of range */ } idopt_T; /* * Options local to a window have a value local to a buffer and global to all * buffers. Indicate this by setting "var" to VAR_WIN. */ #define VAR_WIN ((char_u *)-1) /* * These are the global values for options which are also local to a buffer. * Only to be used in option.c! */ static int p_ai; static int p_bin; #ifdef FEAT_MBYTE static int p_bomb; #endif #if defined(FEAT_QUICKFIX) static char_u *p_bh; static char_u *p_bt; #endif static int p_bl; static int p_ci; #ifdef FEAT_CINDENT static int p_cin; static char_u *p_cink; static char_u *p_cino; #endif #if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT) static char_u *p_cinw; #endif #ifdef FEAT_COMMENTS static char_u *p_com; #endif #ifdef FEAT_FOLDING static char_u *p_cms; #endif #ifdef FEAT_INS_EXPAND static char_u *p_cpt; #endif #ifdef FEAT_COMPL_FUNC static char_u *p_cfu; static char_u *p_ofu; #endif static int p_eol; static int p_et; #ifdef FEAT_MBYTE static char_u *p_fenc; #endif static char_u *p_ff; static char_u *p_fo; static char_u *p_flp; #ifdef FEAT_AUTOCMD static char_u *p_ft; #endif static long p_iminsert; static long p_imsearch; #if defined(FEAT_FIND_ID) && defined(FEAT_EVAL) static char_u *p_inex; #endif #if defined(FEAT_CINDENT) && defined(FEAT_EVAL) static char_u *p_inde; static char_u *p_indk; #endif #if defined(FEAT_EVAL) static char_u *p_fex; #endif static int p_inf; static char_u *p_isk; #ifdef FEAT_CRYPT static char_u *p_key; #endif #ifdef FEAT_LISP static int p_lisp; #endif static int p_ml; static int p_ma; static int p_mod; static char_u *p_mps; static char_u *p_nf; static int p_pi; #ifdef FEAT_TEXTOBJ static char_u *p_qe; #endif static int p_ro; #ifdef FEAT_SMARTINDENT static int p_si; #endif #ifndef SHORT_FNAME static int p_sn; #endif static long p_sts; #if defined(FEAT_SEARCHPATH) static char_u *p_sua; #endif static long p_sw; static int p_swf; #ifdef FEAT_SYN_HL static long p_smc; static char_u *p_syn; #endif #ifdef FEAT_SPELL static char_u *p_spc; static char_u *p_spf; static char_u *p_spl; #endif static long p_ts; static long p_tw; static int p_tx; #ifdef FEAT_PERSISTENT_UNDO static int p_udf; #endif static long p_wm; #ifdef FEAT_KEYMAP static char_u *p_keymap; #endif /* Saved values for when 'bin' is set. */ static int p_et_nobin; static int p_ml_nobin; static long p_tw_nobin; static long p_wm_nobin; /* Saved values for when 'paste' is set */ static long p_tw_nopaste; static long p_wm_nopaste; static long p_sts_nopaste; static int p_ai_nopaste; struct vimoption { char *fullname; /* full option name */ char *shortname; /* permissible abbreviation */ long_u flags; /* see below */ char_u *var; /* global option: pointer to variable; * window-local option: VAR_WIN; * buffer-local option: global value */ idopt_T indir; /* global option: PV_NONE; * local option: indirect option index */ char_u *def_val[2]; /* default values for variable (vi and vim) */ #ifdef FEAT_EVAL scid_T scriptID; /* script in which the option was last set */ # define SCRIPTID_INIT , 0 #else # define SCRIPTID_INIT #endif }; #define VI_DEFAULT 0 /* def_val[VI_DEFAULT] is Vi default value */ #define VIM_DEFAULT 1 /* def_val[VIM_DEFAULT] is Vim default value */ /* * Flags */ #define P_BOOL 0x01 /* the option is boolean */ #define P_NUM 0x02 /* the option is numeric */ #define P_STRING 0x04 /* the option is a string */ #define P_ALLOCED 0x08 /* the string option is in allocated memory, must use free_string_option() when assigning new value. Not set if default is the same. */ #define P_EXPAND 0x10 /* environment expansion. NOTE: P_EXPAND can never be used for local or hidden options! */ #define P_NODEFAULT 0x40 /* don't set to default value */ #define P_DEF_ALLOCED 0x80 /* default value is in allocated memory, must use vim_free() when assigning new value */ #define P_WAS_SET 0x100 /* option has been set/reset */ #define P_NO_MKRC 0x200 /* don't include in :mkvimrc output */ #define P_VI_DEF 0x400 /* Use Vi default for Vim */ #define P_VIM 0x800 /* Vim option, reset when 'cp' set */ /* when option changed, what to display: */ #define P_RSTAT 0x1000 /* redraw status lines */ #define P_RWIN 0x2000 /* redraw current window */ #define P_RBUF 0x4000 /* redraw current buffer */ #define P_RALL 0x6000 /* redraw all windows */ #define P_RCLR 0x7000 /* clear and redraw all */ #define P_COMMA 0x8000 /* comma separated list */ #define P_NODUP 0x10000L /* don't allow duplicate strings */ #define P_FLAGLIST 0x20000L /* list of single-char flags */ #define P_SECURE 0x40000L /* cannot change in modeline or secure mode */ #define P_GETTEXT 0x80000L /* expand default value with _() */ #define P_NOGLOB 0x100000L /* do not use local value for global vimrc */ #define P_NFNAME 0x200000L /* only normal file name chars allowed */ #define P_INSECURE 0x400000L /* option was set from a modeline */ #define P_PRI_MKRC 0x800000L /* priority for :mkvimrc (setting option has side effects) */ #define P_NO_ML 0x1000000L /* not allowed in modeline */ #define P_CURSWANT 0x2000000L /* update curswant required; not needed when * there is a redraw flag */ #define ISK_LATIN1 (char_u *)"@,48-57,_,192-255" /* 'isprint' for latin1 is also used for MS-Windows cp1252, where 0x80 is used * for the currency sign. */ #if defined(MSDOS) || defined(MSWIN) || defined(OS2) # define ISP_LATIN1 (char_u *)"@,~-255" #else # define ISP_LATIN1 (char_u *)"@,161-255" #endif /* The 16 bit MS-DOS version is low on space, make the string as short as * possible when compiling with few features. */ #if defined(FEAT_DIFF) || defined(FEAT_FOLDING) || defined(FEAT_SPELL) \ || defined(FEAT_VERTSPLIT) || defined(FEAT_CLIPBOARD) \ || defined(FEAT_INS_EXPAND) || defined(FEAT_SYN_HL) || defined(FEAT_CONCEAL) # define HIGHLIGHT_INIT "8:SpecialKey,@:NonText,d:Directory,e:ErrorMsg,i:IncSearch,l:Search,m:MoreMsg,M:ModeMsg,n:LineNr,N:CursorLineNr,r:Question,s:StatusLine,S:StatusLineNC,c:VertSplit,t:Title,v:Visual,V:VisualNOS,w:WarningMsg,W:WildMenu,f:Folded,F:FoldColumn,A:DiffAdd,C:DiffChange,D:DiffDelete,T:DiffText,>:SignColumn,-:Conceal,B:SpellBad,P:SpellCap,R:SpellRare,L:SpellLocal,+:Pmenu,=:PmenuSel,x:PmenuSbar,X:PmenuThumb,*:TabLine,#:TabLineSel,_:TabLineFill,!:CursorColumn,.:CursorLine,o:ColorColumn" #else # define HIGHLIGHT_INIT "8:SpecialKey,@:NonText,d:Directory,e:ErrorMsg,i:IncSearch,l:Search,m:MoreMsg,M:ModeMsg,n:LineNr,N:CursorLineNr,r:Question,s:StatusLine,S:StatusLineNC,t:Title,v:Visual,w:WarningMsg,W:WildMenu,>:SignColumn,*:TabLine,#:TabLineSel,_:TabLineFill" #endif /* * options[] is initialized here. * The order of the options MUST be alphabetic for ":set all" and findoption(). * All option names MUST start with a lowercase letter (for findoption()). * Exception: "t_" options are at the end. * The options with a NULL variable are 'hidden': a set command for them is * ignored and they are not printed. */ static struct vimoption #ifdef FEAT_GUI_W16 _far #endif options[] = { {"aleph", "al", P_NUM|P_VI_DEF|P_CURSWANT, #ifdef FEAT_RIGHTLEFT (char_u *)&p_aleph, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif { #if (defined(MSDOS) || defined(WIN3264) || defined(OS2)) && !defined(FEAT_GUI_W32) (char_u *)128L, #else (char_u *)224L, #endif (char_u *)0L} SCRIPTID_INIT}, {"antialias", "anti", P_BOOL|P_VI_DEF|P_VIM|P_RCLR, #if defined(FEAT_GUI) && defined(MACOS_X) (char_u *)&p_antialias, PV_NONE, {(char_u *)FALSE, (char_u *)FALSE} #else (char_u *)NULL, PV_NONE, {(char_u *)FALSE, (char_u *)FALSE} #endif SCRIPTID_INIT}, {"arabic", "arab", P_BOOL|P_VI_DEF|P_VIM|P_CURSWANT, #ifdef FEAT_ARABIC (char_u *)VAR_WIN, PV_ARAB, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"arabicshape", "arshape", P_BOOL|P_VI_DEF|P_VIM|P_RCLR, #ifdef FEAT_ARABIC (char_u *)&p_arshape, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, {"allowrevins", "ari", P_BOOL|P_VI_DEF|P_VIM, #ifdef FEAT_RIGHTLEFT (char_u *)&p_ari, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"altkeymap", "akm", P_BOOL|P_VI_DEF, #ifdef FEAT_FKMAP (char_u *)&p_altkeymap, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"ambiwidth", "ambw", P_STRING|P_VI_DEF|P_RCLR, #if defined(FEAT_MBYTE) (char_u *)&p_ambw, PV_NONE, {(char_u *)"single", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, #ifdef FEAT_AUTOCHDIR {"autochdir", "acd", P_BOOL|P_VI_DEF, (char_u *)&p_acd, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, #endif {"autoindent", "ai", P_BOOL|P_VI_DEF, (char_u *)&p_ai, PV_AI, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"autoprint", "ap", P_BOOL|P_VI_DEF, (char_u *)NULL, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"autoread", "ar", P_BOOL|P_VI_DEF, (char_u *)&p_ar, PV_AR, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"autowrite", "aw", P_BOOL|P_VI_DEF, (char_u *)&p_aw, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"autowriteall","awa", P_BOOL|P_VI_DEF, (char_u *)&p_awa, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"background", "bg", P_STRING|P_VI_DEF|P_RCLR, (char_u *)&p_bg, PV_NONE, { #if (defined(MSDOS) || defined(OS2) || defined(WIN3264)) && !defined(FEAT_GUI) (char_u *)"dark", #else (char_u *)"light", #endif (char_u *)0L} SCRIPTID_INIT}, {"backspace", "bs", P_STRING|P_VI_DEF|P_VIM|P_COMMA|P_NODUP, (char_u *)&p_bs, PV_NONE, {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"backup", "bk", P_BOOL|P_VI_DEF|P_VIM, (char_u *)&p_bk, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"backupcopy", "bkc", P_STRING|P_VIM|P_COMMA|P_NODUP, (char_u *)&p_bkc, PV_NONE, #ifdef UNIX {(char_u *)"yes", (char_u *)"auto"} #else {(char_u *)"auto", (char_u *)"auto"} #endif SCRIPTID_INIT}, {"backupdir", "bdir", P_STRING|P_EXPAND|P_VI_DEF|P_COMMA|P_NODUP|P_SECURE, (char_u *)&p_bdir, PV_NONE, {(char_u *)DFLT_BDIR, (char_u *)0L} SCRIPTID_INIT}, {"backupext", "bex", P_STRING|P_VI_DEF|P_NFNAME, (char_u *)&p_bex, PV_NONE, { #ifdef VMS (char_u *)"_", #else (char_u *)"~", #endif (char_u *)0L} SCRIPTID_INIT}, {"backupskip", "bsk", P_STRING|P_VI_DEF|P_COMMA, #ifdef FEAT_WILDIGN (char_u *)&p_bsk, PV_NONE, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, #ifdef FEAT_BEVAL {"balloondelay","bdlay",P_NUM|P_VI_DEF, (char_u *)&p_bdlay, PV_NONE, {(char_u *)600L, (char_u *)0L} SCRIPTID_INIT}, {"ballooneval", "beval",P_BOOL|P_VI_DEF|P_NO_MKRC, (char_u *)&p_beval, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, # ifdef FEAT_EVAL {"balloonexpr", "bexpr", P_STRING|P_ALLOCED|P_VI_DEF|P_VIM, (char_u *)&p_bexpr, PV_BEXPR, {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, # endif #endif {"beautify", "bf", P_BOOL|P_VI_DEF, (char_u *)NULL, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"binary", "bin", P_BOOL|P_VI_DEF|P_RSTAT, (char_u *)&p_bin, PV_BIN, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"bioskey", "biosk",P_BOOL|P_VI_DEF, #ifdef MSDOS (char_u *)&p_biosk, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, {"bomb", NULL, P_BOOL|P_NO_MKRC|P_VI_DEF|P_RSTAT, #ifdef FEAT_MBYTE (char_u *)&p_bomb, PV_BOMB, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"breakat", "brk", P_STRING|P_VI_DEF|P_RALL|P_FLAGLIST, #ifdef FEAT_LINEBREAK (char_u *)&p_breakat, PV_NONE, {(char_u *)" \t!@*-+;:,./?", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"browsedir", "bsdir",P_STRING|P_VI_DEF, #ifdef FEAT_BROWSE (char_u *)&p_bsdir, PV_NONE, {(char_u *)"last", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"bufhidden", "bh", P_STRING|P_ALLOCED|P_VI_DEF|P_NOGLOB, #if defined(FEAT_QUICKFIX) (char_u *)&p_bh, PV_BH, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"buflisted", "bl", P_BOOL|P_VI_DEF|P_NOGLOB, (char_u *)&p_bl, PV_BL, {(char_u *)1L, (char_u *)0L} SCRIPTID_INIT}, {"buftype", "bt", P_STRING|P_ALLOCED|P_VI_DEF|P_NOGLOB, #if defined(FEAT_QUICKFIX) (char_u *)&p_bt, PV_BT, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"casemap", "cmp", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, #ifdef FEAT_MBYTE (char_u *)&p_cmp, PV_NONE, {(char_u *)"internal,keepascii", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"cdpath", "cd", P_STRING|P_EXPAND|P_VI_DEF|P_COMMA|P_NODUP, #ifdef FEAT_SEARCHPATH (char_u *)&p_cdpath, PV_NONE, {(char_u *)",,", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"cedit", NULL, P_STRING, #ifdef FEAT_CMDWIN (char_u *)&p_cedit, PV_NONE, {(char_u *)"", (char_u *)CTRL_F_STR} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"charconvert", "ccv", P_STRING|P_VI_DEF|P_SECURE, #if defined(FEAT_MBYTE) && defined(FEAT_EVAL) (char_u *)&p_ccv, PV_NONE, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"cindent", "cin", P_BOOL|P_VI_DEF|P_VIM, #ifdef FEAT_CINDENT (char_u *)&p_cin, PV_CIN, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"cinkeys", "cink", P_STRING|P_ALLOCED|P_VI_DEF|P_COMMA|P_NODUP, #ifdef FEAT_CINDENT (char_u *)&p_cink, PV_CINK, {(char_u *)"0{,0},0),:,0#,!^F,o,O,e", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"cinoptions", "cino", P_STRING|P_ALLOCED|P_VI_DEF|P_COMMA|P_NODUP, #ifdef FEAT_CINDENT (char_u *)&p_cino, PV_CINO, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"cinwords", "cinw", P_STRING|P_ALLOCED|P_VI_DEF|P_COMMA|P_NODUP, #if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT) (char_u *)&p_cinw, PV_CINW, {(char_u *)"if,else,while,do,for,switch", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"clipboard", "cb", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, #ifdef FEAT_CLIPBOARD (char_u *)&p_cb, PV_NONE, # ifdef FEAT_XCLIPBOARD {(char_u *)"autoselect,exclude:cons\\|linux", (char_u *)0L} # else {(char_u *)"", (char_u *)0L} # endif #else (char_u *)NULL, PV_NONE, {(char_u *)"", (char_u *)0L} #endif SCRIPTID_INIT}, {"cmdheight", "ch", P_NUM|P_VI_DEF|P_RALL, (char_u *)&p_ch, PV_NONE, {(char_u *)1L, (char_u *)0L} SCRIPTID_INIT}, {"cmdwinheight", "cwh", P_NUM|P_VI_DEF, #ifdef FEAT_CMDWIN (char_u *)&p_cwh, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)7L, (char_u *)0L} SCRIPTID_INIT}, {"colorcolumn", "cc", P_STRING|P_VI_DEF|P_COMMA|P_NODUP|P_RWIN, #ifdef FEAT_SYN_HL (char_u *)VAR_WIN, PV_CC, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"columns", "co", P_NUM|P_NODEFAULT|P_NO_MKRC|P_VI_DEF|P_RCLR, (char_u *)&Columns, PV_NONE, {(char_u *)80L, (char_u *)0L} SCRIPTID_INIT}, {"comments", "com", P_STRING|P_ALLOCED|P_VI_DEF|P_COMMA|P_NODUP|P_CURSWANT, #ifdef FEAT_COMMENTS (char_u *)&p_com, PV_COM, {(char_u *)"s1:/*,mb:*,ex:*/,://,b:#,:%,:XCOMM,n:>,fb:-", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"commentstring", "cms", P_STRING|P_ALLOCED|P_VI_DEF|P_CURSWANT, #ifdef FEAT_FOLDING (char_u *)&p_cms, PV_CMS, {(char_u *)"/*%s*/", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, /* P_PRI_MKRC isn't needed here, optval_default() * always returns TRUE for 'compatible' */ {"compatible", "cp", P_BOOL|P_RALL, (char_u *)&p_cp, PV_NONE, {(char_u *)TRUE, (char_u *)FALSE} SCRIPTID_INIT}, {"complete", "cpt", P_STRING|P_ALLOCED|P_VI_DEF|P_COMMA|P_NODUP, #ifdef FEAT_INS_EXPAND (char_u *)&p_cpt, PV_CPT, {(char_u *)".,w,b,u,t,i", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"concealcursor","cocu", P_STRING|P_ALLOCED|P_RWIN|P_VI_DEF, #ifdef FEAT_CONCEAL (char_u *)VAR_WIN, PV_COCU, {(char_u *)"", (char_u *)NULL} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"conceallevel","cole", P_NUM|P_RWIN|P_VI_DEF, #ifdef FEAT_CONCEAL (char_u *)VAR_WIN, PV_COLE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"completefunc", "cfu", P_STRING|P_ALLOCED|P_VI_DEF|P_SECURE, #ifdef FEAT_COMPL_FUNC (char_u *)&p_cfu, PV_CFU, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"completeopt", "cot", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, #ifdef FEAT_INS_EXPAND (char_u *)&p_cot, PV_NONE, {(char_u *)"menu,preview", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"confirm", "cf", P_BOOL|P_VI_DEF, #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) (char_u *)&p_confirm, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"conskey", "consk",P_BOOL|P_VI_DEF, #ifdef MSDOS (char_u *)&p_consk, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"copyindent", "ci", P_BOOL|P_VI_DEF|P_VIM, (char_u *)&p_ci, PV_CI, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"cpoptions", "cpo", P_STRING|P_VIM|P_RALL|P_FLAGLIST, (char_u *)&p_cpo, PV_NONE, {(char_u *)CPO_VI, (char_u *)CPO_VIM} SCRIPTID_INIT}, {"cryptmethod", "cm", P_STRING|P_ALLOCED|P_VI_DEF, #ifdef FEAT_CRYPT (char_u *)&p_cm, PV_CM, {(char_u *)"zip", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"cscopepathcomp", "cspc", P_NUM|P_VI_DEF|P_VIM, #ifdef FEAT_CSCOPE (char_u *)&p_cspc, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"cscopeprg", "csprg", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE, #ifdef FEAT_CSCOPE (char_u *)&p_csprg, PV_NONE, {(char_u *)"cscope", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"cscopequickfix", "csqf", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, #if defined(FEAT_CSCOPE) && defined(FEAT_QUICKFIX) (char_u *)&p_csqf, PV_NONE, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"cscoperelative", "csre", P_BOOL|P_VI_DEF|P_VIM, #ifdef FEAT_CSCOPE (char_u *)&p_csre, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"cscopetag", "cst", P_BOOL|P_VI_DEF|P_VIM, #ifdef FEAT_CSCOPE (char_u *)&p_cst, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"cscopetagorder", "csto", P_NUM|P_VI_DEF|P_VIM, #ifdef FEAT_CSCOPE (char_u *)&p_csto, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"cscopeverbose", "csverb", P_BOOL|P_VI_DEF|P_VIM, #ifdef FEAT_CSCOPE (char_u *)&p_csverbose, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"cursorbind", "crb", P_BOOL|P_VI_DEF, #ifdef FEAT_CURSORBIND (char_u *)VAR_WIN, PV_CRBIND, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"cursorcolumn", "cuc", P_BOOL|P_VI_DEF|P_RWIN, #ifdef FEAT_SYN_HL (char_u *)VAR_WIN, PV_CUC, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"cursorline", "cul", P_BOOL|P_VI_DEF|P_RWIN, #ifdef FEAT_SYN_HL (char_u *)VAR_WIN, PV_CUL, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"debug", NULL, P_STRING|P_VI_DEF, (char_u *)&p_debug, PV_NONE, {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"define", "def", P_STRING|P_ALLOCED|P_VI_DEF|P_CURSWANT, #ifdef FEAT_FIND_ID (char_u *)&p_def, PV_DEF, {(char_u *)"^\\s*#\\s*define", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"delcombine", "deco", P_BOOL|P_VI_DEF|P_VIM, #ifdef FEAT_MBYTE (char_u *)&p_deco, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"dictionary", "dict", P_STRING|P_EXPAND|P_VI_DEF|P_COMMA|P_NODUP, #ifdef FEAT_INS_EXPAND (char_u *)&p_dict, PV_DICT, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"diff", NULL, P_BOOL|P_VI_DEF|P_RWIN|P_NOGLOB, #ifdef FEAT_DIFF (char_u *)VAR_WIN, PV_DIFF, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"diffexpr", "dex", P_STRING|P_VI_DEF|P_SECURE|P_CURSWANT, #if defined(FEAT_DIFF) && defined(FEAT_EVAL) (char_u *)&p_dex, PV_NONE, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"diffopt", "dip", P_STRING|P_ALLOCED|P_VI_DEF|P_RWIN|P_COMMA|P_NODUP, #ifdef FEAT_DIFF (char_u *)&p_dip, PV_NONE, {(char_u *)"filler", (char_u *)NULL} #else (char_u *)NULL, PV_NONE, {(char_u *)"", (char_u *)NULL} #endif SCRIPTID_INIT}, {"digraph", "dg", P_BOOL|P_VI_DEF|P_VIM, #ifdef FEAT_DIGRAPHS (char_u *)&p_dg, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"directory", "dir", P_STRING|P_EXPAND|P_VI_DEF|P_COMMA|P_NODUP|P_SECURE, (char_u *)&p_dir, PV_NONE, {(char_u *)DFLT_DIR, (char_u *)0L} SCRIPTID_INIT}, {"display", "dy", P_STRING|P_VI_DEF|P_COMMA|P_RALL|P_NODUP, (char_u *)&p_dy, PV_NONE, {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"eadirection", "ead", P_STRING|P_VI_DEF, #ifdef FEAT_VERTSPLIT (char_u *)&p_ead, PV_NONE, {(char_u *)"both", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"edcompatible","ed", P_BOOL|P_VI_DEF, (char_u *)&p_ed, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"encoding", "enc", P_STRING|P_VI_DEF|P_RCLR|P_NO_ML, #ifdef FEAT_MBYTE (char_u *)&p_enc, PV_NONE, {(char_u *)ENC_DFLT, (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"endofline", "eol", P_BOOL|P_NO_MKRC|P_VI_DEF|P_RSTAT, (char_u *)&p_eol, PV_EOL, {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, {"equalalways", "ea", P_BOOL|P_VI_DEF|P_RALL, (char_u *)&p_ea, PV_NONE, {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, {"equalprg", "ep", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE, (char_u *)&p_ep, PV_EP, {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"errorbells", "eb", P_BOOL|P_VI_DEF, (char_u *)&p_eb, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"errorfile", "ef", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE, #ifdef FEAT_QUICKFIX (char_u *)&p_ef, PV_NONE, {(char_u *)DFLT_ERRORFILE, (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"errorformat", "efm", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, #ifdef FEAT_QUICKFIX (char_u *)&p_efm, PV_EFM, {(char_u *)DFLT_EFM, (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"esckeys", "ek", P_BOOL|P_VIM, (char_u *)&p_ek, PV_NONE, {(char_u *)FALSE, (char_u *)TRUE} SCRIPTID_INIT}, {"eventignore", "ei", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, #ifdef FEAT_AUTOCMD (char_u *)&p_ei, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"expandtab", "et", P_BOOL|P_VI_DEF|P_VIM, (char_u *)&p_et, PV_ET, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"exrc", "ex", P_BOOL|P_VI_DEF|P_SECURE, (char_u *)&p_exrc, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"fileencoding","fenc", P_STRING|P_ALLOCED|P_VI_DEF|P_RSTAT|P_RBUF|P_NO_MKRC, #ifdef FEAT_MBYTE (char_u *)&p_fenc, PV_FENC, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"fileencodings","fencs", P_STRING|P_VI_DEF|P_COMMA, #ifdef FEAT_MBYTE (char_u *)&p_fencs, PV_NONE, {(char_u *)"ucs-bom", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"fileformat", "ff", P_STRING|P_ALLOCED|P_VI_DEF|P_RSTAT|P_NO_MKRC|P_CURSWANT, (char_u *)&p_ff, PV_FF, {(char_u *)DFLT_FF, (char_u *)0L} SCRIPTID_INIT}, {"fileformats", "ffs", P_STRING|P_VIM|P_COMMA|P_NODUP, (char_u *)&p_ffs, PV_NONE, {(char_u *)DFLT_FFS_VI, (char_u *)DFLT_FFS_VIM} SCRIPTID_INIT}, {"filetype", "ft", P_STRING|P_ALLOCED|P_VI_DEF|P_NOGLOB|P_NFNAME, #ifdef FEAT_AUTOCMD (char_u *)&p_ft, PV_FT, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"fillchars", "fcs", P_STRING|P_VI_DEF|P_RALL|P_COMMA|P_NODUP, #if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING) (char_u *)&p_fcs, PV_NONE, {(char_u *)"vert:|,fold:-", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)"", (char_u *)0L} #endif SCRIPTID_INIT}, {"fkmap", "fk", P_BOOL|P_VI_DEF, #ifdef FEAT_FKMAP (char_u *)&p_fkmap, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"flash", "fl", P_BOOL|P_VI_DEF, (char_u *)NULL, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, #ifdef FEAT_FOLDING {"foldclose", "fcl", P_STRING|P_VI_DEF|P_COMMA|P_NODUP|P_RWIN, (char_u *)&p_fcl, PV_NONE, {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"foldcolumn", "fdc", P_NUM|P_VI_DEF|P_RWIN, (char_u *)VAR_WIN, PV_FDC, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"foldenable", "fen", P_BOOL|P_VI_DEF|P_RWIN, (char_u *)VAR_WIN, PV_FEN, {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, {"foldexpr", "fde", P_STRING|P_ALLOCED|P_VIM|P_VI_DEF|P_RWIN, # ifdef FEAT_EVAL (char_u *)VAR_WIN, PV_FDE, {(char_u *)"0", (char_u *)NULL} # else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} # endif SCRIPTID_INIT}, {"foldignore", "fdi", P_STRING|P_ALLOCED|P_VIM|P_VI_DEF|P_RWIN, (char_u *)VAR_WIN, PV_FDI, {(char_u *)"#", (char_u *)NULL} SCRIPTID_INIT}, {"foldlevel", "fdl", P_NUM|P_VI_DEF|P_RWIN, (char_u *)VAR_WIN, PV_FDL, {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"foldlevelstart","fdls", P_NUM|P_VI_DEF|P_CURSWANT, (char_u *)&p_fdls, PV_NONE, {(char_u *)-1L, (char_u *)0L} SCRIPTID_INIT}, {"foldmarker", "fmr", P_STRING|P_ALLOCED|P_VIM|P_VI_DEF| P_RWIN|P_COMMA|P_NODUP, (char_u *)VAR_WIN, PV_FMR, {(char_u *)"{{{,}}}", (char_u *)NULL} SCRIPTID_INIT}, {"foldmethod", "fdm", P_STRING|P_ALLOCED|P_VIM|P_VI_DEF|P_RWIN, (char_u *)VAR_WIN, PV_FDM, {(char_u *)"manual", (char_u *)NULL} SCRIPTID_INIT}, {"foldminlines","fml", P_NUM|P_VI_DEF|P_RWIN, (char_u *)VAR_WIN, PV_FML, {(char_u *)1L, (char_u *)0L} SCRIPTID_INIT}, {"foldnestmax", "fdn", P_NUM|P_VI_DEF|P_RWIN, (char_u *)VAR_WIN, PV_FDN, {(char_u *)20L, (char_u *)0L} SCRIPTID_INIT}, {"foldopen", "fdo", P_STRING|P_VI_DEF|P_COMMA|P_NODUP|P_CURSWANT, (char_u *)&p_fdo, PV_NONE, {(char_u *)"block,hor,mark,percent,quickfix,search,tag,undo", (char_u *)0L} SCRIPTID_INIT}, {"foldtext", "fdt", P_STRING|P_ALLOCED|P_VIM|P_VI_DEF|P_RWIN, # ifdef FEAT_EVAL (char_u *)VAR_WIN, PV_FDT, {(char_u *)"foldtext()", (char_u *)NULL} # else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} # endif SCRIPTID_INIT}, #endif {"formatexpr", "fex", P_STRING|P_ALLOCED|P_VI_DEF|P_VIM, #ifdef FEAT_EVAL (char_u *)&p_fex, PV_FEX, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"formatoptions","fo", P_STRING|P_ALLOCED|P_VIM|P_FLAGLIST, (char_u *)&p_fo, PV_FO, {(char_u *)DFLT_FO_VI, (char_u *)DFLT_FO_VIM} SCRIPTID_INIT}, {"formatlistpat","flp", P_STRING|P_ALLOCED|P_VI_DEF, (char_u *)&p_flp, PV_FLP, {(char_u *)"^\\s*\\d\\+[\\]:.)}\\t ]\\s*", (char_u *)0L} SCRIPTID_INIT}, {"formatprg", "fp", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE, (char_u *)&p_fp, PV_NONE, {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"fsync", "fs", P_BOOL|P_SECURE|P_VI_DEF, #ifdef HAVE_FSYNC (char_u *)&p_fs, PV_NONE, {(char_u *)TRUE, (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)FALSE, (char_u *)0L} #endif SCRIPTID_INIT}, {"gdefault", "gd", P_BOOL|P_VI_DEF|P_VIM, (char_u *)&p_gd, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"graphic", "gr", P_BOOL|P_VI_DEF, (char_u *)NULL, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"grepformat", "gfm", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, #ifdef FEAT_QUICKFIX (char_u *)&p_gefm, PV_NONE, {(char_u *)DFLT_GREPFORMAT, (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"grepprg", "gp", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE, #ifdef FEAT_QUICKFIX (char_u *)&p_gp, PV_GP, { # ifdef WIN3264 /* may be changed to "grep -n" in os_win32.c */ (char_u *)"findstr /n", # else # ifdef UNIX /* Add an extra file name so that grep will always * insert a file name in the match line. */ (char_u *)"grep -n $* /dev/null", # else # ifdef VMS (char_u *)"SEARCH/NUMBERS ", # else (char_u *)"grep -n ", # endif # endif # endif (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"guicursor", "gcr", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, #ifdef CURSOR_SHAPE (char_u *)&p_guicursor, PV_NONE, { # ifdef FEAT_GUI (char_u *)"n-v-c:block-Cursor/lCursor,ve:ver35-Cursor,o:hor50-Cursor,i-ci:ver25-Cursor/lCursor,r-cr:hor20-Cursor/lCursor,sm:block-Cursor-blinkwait175-blinkoff150-blinkon175", # else /* MSDOS or Win32 console */ (char_u *)"n-v-c:block,o:hor50,i-ci:hor15,r-cr:hor30,sm:block", # endif (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"guifont", "gfn", P_STRING|P_VI_DEF|P_RCLR|P_COMMA|P_NODUP, #ifdef FEAT_GUI (char_u *)&p_guifont, PV_NONE, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"guifontset", "gfs", P_STRING|P_VI_DEF|P_RCLR|P_COMMA, #if defined(FEAT_GUI) && defined(FEAT_XFONTSET) (char_u *)&p_guifontset, PV_NONE, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"guifontwide", "gfw", P_STRING|P_VI_DEF|P_RCLR|P_COMMA|P_NODUP, #if defined(FEAT_GUI) && defined(FEAT_MBYTE) (char_u *)&p_guifontwide, PV_NONE, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"guiheadroom", "ghr", P_NUM|P_VI_DEF, #if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_X11) (char_u *)&p_ghr, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)50L, (char_u *)0L} SCRIPTID_INIT}, {"guioptions", "go", P_STRING|P_VI_DEF|P_RALL|P_FLAGLIST, #if defined(FEAT_GUI) (char_u *)&p_go, PV_NONE, # if defined(UNIX) && !defined(MACOS) {(char_u *)"aegimrLtT", (char_u *)0L} # else {(char_u *)"egmrLtT", (char_u *)0L} # endif #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"guipty", NULL, P_BOOL|P_VI_DEF, #if defined(FEAT_GUI) (char_u *)&p_guipty, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, {"guitablabel", "gtl", P_STRING|P_VI_DEF|P_RWIN, #if defined(FEAT_GUI_TABLINE) (char_u *)&p_gtl, PV_NONE, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"guitabtooltip", "gtt", P_STRING|P_VI_DEF|P_RWIN, #if defined(FEAT_GUI_TABLINE) (char_u *)&p_gtt, PV_NONE, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"hardtabs", "ht", P_NUM|P_VI_DEF, (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"helpfile", "hf", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE, (char_u *)&p_hf, PV_NONE, {(char_u *)DFLT_HELPFILE, (char_u *)0L} SCRIPTID_INIT}, {"helpheight", "hh", P_NUM|P_VI_DEF, #ifdef FEAT_WINDOWS (char_u *)&p_hh, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)20L, (char_u *)0L} SCRIPTID_INIT}, {"helplang", "hlg", P_STRING|P_VI_DEF|P_COMMA, #ifdef FEAT_MULTI_LANG (char_u *)&p_hlg, PV_NONE, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"hidden", "hid", P_BOOL|P_VI_DEF, (char_u *)&p_hid, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"highlight", "hl", P_STRING|P_VI_DEF|P_RCLR|P_COMMA|P_NODUP, (char_u *)&p_hl, PV_NONE, {(char_u *)HIGHLIGHT_INIT, (char_u *)0L} SCRIPTID_INIT}, {"history", "hi", P_NUM|P_VIM, (char_u *)&p_hi, PV_NONE, {(char_u *)0L, (char_u *)20L} SCRIPTID_INIT}, {"hkmap", "hk", P_BOOL|P_VI_DEF|P_VIM, #ifdef FEAT_RIGHTLEFT (char_u *)&p_hkmap, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"hkmapp", "hkp", P_BOOL|P_VI_DEF|P_VIM, #ifdef FEAT_RIGHTLEFT (char_u *)&p_hkmapp, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"hlsearch", "hls", P_BOOL|P_VI_DEF|P_VIM|P_RALL, (char_u *)&p_hls, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"icon", NULL, P_BOOL|P_VI_DEF, #ifdef FEAT_TITLE (char_u *)&p_icon, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"iconstring", NULL, P_STRING|P_VI_DEF, #ifdef FEAT_TITLE (char_u *)&p_iconstring, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"ignorecase", "ic", P_BOOL|P_VI_DEF, (char_u *)&p_ic, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"imactivatekey","imak",P_STRING|P_VI_DEF, #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK) (char_u *)&p_imak, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"imcmdline", "imc", P_BOOL|P_VI_DEF, #ifdef USE_IM_CONTROL (char_u *)&p_imcmdline, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"imdisable", "imd", P_BOOL|P_VI_DEF, #ifdef USE_IM_CONTROL (char_u *)&p_imdisable, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif #ifdef __sgi {(char_u *)TRUE, (char_u *)0L} #else {(char_u *)FALSE, (char_u *)0L} #endif SCRIPTID_INIT}, {"iminsert", "imi", P_NUM|P_VI_DEF, (char_u *)&p_iminsert, PV_IMI, #ifdef B_IMODE_IM {(char_u *)B_IMODE_IM, (char_u *)0L} #else {(char_u *)B_IMODE_NONE, (char_u *)0L} #endif SCRIPTID_INIT}, {"imsearch", "ims", P_NUM|P_VI_DEF, (char_u *)&p_imsearch, PV_IMS, #ifdef B_IMODE_IM {(char_u *)B_IMODE_IM, (char_u *)0L} #else {(char_u *)B_IMODE_NONE, (char_u *)0L} #endif SCRIPTID_INIT}, {"include", "inc", P_STRING|P_ALLOCED|P_VI_DEF, #ifdef FEAT_FIND_ID (char_u *)&p_inc, PV_INC, {(char_u *)"^\\s*#\\s*include", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"includeexpr", "inex", P_STRING|P_ALLOCED|P_VI_DEF, #if defined(FEAT_FIND_ID) && defined(FEAT_EVAL) (char_u *)&p_inex, PV_INEX, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"incsearch", "is", P_BOOL|P_VI_DEF|P_VIM, (char_u *)&p_is, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"indentexpr", "inde", P_STRING|P_ALLOCED|P_VI_DEF|P_VIM, #if defined(FEAT_CINDENT) && defined(FEAT_EVAL) (char_u *)&p_inde, PV_INDE, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"indentkeys", "indk", P_STRING|P_ALLOCED|P_VI_DEF|P_COMMA|P_NODUP, #if defined(FEAT_CINDENT) && defined(FEAT_EVAL) (char_u *)&p_indk, PV_INDK, {(char_u *)"0{,0},:,0#,!^F,o,O,e", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"infercase", "inf", P_BOOL|P_VI_DEF, (char_u *)&p_inf, PV_INF, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"insertmode", "im", P_BOOL|P_VI_DEF|P_VIM, (char_u *)&p_im, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"isfname", "isf", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, (char_u *)&p_isf, PV_NONE, { #ifdef BACKSLASH_IN_FILENAME /* Excluded are: & and ^ are special in cmd.exe * ( and ) are used in text separating fnames */ (char_u *)"@,48-57,/,\\,.,-,_,+,,,#,$,%,{,},[,],:,@-@,!,~,=", #else # ifdef AMIGA (char_u *)"@,48-57,/,.,-,_,+,,,$,:", # else # ifdef VMS (char_u *)"@,48-57,/,.,-,_,+,,,#,$,%,<,>,[,],:,;,~", # else /* UNIX et al. */ # ifdef EBCDIC (char_u *)"@,240-249,/,.,-,_,+,,,#,$,%,~,=", # else (char_u *)"@,48-57,/,.,-,_,+,,,#,$,%,~,=", # endif # endif # endif #endif (char_u *)0L} SCRIPTID_INIT}, {"isident", "isi", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, (char_u *)&p_isi, PV_NONE, { #if defined(MSDOS) || defined(MSWIN) || defined(OS2) (char_u *)"@,48-57,_,128-167,224-235", #else # ifdef EBCDIC /* TODO: EBCDIC Check this! @ == isalpha()*/ (char_u *)"@,240-249,_,66-73,81-89,98-105," "112-120,128,140-142,156,158,172," "174,186,191,203-207,219-225,235-239," "251-254", # else (char_u *)"@,48-57,_,192-255", # endif #endif (char_u *)0L} SCRIPTID_INIT}, {"iskeyword", "isk", P_STRING|P_ALLOCED|P_VIM|P_COMMA|P_NODUP, (char_u *)&p_isk, PV_ISK, { #ifdef EBCDIC (char_u *)"@,240-249,_", /* TODO: EBCDIC Check this! @ == isalpha()*/ (char_u *)"@,240-249,_,66-73,81-89,98-105," "112-120,128,140-142,156,158,172," "174,186,191,203-207,219-225,235-239," "251-254", #else (char_u *)"@,48-57,_", # if defined(MSDOS) || defined(MSWIN) || defined(OS2) (char_u *)"@,48-57,_,128-167,224-235" # else ISK_LATIN1 # endif #endif } SCRIPTID_INIT}, {"isprint", "isp", P_STRING|P_VI_DEF|P_RALL|P_COMMA|P_NODUP, (char_u *)&p_isp, PV_NONE, { #if defined(MSDOS) || defined(MSWIN) || defined(OS2) \ || (defined(MACOS) && !defined(MACOS_X)) \ || defined(VMS) (char_u *)"@,~-255", #else # ifdef EBCDIC /* all chars above 63 are printable */ (char_u *)"63-255", # else ISP_LATIN1, # endif #endif (char_u *)0L} SCRIPTID_INIT}, {"joinspaces", "js", P_BOOL|P_VI_DEF|P_VIM, (char_u *)&p_js, PV_NONE, {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, {"key", NULL, P_STRING|P_ALLOCED|P_VI_DEF|P_NO_MKRC, #ifdef FEAT_CRYPT (char_u *)&p_key, PV_KEY, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"keymap", "kmp", P_STRING|P_ALLOCED|P_VI_DEF|P_RBUF|P_RSTAT|P_NFNAME|P_PRI_MKRC, #ifdef FEAT_KEYMAP (char_u *)&p_keymap, PV_KMAP, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)"", (char_u *)0L} #endif SCRIPTID_INIT}, {"keymodel", "km", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, #ifdef FEAT_VISUAL (char_u *)&p_km, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"keywordprg", "kp", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE, (char_u *)&p_kp, PV_KP, { #if defined(MSDOS) || defined(MSWIN) (char_u *)":help", #else #ifdef VMS (char_u *)"help", #else # if defined(OS2) (char_u *)"view /", # else # ifdef USEMAN_S (char_u *)"man -s", # else (char_u *)"man", # endif # endif #endif #endif (char_u *)0L} SCRIPTID_INIT}, {"langmap", "lmap", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, #ifdef FEAT_LANGMAP (char_u *)&p_langmap, PV_NONE, {(char_u *)"", /* unmatched } */ #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, #endif (char_u *)0L} SCRIPTID_INIT}, {"langmenu", "lm", P_STRING|P_VI_DEF|P_NFNAME, #if defined(FEAT_MENU) && defined(FEAT_MULTI_LANG) (char_u *)&p_lm, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"laststatus", "ls", P_NUM|P_VI_DEF|P_RALL, #ifdef FEAT_WINDOWS (char_u *)&p_ls, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)1L, (char_u *)0L} SCRIPTID_INIT}, {"lazyredraw", "lz", P_BOOL|P_VI_DEF, (char_u *)&p_lz, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"linebreak", "lbr", P_BOOL|P_VI_DEF|P_RWIN, #ifdef FEAT_LINEBREAK (char_u *)VAR_WIN, PV_LBR, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"lines", NULL, P_NUM|P_NODEFAULT|P_NO_MKRC|P_VI_DEF|P_RCLR, (char_u *)&Rows, PV_NONE, { #if defined(MSDOS) || defined(WIN3264) || defined(OS2) (char_u *)25L, #else (char_u *)24L, #endif (char_u *)0L} SCRIPTID_INIT}, {"linespace", "lsp", P_NUM|P_VI_DEF|P_RCLR, #ifdef FEAT_GUI (char_u *)&p_linespace, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif #ifdef FEAT_GUI_W32 {(char_u *)1L, (char_u *)0L} #else {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"lisp", NULL, P_BOOL|P_VI_DEF, #ifdef FEAT_LISP (char_u *)&p_lisp, PV_LISP, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"lispwords", "lw", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, #ifdef FEAT_LISP (char_u *)&p_lispwords, PV_NONE, {(char_u *)LISPWORD_VALUE, (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)"", (char_u *)0L} #endif SCRIPTID_INIT}, {"list", NULL, P_BOOL|P_VI_DEF|P_RWIN, (char_u *)VAR_WIN, PV_LIST, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"listchars", "lcs", P_STRING|P_VI_DEF|P_RALL|P_COMMA|P_NODUP, (char_u *)&p_lcs, PV_NONE, {(char_u *)"eol:$", (char_u *)0L} SCRIPTID_INIT}, {"loadplugins", "lpl", P_BOOL|P_VI_DEF, (char_u *)&p_lpl, PV_NONE, {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, #ifdef FEAT_GUI_MAC {"macatsui", NULL, P_BOOL|P_VI_DEF|P_RCLR, (char_u *)&p_macatsui, PV_NONE, {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, #endif {"magic", NULL, P_BOOL|P_VI_DEF, (char_u *)&p_magic, PV_NONE, {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, {"makeef", "mef", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE, #ifdef FEAT_QUICKFIX (char_u *)&p_mef, PV_NONE, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"makeprg", "mp", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE, #ifdef FEAT_QUICKFIX (char_u *)&p_mp, PV_MP, # ifdef VMS {(char_u *)"MMS", (char_u *)0L} # else {(char_u *)"make", (char_u *)0L} # endif #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"matchpairs", "mps", P_STRING|P_ALLOCED|P_VI_DEF|P_COMMA|P_NODUP, (char_u *)&p_mps, PV_MPS, {(char_u *)"(:),{:},[:]", (char_u *)0L} SCRIPTID_INIT}, {"matchtime", "mat", P_NUM|P_VI_DEF, (char_u *)&p_mat, PV_NONE, {(char_u *)5L, (char_u *)0L} SCRIPTID_INIT}, {"maxcombine", "mco", P_NUM|P_VI_DEF|P_CURSWANT, #ifdef FEAT_MBYTE (char_u *)&p_mco, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)2, (char_u *)0L} SCRIPTID_INIT}, {"maxfuncdepth", "mfd", P_NUM|P_VI_DEF, #ifdef FEAT_EVAL (char_u *)&p_mfd, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)100L, (char_u *)0L} SCRIPTID_INIT}, {"maxmapdepth", "mmd", P_NUM|P_VI_DEF, (char_u *)&p_mmd, PV_NONE, {(char_u *)1000L, (char_u *)0L} SCRIPTID_INIT}, {"maxmem", "mm", P_NUM|P_VI_DEF, (char_u *)&p_mm, PV_NONE, {(char_u *)DFLT_MAXMEM, (char_u *)0L} SCRIPTID_INIT}, {"maxmempattern","mmp", P_NUM|P_VI_DEF, (char_u *)&p_mmp, PV_NONE, {(char_u *)1000L, (char_u *)0L} SCRIPTID_INIT}, {"maxmemtot", "mmt", P_NUM|P_VI_DEF, (char_u *)&p_mmt, PV_NONE, {(char_u *)DFLT_MAXMEMTOT, (char_u *)0L} SCRIPTID_INIT}, {"menuitems", "mis", P_NUM|P_VI_DEF, #ifdef FEAT_MENU (char_u *)&p_mis, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)25L, (char_u *)0L} SCRIPTID_INIT}, {"mesg", NULL, P_BOOL|P_VI_DEF, (char_u *)NULL, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"mkspellmem", "msm", P_STRING|P_VI_DEF|P_EXPAND|P_SECURE, #ifdef FEAT_SPELL (char_u *)&p_msm, PV_NONE, {(char_u *)"460000,2000,500", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"modeline", "ml", P_BOOL|P_VIM, (char_u *)&p_ml, PV_ML, {(char_u *)FALSE, (char_u *)TRUE} SCRIPTID_INIT}, {"modelines", "mls", P_NUM|P_VI_DEF, (char_u *)&p_mls, PV_NONE, {(char_u *)5L, (char_u *)0L} SCRIPTID_INIT}, {"modifiable", "ma", P_BOOL|P_VI_DEF|P_NOGLOB, (char_u *)&p_ma, PV_MA, {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, {"modified", "mod", P_BOOL|P_NO_MKRC|P_VI_DEF|P_RSTAT, (char_u *)&p_mod, PV_MOD, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"more", NULL, P_BOOL|P_VIM, (char_u *)&p_more, PV_NONE, {(char_u *)FALSE, (char_u *)TRUE} SCRIPTID_INIT}, {"mouse", NULL, P_STRING|P_VI_DEF|P_FLAGLIST, (char_u *)&p_mouse, PV_NONE, { #if defined(MSDOS) || defined(WIN3264) (char_u *)"a", #else (char_u *)"", #endif (char_u *)0L} SCRIPTID_INIT}, {"mousefocus", "mousef", P_BOOL|P_VI_DEF, #ifdef FEAT_GUI (char_u *)&p_mousef, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"mousehide", "mh", P_BOOL|P_VI_DEF, #ifdef FEAT_GUI (char_u *)&p_mh, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, {"mousemodel", "mousem", P_STRING|P_VI_DEF, (char_u *)&p_mousem, PV_NONE, { #if defined(MSDOS) || defined(MSWIN) (char_u *)"popup", #else # if defined(MACOS) (char_u *)"popup_setpos", # else (char_u *)"extend", # endif #endif (char_u *)0L} SCRIPTID_INIT}, {"mouseshape", "mouses", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, #ifdef FEAT_MOUSESHAPE (char_u *)&p_mouseshape, PV_NONE, {(char_u *)"i-r:beam,s:updown,sd:udsizing,vs:leftright,vd:lrsizing,m:no,ml:up-arrow,v:rightup-arrow", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"mousetime", "mouset", P_NUM|P_VI_DEF, (char_u *)&p_mouset, PV_NONE, {(char_u *)500L, (char_u *)0L} SCRIPTID_INIT}, {"mzquantum", "mzq", P_NUM, #ifdef FEAT_MZSCHEME (char_u *)&p_mzq, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)100L, (char_u *)100L} SCRIPTID_INIT}, {"novice", NULL, P_BOOL|P_VI_DEF, (char_u *)NULL, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"nrformats", "nf", P_STRING|P_ALLOCED|P_VI_DEF|P_COMMA|P_NODUP, (char_u *)&p_nf, PV_NF, {(char_u *)"octal,hex", (char_u *)0L} SCRIPTID_INIT}, {"number", "nu", P_BOOL|P_VI_DEF|P_RWIN, (char_u *)VAR_WIN, PV_NU, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"numberwidth", "nuw", P_NUM|P_RWIN|P_VIM, #ifdef FEAT_LINEBREAK (char_u *)VAR_WIN, PV_NUW, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)8L, (char_u *)4L} SCRIPTID_INIT}, {"omnifunc", "ofu", P_STRING|P_ALLOCED|P_VI_DEF|P_SECURE, #ifdef FEAT_COMPL_FUNC (char_u *)&p_ofu, PV_OFU, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"open", NULL, P_BOOL|P_VI_DEF, (char_u *)NULL, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"opendevice", "odev", P_BOOL|P_VI_DEF, #if defined(MSDOS) || defined(MSWIN) || defined(OS2) (char_u *)&p_odev, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)FALSE} SCRIPTID_INIT}, {"operatorfunc", "opfunc", P_STRING|P_VI_DEF|P_SECURE, (char_u *)&p_opfunc, PV_NONE, {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"optimize", "opt", P_BOOL|P_VI_DEF, (char_u *)NULL, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"osfiletype", "oft", P_STRING|P_ALLOCED|P_VI_DEF, (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"paragraphs", "para", P_STRING|P_VI_DEF, (char_u *)&p_para, PV_NONE, {(char_u *)"IPLPPPQPP TPHPLIPpLpItpplpipbp", (char_u *)0L} SCRIPTID_INIT}, {"paste", NULL, P_BOOL|P_VI_DEF|P_PRI_MKRC, (char_u *)&p_paste, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"pastetoggle", "pt", P_STRING|P_VI_DEF, (char_u *)&p_pt, PV_NONE, {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"patchexpr", "pex", P_STRING|P_VI_DEF|P_SECURE, #if defined(FEAT_DIFF) && defined(FEAT_EVAL) (char_u *)&p_pex, PV_NONE, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"patchmode", "pm", P_STRING|P_VI_DEF|P_NFNAME, (char_u *)&p_pm, PV_NONE, {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"path", "pa", P_STRING|P_EXPAND|P_VI_DEF|P_COMMA|P_NODUP, (char_u *)&p_path, PV_PATH, { #if defined AMIGA || defined MSDOS || defined MSWIN (char_u *)".,,", #else # if defined(__EMX__) (char_u *)".,/emx/include,,", # else /* Unix, probably */ (char_u *)".,/usr/include,,", # endif #endif (char_u *)0L} SCRIPTID_INIT}, {"preserveindent", "pi", P_BOOL|P_VI_DEF|P_VIM, (char_u *)&p_pi, PV_PI, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"previewheight", "pvh", P_NUM|P_VI_DEF, #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX) (char_u *)&p_pvh, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)12L, (char_u *)0L} SCRIPTID_INIT}, {"previewwindow", "pvw", P_BOOL|P_VI_DEF|P_RSTAT|P_NOGLOB, #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX) (char_u *)VAR_WIN, PV_PVW, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"printdevice", "pdev", P_STRING|P_VI_DEF|P_SECURE, #ifdef FEAT_PRINTER (char_u *)&p_pdev, PV_NONE, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"printencoding", "penc", P_STRING|P_VI_DEF, #ifdef FEAT_POSTSCRIPT (char_u *)&p_penc, PV_NONE, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"printexpr", "pexpr", P_STRING|P_VI_DEF, #ifdef FEAT_POSTSCRIPT (char_u *)&p_pexpr, PV_NONE, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"printfont", "pfn", P_STRING|P_VI_DEF, #ifdef FEAT_PRINTER (char_u *)&p_pfn, PV_NONE, { # ifdef MSWIN (char_u *)"Courier_New:h10", # else (char_u *)"courier", # endif (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"printheader", "pheader", P_STRING|P_VI_DEF|P_GETTEXT, #ifdef FEAT_PRINTER (char_u *)&p_header, PV_NONE, {(char_u *)N_("%<%f%h%m%=Page %N"), (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"printmbcharset", "pmbcs", P_STRING|P_VI_DEF, #if defined(FEAT_POSTSCRIPT) && defined(FEAT_MBYTE) (char_u *)&p_pmcs, PV_NONE, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"printmbfont", "pmbfn", P_STRING|P_VI_DEF, #if defined(FEAT_POSTSCRIPT) && defined(FEAT_MBYTE) (char_u *)&p_pmfn, PV_NONE, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"printoptions", "popt", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, #ifdef FEAT_PRINTER (char_u *)&p_popt, PV_NONE, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"prompt", NULL, P_BOOL|P_VI_DEF, (char_u *)&p_prompt, PV_NONE, {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, {"pumheight", "ph", P_NUM|P_VI_DEF, #ifdef FEAT_INS_EXPAND (char_u *)&p_ph, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"quoteescape", "qe", P_STRING|P_ALLOCED|P_VI_DEF, #ifdef FEAT_TEXTOBJ (char_u *)&p_qe, PV_QE, {(char_u *)"\\", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"readonly", "ro", P_BOOL|P_VI_DEF|P_RSTAT|P_NOGLOB, (char_u *)&p_ro, PV_RO, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"redraw", NULL, P_BOOL|P_VI_DEF, (char_u *)NULL, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"redrawtime", "rdt", P_NUM|P_VI_DEF, #ifdef FEAT_RELTIME (char_u *)&p_rdt, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)2000L, (char_u *)0L} SCRIPTID_INIT}, {"relativenumber", "rnu", P_BOOL|P_VI_DEF|P_RWIN, (char_u *)VAR_WIN, PV_RNU, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"remap", NULL, P_BOOL|P_VI_DEF, (char_u *)&p_remap, PV_NONE, {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, {"report", NULL, P_NUM|P_VI_DEF, (char_u *)&p_report, PV_NONE, {(char_u *)2L, (char_u *)0L} SCRIPTID_INIT}, {"restorescreen", "rs", P_BOOL|P_VI_DEF, #ifdef WIN3264 (char_u *)&p_rs, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, {"revins", "ri", P_BOOL|P_VI_DEF|P_VIM, #ifdef FEAT_RIGHTLEFT (char_u *)&p_ri, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"rightleft", "rl", P_BOOL|P_VI_DEF|P_RWIN, #ifdef FEAT_RIGHTLEFT (char_u *)VAR_WIN, PV_RL, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"rightleftcmd", "rlc", P_STRING|P_ALLOCED|P_VI_DEF|P_RWIN, #ifdef FEAT_RIGHTLEFT (char_u *)VAR_WIN, PV_RLC, {(char_u *)"search", (char_u *)NULL} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"ruler", "ru", P_BOOL|P_VI_DEF|P_VIM|P_RSTAT, #ifdef FEAT_CMDL_INFO (char_u *)&p_ru, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"rulerformat", "ruf", P_STRING|P_VI_DEF|P_ALLOCED|P_RSTAT, #ifdef FEAT_STL_OPT (char_u *)&p_ruf, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"runtimepath", "rtp", P_STRING|P_VI_DEF|P_EXPAND|P_COMMA|P_NODUP|P_SECURE, (char_u *)&p_rtp, PV_NONE, {(char_u *)DFLT_RUNTIMEPATH, (char_u *)0L} SCRIPTID_INIT}, {"scroll", "scr", P_NUM|P_NO_MKRC|P_VI_DEF, (char_u *)VAR_WIN, PV_SCROLL, {(char_u *)12L, (char_u *)0L} SCRIPTID_INIT}, {"scrollbind", "scb", P_BOOL|P_VI_DEF, #ifdef FEAT_SCROLLBIND (char_u *)VAR_WIN, PV_SCBIND, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"scrolljump", "sj", P_NUM|P_VI_DEF|P_VIM, (char_u *)&p_sj, PV_NONE, {(char_u *)1L, (char_u *)0L} SCRIPTID_INIT}, {"scrolloff", "so", P_NUM|P_VI_DEF|P_VIM|P_RALL, (char_u *)&p_so, PV_NONE, {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"scrollopt", "sbo", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, #ifdef FEAT_SCROLLBIND (char_u *)&p_sbo, PV_NONE, {(char_u *)"ver,jump", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"sections", "sect", P_STRING|P_VI_DEF, (char_u *)&p_sections, PV_NONE, {(char_u *)"SHNHH HUnhsh", (char_u *)0L} SCRIPTID_INIT}, {"secure", NULL, P_BOOL|P_VI_DEF|P_SECURE, (char_u *)&p_secure, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"selection", "sel", P_STRING|P_VI_DEF, #ifdef FEAT_VISUAL (char_u *)&p_sel, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)"inclusive", (char_u *)0L} SCRIPTID_INIT}, {"selectmode", "slm", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, #ifdef FEAT_VISUAL (char_u *)&p_slm, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"sessionoptions", "ssop", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, #ifdef FEAT_SESSION (char_u *)&p_ssop, PV_NONE, {(char_u *)"blank,buffers,curdir,folds,help,options,tabpages,winsize", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"shell", "sh", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE, (char_u *)&p_sh, PV_NONE, { #ifdef VMS (char_u *)"-", #else # if defined(MSDOS) (char_u *)"command", # else # if defined(WIN16) (char_u *)"command.com", # else # if defined(WIN3264) (char_u *)"", /* set in set_init_1() */ # else # if defined(OS2) (char_u *)"cmd.exe", # else # if defined(ARCHIE) (char_u *)"gos", # else (char_u *)"sh", # endif # endif # endif # endif # endif #endif /* VMS */ (char_u *)0L} SCRIPTID_INIT}, {"shellcmdflag","shcf", P_STRING|P_VI_DEF|P_SECURE, (char_u *)&p_shcf, PV_NONE, { #if defined(MSDOS) || defined(MSWIN) (char_u *)"/c", #else # if defined(OS2) (char_u *)"/c", # else (char_u *)"-c", # endif #endif (char_u *)0L} SCRIPTID_INIT}, {"shellpipe", "sp", P_STRING|P_VI_DEF|P_SECURE, #ifdef FEAT_QUICKFIX (char_u *)&p_sp, PV_NONE, { #if defined(UNIX) || defined(OS2) # ifdef ARCHIE (char_u *)"2>", # else (char_u *)"| tee", # endif #else (char_u *)">", #endif (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"shellquote", "shq", P_STRING|P_VI_DEF|P_SECURE, (char_u *)&p_shq, PV_NONE, {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"shellredir", "srr", P_STRING|P_VI_DEF|P_SECURE, (char_u *)&p_srr, PV_NONE, {(char_u *)">", (char_u *)0L} SCRIPTID_INIT}, {"shellslash", "ssl", P_BOOL|P_VI_DEF, #ifdef BACKSLASH_IN_FILENAME (char_u *)&p_ssl, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"shelltemp", "stmp", P_BOOL, (char_u *)&p_stmp, PV_NONE, {(char_u *)FALSE, (char_u *)TRUE} SCRIPTID_INIT}, {"shelltype", "st", P_NUM|P_VI_DEF, #ifdef AMIGA (char_u *)&p_st, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"shellxquote", "sxq", P_STRING|P_VI_DEF|P_SECURE, (char_u *)&p_sxq, PV_NONE, { #if defined(UNIX) && defined(USE_SYSTEM) && !defined(__EMX__) (char_u *)"\"", #else (char_u *)"", #endif (char_u *)0L} SCRIPTID_INIT}, {"shellxescape", "sxe", P_STRING|P_VI_DEF|P_SECURE, (char_u *)&p_sxe, PV_NONE, { #if defined(MSDOS) || defined(WIN16) || defined(WIN3264) (char_u *)"\"&|<>()@^", #else (char_u *)"", #endif (char_u *)0L} SCRIPTID_INIT}, {"shiftround", "sr", P_BOOL|P_VI_DEF|P_VIM, (char_u *)&p_sr, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"shiftwidth", "sw", P_NUM|P_VI_DEF, (char_u *)&p_sw, PV_SW, {(char_u *)8L, (char_u *)0L} SCRIPTID_INIT}, {"shortmess", "shm", P_STRING|P_VIM|P_FLAGLIST, (char_u *)&p_shm, PV_NONE, {(char_u *)"", (char_u *)"filnxtToO"} SCRIPTID_INIT}, {"shortname", "sn", P_BOOL|P_VI_DEF, #ifdef SHORT_FNAME (char_u *)NULL, PV_NONE, #else (char_u *)&p_sn, PV_SN, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"showbreak", "sbr", P_STRING|P_VI_DEF|P_RALL, #ifdef FEAT_LINEBREAK (char_u *)&p_sbr, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"showcmd", "sc", P_BOOL|P_VIM, #ifdef FEAT_CMDL_INFO (char_u *)&p_sc, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, #ifdef UNIX (char_u *)FALSE #else (char_u *)TRUE #endif } SCRIPTID_INIT}, {"showfulltag", "sft", P_BOOL|P_VI_DEF, (char_u *)&p_sft, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"showmatch", "sm", P_BOOL|P_VI_DEF, (char_u *)&p_sm, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"showmode", "smd", P_BOOL|P_VIM, (char_u *)&p_smd, PV_NONE, {(char_u *)FALSE, (char_u *)TRUE} SCRIPTID_INIT}, {"showtabline", "stal", P_NUM|P_VI_DEF|P_RALL, #ifdef FEAT_WINDOWS (char_u *)&p_stal, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)1L, (char_u *)0L} SCRIPTID_INIT}, {"sidescroll", "ss", P_NUM|P_VI_DEF, (char_u *)&p_ss, PV_NONE, {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"sidescrolloff", "siso", P_NUM|P_VI_DEF|P_VIM|P_RBUF, (char_u *)&p_siso, PV_NONE, {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"slowopen", "slow", P_BOOL|P_VI_DEF, (char_u *)NULL, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"smartcase", "scs", P_BOOL|P_VI_DEF|P_VIM, (char_u *)&p_scs, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"smartindent", "si", P_BOOL|P_VI_DEF|P_VIM, #ifdef FEAT_SMARTINDENT (char_u *)&p_si, PV_SI, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"smarttab", "sta", P_BOOL|P_VI_DEF|P_VIM, (char_u *)&p_sta, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"softtabstop", "sts", P_NUM|P_VI_DEF|P_VIM, (char_u *)&p_sts, PV_STS, {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"sourceany", NULL, P_BOOL|P_VI_DEF, (char_u *)NULL, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"spell", NULL, P_BOOL|P_VI_DEF|P_RWIN, #ifdef FEAT_SPELL (char_u *)VAR_WIN, PV_SPELL, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"spellcapcheck", "spc", P_STRING|P_ALLOCED|P_VI_DEF|P_RBUF, #ifdef FEAT_SPELL (char_u *)&p_spc, PV_SPC, {(char_u *)"[.?!]\\_[\\])'\" ]\\+", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"spellfile", "spf", P_STRING|P_EXPAND|P_ALLOCED|P_VI_DEF|P_SECURE|P_COMMA, #ifdef FEAT_SPELL (char_u *)&p_spf, PV_SPF, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"spelllang", "spl", P_STRING|P_ALLOCED|P_VI_DEF|P_COMMA|P_RBUF|P_EXPAND, #ifdef FEAT_SPELL (char_u *)&p_spl, PV_SPL, {(char_u *)"en", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"spellsuggest", "sps", P_STRING|P_VI_DEF|P_EXPAND|P_SECURE|P_COMMA, #ifdef FEAT_SPELL (char_u *)&p_sps, PV_NONE, {(char_u *)"best", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"splitbelow", "sb", P_BOOL|P_VI_DEF, #ifdef FEAT_WINDOWS (char_u *)&p_sb, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"splitright", "spr", P_BOOL|P_VI_DEF, #ifdef FEAT_VERTSPLIT (char_u *)&p_spr, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"startofline", "sol", P_BOOL|P_VI_DEF|P_VIM, (char_u *)&p_sol, PV_NONE, {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, {"statusline" ,"stl", P_STRING|P_VI_DEF|P_ALLOCED|P_RSTAT, #ifdef FEAT_STL_OPT (char_u *)&p_stl, PV_STL, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"suffixes", "su", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, (char_u *)&p_su, PV_NONE, {(char_u *)".bak,~,.o,.h,.info,.swp,.obj", (char_u *)0L} SCRIPTID_INIT}, {"suffixesadd", "sua", P_STRING|P_VI_DEF|P_ALLOCED|P_COMMA|P_NODUP, #ifdef FEAT_SEARCHPATH (char_u *)&p_sua, PV_SUA, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"swapfile", "swf", P_BOOL|P_VI_DEF|P_RSTAT, (char_u *)&p_swf, PV_SWF, {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, {"swapsync", "sws", P_STRING|P_VI_DEF, (char_u *)&p_sws, PV_NONE, {(char_u *)"fsync", (char_u *)0L} SCRIPTID_INIT}, {"switchbuf", "swb", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, (char_u *)&p_swb, PV_NONE, {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"synmaxcol", "smc", P_NUM|P_VI_DEF|P_RBUF, #ifdef FEAT_SYN_HL (char_u *)&p_smc, PV_SMC, {(char_u *)3000L, (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"syntax", "syn", P_STRING|P_ALLOCED|P_VI_DEF|P_NOGLOB|P_NFNAME, #ifdef FEAT_SYN_HL (char_u *)&p_syn, PV_SYN, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"tabline", "tal", P_STRING|P_VI_DEF|P_RALL, #ifdef FEAT_STL_OPT (char_u *)&p_tal, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"tabpagemax", "tpm", P_NUM|P_VI_DEF, #ifdef FEAT_WINDOWS (char_u *)&p_tpm, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)10L, (char_u *)0L} SCRIPTID_INIT}, {"tabstop", "ts", P_NUM|P_VI_DEF|P_RBUF, (char_u *)&p_ts, PV_TS, {(char_u *)8L, (char_u *)0L} SCRIPTID_INIT}, {"tagbsearch", "tbs", P_BOOL|P_VI_DEF, (char_u *)&p_tbs, PV_NONE, #ifdef VMS /* binary searching doesn't appear to work on VMS */ {(char_u *)0L, (char_u *)0L} #else {(char_u *)TRUE, (char_u *)0L} #endif SCRIPTID_INIT}, {"taglength", "tl", P_NUM|P_VI_DEF, (char_u *)&p_tl, PV_NONE, {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"tagrelative", "tr", P_BOOL|P_VIM, (char_u *)&p_tr, PV_NONE, {(char_u *)FALSE, (char_u *)TRUE} SCRIPTID_INIT}, {"tags", "tag", P_STRING|P_EXPAND|P_VI_DEF|P_COMMA|P_NODUP, (char_u *)&p_tags, PV_TAGS, { #if defined(FEAT_EMACS_TAGS) && !defined(CASE_INSENSITIVE_FILENAME) (char_u *)"./tags,./TAGS,tags,TAGS", #else (char_u *)"./tags,tags", #endif (char_u *)0L} SCRIPTID_INIT}, {"tagstack", "tgst", P_BOOL|P_VI_DEF, (char_u *)&p_tgst, PV_NONE, {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, {"term", NULL, P_STRING|P_EXPAND|P_NODEFAULT|P_NO_MKRC|P_VI_DEF|P_RALL, (char_u *)&T_NAME, PV_NONE, {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"termbidi", "tbidi", P_BOOL|P_VI_DEF, #ifdef FEAT_ARABIC (char_u *)&p_tbidi, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"termencoding", "tenc", P_STRING|P_VI_DEF|P_RCLR, #ifdef FEAT_MBYTE (char_u *)&p_tenc, PV_NONE, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"terse", NULL, P_BOOL|P_VI_DEF, (char_u *)&p_terse, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"textauto", "ta", P_BOOL|P_VIM, (char_u *)&p_ta, PV_NONE, {(char_u *)DFLT_TEXTAUTO, (char_u *)TRUE} SCRIPTID_INIT}, {"textmode", "tx", P_BOOL|P_VI_DEF|P_NO_MKRC, (char_u *)&p_tx, PV_TX, { #ifdef USE_CRNL (char_u *)TRUE, #else (char_u *)FALSE, #endif (char_u *)0L} SCRIPTID_INIT}, {"textwidth", "tw", P_NUM|P_VI_DEF|P_VIM|P_RBUF, (char_u *)&p_tw, PV_TW, {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"thesaurus", "tsr", P_STRING|P_EXPAND|P_VI_DEF|P_COMMA|P_NODUP, #ifdef FEAT_INS_EXPAND (char_u *)&p_tsr, PV_TSR, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"tildeop", "top", P_BOOL|P_VI_DEF|P_VIM, (char_u *)&p_to, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"timeout", "to", P_BOOL|P_VI_DEF, (char_u *)&p_timeout, PV_NONE, {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, {"timeoutlen", "tm", P_NUM|P_VI_DEF, (char_u *)&p_tm, PV_NONE, {(char_u *)1000L, (char_u *)0L} SCRIPTID_INIT}, {"title", NULL, P_BOOL|P_VI_DEF, #ifdef FEAT_TITLE (char_u *)&p_title, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"titlelen", NULL, P_NUM|P_VI_DEF, #ifdef FEAT_TITLE (char_u *)&p_titlelen, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)85L, (char_u *)0L} SCRIPTID_INIT}, {"titleold", NULL, P_STRING|P_VI_DEF|P_GETTEXT|P_SECURE|P_NO_MKRC, #ifdef FEAT_TITLE (char_u *)&p_titleold, PV_NONE, {(char_u *)N_("Thanks for flying Vim"), (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"titlestring", NULL, P_STRING|P_VI_DEF, #ifdef FEAT_TITLE (char_u *)&p_titlestring, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, #if defined(FEAT_TOOLBAR) && !defined(FEAT_GUI_W32) {"toolbar", "tb", P_STRING|P_COMMA|P_VI_DEF|P_NODUP, (char_u *)&p_toolbar, PV_NONE, {(char_u *)"icons,tooltips", (char_u *)0L} SCRIPTID_INIT}, #endif #if defined(FEAT_TOOLBAR) && defined(FEAT_GUI_GTK) {"toolbariconsize", "tbis", P_STRING|P_VI_DEF, (char_u *)&p_tbis, PV_NONE, {(char_u *)"small", (char_u *)0L} SCRIPTID_INIT}, #endif {"ttimeout", NULL, P_BOOL|P_VI_DEF|P_VIM, (char_u *)&p_ttimeout, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"ttimeoutlen", "ttm", P_NUM|P_VI_DEF, (char_u *)&p_ttm, PV_NONE, {(char_u *)-1L, (char_u *)0L} SCRIPTID_INIT}, {"ttybuiltin", "tbi", P_BOOL|P_VI_DEF, (char_u *)&p_tbi, PV_NONE, {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, {"ttyfast", "tf", P_BOOL|P_NO_MKRC|P_VI_DEF, (char_u *)&p_tf, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"ttymouse", "ttym", P_STRING|P_NODEFAULT|P_NO_MKRC|P_VI_DEF, #if defined(FEAT_MOUSE) && (defined(UNIX) || defined(VMS)) (char_u *)&p_ttym, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"ttyscroll", "tsl", P_NUM|P_VI_DEF, (char_u *)&p_ttyscroll, PV_NONE, {(char_u *)999L, (char_u *)0L} SCRIPTID_INIT}, {"ttytype", "tty", P_STRING|P_EXPAND|P_NODEFAULT|P_NO_MKRC|P_VI_DEF|P_RALL, (char_u *)&T_NAME, PV_NONE, {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"undodir", "udir", P_STRING|P_EXPAND|P_COMMA|P_NODUP|P_SECURE|P_VI_DEF, #ifdef FEAT_PERSISTENT_UNDO (char_u *)&p_udir, PV_NONE, {(char_u *)".", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"undofile", "udf", P_BOOL|P_VI_DEF|P_VIM, #ifdef FEAT_PERSISTENT_UNDO (char_u *)&p_udf, PV_UDF, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"undolevels", "ul", P_NUM|P_VI_DEF, (char_u *)&p_ul, PV_NONE, { #if defined(UNIX) || defined(WIN3264) || defined(OS2) || defined(VMS) (char_u *)1000L, #else (char_u *)100L, #endif (char_u *)0L} SCRIPTID_INIT}, {"undoreload", "ur", P_NUM|P_VI_DEF, (char_u *)&p_ur, PV_NONE, { (char_u *)10000L, (char_u *)0L} SCRIPTID_INIT}, {"updatecount", "uc", P_NUM|P_VI_DEF, (char_u *)&p_uc, PV_NONE, {(char_u *)200L, (char_u *)0L} SCRIPTID_INIT}, {"updatetime", "ut", P_NUM|P_VI_DEF, (char_u *)&p_ut, PV_NONE, {(char_u *)4000L, (char_u *)0L} SCRIPTID_INIT}, {"verbose", "vbs", P_NUM|P_VI_DEF, (char_u *)&p_verbose, PV_NONE, {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"verbosefile", "vfile", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE, (char_u *)&p_vfile, PV_NONE, {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"viewdir", "vdir", P_STRING|P_EXPAND|P_VI_DEF|P_SECURE, #ifdef FEAT_SESSION (char_u *)&p_vdir, PV_NONE, {(char_u *)DFLT_VDIR, (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"viewoptions", "vop", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, #ifdef FEAT_SESSION (char_u *)&p_vop, PV_NONE, {(char_u *)"folds,options,cursor", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"viminfo", "vi", P_STRING|P_COMMA|P_NODUP|P_SECURE, #ifdef FEAT_VIMINFO (char_u *)&p_viminfo, PV_NONE, #if defined(MSDOS) || defined(MSWIN) || defined(OS2) {(char_u *)"", (char_u *)"'100,<50,s10,h,rA:,rB:"} #else # ifdef AMIGA {(char_u *)"", (char_u *)"'100,<50,s10,h,rdf0:,rdf1:,rdf2:"} # else {(char_u *)"", (char_u *)"'100,<50,s10,h"} # endif #endif #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"virtualedit", "ve", P_STRING|P_COMMA|P_NODUP|P_VI_DEF|P_VIM|P_CURSWANT, #ifdef FEAT_VIRTUALEDIT (char_u *)&p_ve, PV_NONE, {(char_u *)"", (char_u *)""} #else (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} #endif SCRIPTID_INIT}, {"visualbell", "vb", P_BOOL|P_VI_DEF, (char_u *)&p_vb, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"w300", NULL, P_NUM|P_VI_DEF, (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"w1200", NULL, P_NUM|P_VI_DEF, (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"w9600", NULL, P_NUM|P_VI_DEF, (char_u *)NULL, PV_NONE, {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"warn", NULL, P_BOOL|P_VI_DEF, (char_u *)&p_warn, PV_NONE, {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, {"weirdinvert", "wiv", P_BOOL|P_VI_DEF|P_RCLR, (char_u *)&p_wiv, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"whichwrap", "ww", P_STRING|P_VIM|P_COMMA|P_FLAGLIST, (char_u *)&p_ww, PV_NONE, {(char_u *)"", (char_u *)"b,s"} SCRIPTID_INIT}, {"wildchar", "wc", P_NUM|P_VIM, (char_u *)&p_wc, PV_NONE, {(char_u *)(long)Ctrl_E, (char_u *)(long)TAB} SCRIPTID_INIT}, {"wildcharm", "wcm", P_NUM|P_VI_DEF, (char_u *)&p_wcm, PV_NONE, {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"wildignore", "wig", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, #ifdef FEAT_WILDIGN (char_u *)&p_wig, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, {"wildignorecase", "wic", P_BOOL|P_VI_DEF, (char_u *)&p_wic, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"wildmenu", "wmnu", P_BOOL|P_VI_DEF, #ifdef FEAT_WILDMENU (char_u *)&p_wmnu, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"wildmode", "wim", P_STRING|P_VI_DEF|P_COMMA|P_NODUP, (char_u *)&p_wim, PV_NONE, {(char_u *)"full", (char_u *)0L} SCRIPTID_INIT}, {"wildoptions", "wop", P_STRING|P_VI_DEF, #ifdef FEAT_CMDL_COMPL (char_u *)&p_wop, PV_NONE, {(char_u *)"", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"winaltkeys", "wak", P_STRING|P_VI_DEF, #ifdef FEAT_WAK (char_u *)&p_wak, PV_NONE, {(char_u *)"menu", (char_u *)0L} #else (char_u *)NULL, PV_NONE, {(char_u *)NULL, (char_u *)0L} #endif SCRIPTID_INIT}, {"window", "wi", P_NUM|P_VI_DEF, (char_u *)&p_window, PV_NONE, {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"winheight", "wh", P_NUM|P_VI_DEF, #ifdef FEAT_WINDOWS (char_u *)&p_wh, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)1L, (char_u *)0L} SCRIPTID_INIT}, {"winfixheight", "wfh", P_BOOL|P_VI_DEF|P_RSTAT, #ifdef FEAT_WINDOWS (char_u *)VAR_WIN, PV_WFH, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"winfixwidth", "wfw", P_BOOL|P_VI_DEF|P_RSTAT, #ifdef FEAT_VERTSPLIT (char_u *)VAR_WIN, PV_WFW, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"winminheight", "wmh", P_NUM|P_VI_DEF, #ifdef FEAT_WINDOWS (char_u *)&p_wmh, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)1L, (char_u *)0L} SCRIPTID_INIT}, {"winminwidth", "wmw", P_NUM|P_VI_DEF, #ifdef FEAT_VERTSPLIT (char_u *)&p_wmw, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)1L, (char_u *)0L} SCRIPTID_INIT}, {"winwidth", "wiw", P_NUM|P_VI_DEF, #ifdef FEAT_VERTSPLIT (char_u *)&p_wiw, PV_NONE, #else (char_u *)NULL, PV_NONE, #endif {(char_u *)20L, (char_u *)0L} SCRIPTID_INIT}, {"wrap", NULL, P_BOOL|P_VI_DEF|P_RWIN, (char_u *)VAR_WIN, PV_WRAP, {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, {"wrapmargin", "wm", P_NUM|P_VI_DEF, (char_u *)&p_wm, PV_WM, {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, {"wrapscan", "ws", P_BOOL|P_VI_DEF, (char_u *)&p_ws, PV_NONE, {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, {"write", NULL, P_BOOL|P_VI_DEF, (char_u *)&p_write, PV_NONE, {(char_u *)TRUE, (char_u *)0L} SCRIPTID_INIT}, {"writeany", "wa", P_BOOL|P_VI_DEF, (char_u *)&p_wa, PV_NONE, {(char_u *)FALSE, (char_u *)0L} SCRIPTID_INIT}, {"writebackup", "wb", P_BOOL|P_VI_DEF|P_VIM, (char_u *)&p_wb, PV_NONE, { #ifdef FEAT_WRITEBACKUP (char_u *)TRUE, #else (char_u *)FALSE, #endif (char_u *)0L} SCRIPTID_INIT}, {"writedelay", "wd", P_NUM|P_VI_DEF, (char_u *)&p_wd, PV_NONE, {(char_u *)0L, (char_u *)0L} SCRIPTID_INIT}, /* terminal output codes */ #define p_term(sss, vvv) {sss, NULL, P_STRING|P_VI_DEF|P_RALL|P_SECURE, \ (char_u *)&vvv, PV_NONE, \ {(char_u *)"", (char_u *)0L} SCRIPTID_INIT}, p_term("t_AB", T_CAB) p_term("t_AF", T_CAF) p_term("t_AL", T_CAL) p_term("t_al", T_AL) p_term("t_bc", T_BC) p_term("t_cd", T_CD) p_term("t_ce", T_CE) p_term("t_cl", T_CL) p_term("t_cm", T_CM) p_term("t_Co", T_CCO) p_term("t_CS", T_CCS) p_term("t_cs", T_CS) #ifdef FEAT_VERTSPLIT p_term("t_CV", T_CSV) #endif p_term("t_ut", T_UT) p_term("t_da", T_DA) p_term("t_db", T_DB) p_term("t_DL", T_CDL) p_term("t_dl", T_DL) p_term("t_fs", T_FS) p_term("t_IE", T_CIE) p_term("t_IS", T_CIS) p_term("t_ke", T_KE) p_term("t_ks", T_KS) p_term("t_le", T_LE) p_term("t_mb", T_MB) p_term("t_md", T_MD) p_term("t_me", T_ME) p_term("t_mr", T_MR) p_term("t_ms", T_MS) p_term("t_nd", T_ND) p_term("t_op", T_OP) p_term("t_RI", T_CRI) p_term("t_RV", T_CRV) p_term("t_Sb", T_CSB) p_term("t_Sf", T_CSF) p_term("t_se", T_SE) p_term("t_so", T_SO) p_term("t_sr", T_SR) p_term("t_ts", T_TS) p_term("t_te", T_TE) p_term("t_ti", T_TI) p_term("t_ue", T_UE) p_term("t_us", T_US) p_term("t_vb", T_VB) p_term("t_ve", T_VE) p_term("t_vi", T_VI) p_term("t_vs", T_VS) p_term("t_WP", T_CWP) p_term("t_WS", T_CWS) p_term("t_SI", T_CSI) p_term("t_EI", T_CEI) p_term("t_xs", T_XS) p_term("t_ZH", T_CZH) p_term("t_ZR", T_CZR) /* terminal key codes are not in here */ /* end marker */ {NULL, NULL, 0, NULL, PV_NONE, {NULL, NULL} SCRIPTID_INIT} }; #define PARAM_COUNT (sizeof(options) / sizeof(struct vimoption)) #ifdef FEAT_MBYTE static char *(p_ambw_values[]) = {"single", "double", NULL}; #endif static char *(p_bg_values[]) = {"light", "dark", NULL}; static char *(p_nf_values[]) = {"octal", "hex", "alpha", NULL}; static char *(p_ff_values[]) = {FF_UNIX, FF_DOS, FF_MAC, NULL}; #ifdef FEAT_CRYPT static char *(p_cm_values[]) = {"zip", "blowfish", NULL}; #endif #ifdef FEAT_CMDL_COMPL static char *(p_wop_values[]) = {"tagfile", NULL}; #endif #ifdef FEAT_WAK static char *(p_wak_values[]) = {"yes", "menu", "no", NULL}; #endif static char *(p_mousem_values[]) = {"extend", "popup", "popup_setpos", "mac", NULL}; #ifdef FEAT_VISUAL static char *(p_sel_values[]) = {"inclusive", "exclusive", "old", NULL}; static char *(p_slm_values[]) = {"mouse", "key", "cmd", NULL}; #endif #ifdef FEAT_VISUAL static char *(p_km_values[]) = {"startsel", "stopsel", NULL}; #endif #ifdef FEAT_BROWSE static char *(p_bsdir_values[]) = {"current", "last", "buffer", NULL}; #endif #ifdef FEAT_SCROLLBIND static char *(p_scbopt_values[]) = {"ver", "hor", "jump", NULL}; #endif static char *(p_debug_values[]) = {"msg", "throw", "beep", NULL}; #ifdef FEAT_VERTSPLIT static char *(p_ead_values[]) = {"both", "ver", "hor", NULL}; #endif #if defined(FEAT_QUICKFIX) # ifdef FEAT_AUTOCMD static char *(p_buftype_values[]) = {"nofile", "nowrite", "quickfix", "help", "acwrite", NULL}; # else static char *(p_buftype_values[]) = {"nofile", "nowrite", "quickfix", "help", NULL}; # endif static char *(p_bufhidden_values[]) = {"hide", "unload", "delete", "wipe", NULL}; #endif static char *(p_bs_values[]) = {"indent", "eol", "start", NULL}; #ifdef FEAT_FOLDING static char *(p_fdm_values[]) = {"manual", "expr", "marker", "indent", "syntax", # ifdef FEAT_DIFF "diff", # endif NULL}; static char *(p_fcl_values[]) = {"all", NULL}; #endif #ifdef FEAT_INS_EXPAND static char *(p_cot_values[]) = {"menu", "menuone", "longest", "preview", NULL}; #endif static void set_option_default __ARGS((int, int opt_flags, int compatible)); static void set_options_default __ARGS((int opt_flags)); static char_u *term_bg_default __ARGS((void)); static void did_set_option __ARGS((int opt_idx, int opt_flags, int new_value)); static char_u *illegal_char __ARGS((char_u *, int)); static int string_to_key __ARGS((char_u *arg)); #ifdef FEAT_CMDWIN static char_u *check_cedit __ARGS((void)); #endif #ifdef FEAT_TITLE static void did_set_title __ARGS((int icon)); #endif static char_u *option_expand __ARGS((int opt_idx, char_u *val)); static void didset_options __ARGS((void)); static void check_string_option __ARGS((char_u **pp)); #if defined(FEAT_EVAL) || defined(PROTO) static long_u *insecure_flag __ARGS((int opt_idx, int opt_flags)); #else # define insecure_flag(opt_idx, opt_flags) (&options[opt_idx].flags) #endif static void set_string_option_global __ARGS((int opt_idx, char_u **varp)); static void set_string_option __ARGS((int opt_idx, char_u *value, int opt_flags)); static char_u *did_set_string_option __ARGS((int opt_idx, char_u **varp, int new_value_alloced, char_u *oldval, char_u *errbuf, int opt_flags)); static char_u *set_chars_option __ARGS((char_u **varp)); #ifdef FEAT_SYN_HL static int int_cmp __ARGS((const void *a, const void *b)); #endif #ifdef FEAT_CLIPBOARD static char_u *check_clipboard_option __ARGS((void)); #endif #ifdef FEAT_SPELL static char_u *compile_cap_prog __ARGS((synblock_T *synblock)); #endif #ifdef FEAT_EVAL static void set_option_scriptID_idx __ARGS((int opt_idx, int opt_flags, int id)); #endif static char_u *set_bool_option __ARGS((int opt_idx, char_u *varp, int value, int opt_flags)); static char_u *set_num_option __ARGS((int opt_idx, char_u *varp, long value, char_u *errbuf, size_t errbuflen, int opt_flags)); static void check_redraw __ARGS((long_u flags)); static int findoption __ARGS((char_u *)); static int find_key_option __ARGS((char_u *)); static void showoptions __ARGS((int all, int opt_flags)); static int optval_default __ARGS((struct vimoption *, char_u *varp)); static void showoneopt __ARGS((struct vimoption *, int opt_flags)); static int put_setstring __ARGS((FILE *fd, char *cmd, char *name, char_u **valuep, int expand)); static int put_setnum __ARGS((FILE *fd, char *cmd, char *name, long *valuep)); static int put_setbool __ARGS((FILE *fd, char *cmd, char *name, int value)); static int istermoption __ARGS((struct vimoption *)); static char_u *get_varp_scope __ARGS((struct vimoption *p, int opt_flags)); static char_u *get_varp __ARGS((struct vimoption *)); static void option_value2string __ARGS((struct vimoption *, int opt_flags)); static int wc_use_keyname __ARGS((char_u *varp, long *wcp)); #ifdef FEAT_LANGMAP static void langmap_init __ARGS((void)); static void langmap_set __ARGS((void)); #endif static void paste_option_changed __ARGS((void)); static void compatible_set __ARGS((void)); #ifdef FEAT_LINEBREAK static void fill_breakat_flags __ARGS((void)); #endif static int opt_strings_flags __ARGS((char_u *val, char **values, unsigned *flagp, int list)); static int check_opt_strings __ARGS((char_u *val, char **values, int)); static int check_opt_wim __ARGS((void)); /* * Initialize the options, first part. * * Called only once from main(), just after creating the first buffer. */ void set_init_1() { char_u *p; int opt_idx; long_u n; #ifdef FEAT_LANGMAP langmap_init(); #endif /* Be Vi compatible by default */ p_cp = TRUE; /* Use POSIX compatibility when $VIM_POSIX is set. */ if (mch_getenv((char_u *)"VIM_POSIX") != NULL) { set_string_default("cpo", (char_u *)CPO_ALL); set_string_default("shm", (char_u *)"A"); } /* * Find default value for 'shell' option. * Don't use it if it is empty. */ if (((p = mch_getenv((char_u *)"SHELL")) != NULL && *p != NUL) #if defined(MSDOS) || defined(MSWIN) || defined(OS2) # ifdef __EMX__ || ((p = mch_getenv((char_u *)"EMXSHELL")) != NULL && *p != NUL) # endif || ((p = mch_getenv((char_u *)"COMSPEC")) != NULL && *p != NUL) # ifdef WIN3264 || ((p = default_shell()) != NULL && *p != NUL) # endif #endif ) set_string_default("sh", p); #ifdef FEAT_WILDIGN /* * Set the default for 'backupskip' to include environment variables for * temp files. */ { # ifdef UNIX static char *(names[4]) = {"", "TMPDIR", "TEMP", "TMP"}; # else static char *(names[3]) = {"TMPDIR", "TEMP", "TMP"}; # endif int len; garray_T ga; int mustfree; ga_init2(&ga, 1, 100); for (n = 0; n < (long)(sizeof(names) / sizeof(char *)); ++n) { mustfree = FALSE; # ifdef UNIX if (*names[n] == NUL) p = (char_u *)"/tmp"; else # endif p = vim_getenv((char_u *)names[n], &mustfree); if (p != NULL && *p != NUL) { /* First time count the NUL, otherwise count the ','. */ len = (int)STRLEN(p) + 3; if (ga_grow(&ga, len) == OK) { if (ga.ga_len > 0) STRCAT(ga.ga_data, ","); STRCAT(ga.ga_data, p); add_pathsep(ga.ga_data); STRCAT(ga.ga_data, "*"); ga.ga_len += len; } } if (mustfree) vim_free(p); } if (ga.ga_data != NULL) { set_string_default("bsk", ga.ga_data); vim_free(ga.ga_data); } } #endif /* * 'maxmemtot' and 'maxmem' may have to be adjusted for available memory */ opt_idx = findoption((char_u *)"maxmemtot"); if (opt_idx >= 0) { #if !defined(HAVE_AVAIL_MEM) && !defined(HAVE_TOTAL_MEM) if (options[opt_idx].def_val[VI_DEFAULT] == (char_u *)0L) #endif { #ifdef HAVE_AVAIL_MEM /* Use amount of memory available at this moment. */ n = (mch_avail_mem(FALSE) >> 11); #else # ifdef HAVE_TOTAL_MEM /* Use amount of memory available to Vim. */ n = (mch_total_mem(FALSE) >> 1); # else n = (0x7fffffff >> 11); # endif #endif options[opt_idx].def_val[VI_DEFAULT] = (char_u *)n; opt_idx = findoption((char_u *)"maxmem"); if (opt_idx >= 0) { #if !defined(HAVE_AVAIL_MEM) && !defined(HAVE_TOTAL_MEM) if ((long)options[opt_idx].def_val[VI_DEFAULT] > n || (long)options[opt_idx].def_val[VI_DEFAULT] == 0L) #endif options[opt_idx].def_val[VI_DEFAULT] = (char_u *)n; } } } #ifdef FEAT_GUI_W32 /* force 'shortname' for Win32s */ if (gui_is_win32s()) { opt_idx = findoption((char_u *)"shortname"); if (opt_idx >= 0) options[opt_idx].def_val[VI_DEFAULT] = (char_u *)TRUE; } #endif #ifdef FEAT_SEARCHPATH { char_u *cdpath; char_u *buf; int i; int j; int mustfree = FALSE; /* Initialize the 'cdpath' option's default value. */ cdpath = vim_getenv((char_u *)"CDPATH", &mustfree); if (cdpath != NULL) { buf = alloc((unsigned)((STRLEN(cdpath) << 1) + 2)); if (buf != NULL) { buf[0] = ','; /* start with ",", current dir first */ j = 1; for (i = 0; cdpath[i] != NUL; ++i) { if (vim_ispathlistsep(cdpath[i])) buf[j++] = ','; else { if (cdpath[i] == ' ' || cdpath[i] == ',') buf[j++] = '\\'; buf[j++] = cdpath[i]; } } buf[j] = NUL; opt_idx = findoption((char_u *)"cdpath"); if (opt_idx >= 0) { options[opt_idx].def_val[VI_DEFAULT] = buf; options[opt_idx].flags |= P_DEF_ALLOCED; } else vim_free(buf); /* cannot happen */ } if (mustfree) vim_free(cdpath); } } #endif #if defined(FEAT_POSTSCRIPT) && (defined(MSWIN) || defined(OS2) || defined(VMS) || defined(EBCDIC) || defined(MAC) || defined(hpux)) /* Set print encoding on platforms that don't default to latin1 */ set_string_default("penc", # if defined(MSWIN) || defined(OS2) (char_u *)"cp1252" # else # ifdef VMS (char_u *)"dec-mcs" # else # ifdef EBCDIC (char_u *)"ebcdic-uk" # else # ifdef MAC (char_u *)"mac-roman" # else /* HPUX */ (char_u *)"hp-roman8" # endif # endif # endif # endif ); #endif #ifdef FEAT_POSTSCRIPT /* 'printexpr' must be allocated to be able to evaluate it. */ set_string_default("pexpr", # if defined(MSWIN) || defined(MSDOS) || defined(OS2) (char_u *)"system('copy' . ' ' . v:fname_in . (&printdevice == '' ? ' LPT1:' : (' \"' . &printdevice . '\"'))) . delete(v:fname_in)" # else # ifdef VMS (char_u *)"system('print/delete' . (&printdevice == '' ? '' : ' /queue=' . &printdevice) . ' ' . v:fname_in)" # else (char_u *)"system('lpr' . (&printdevice == '' ? '' : ' -P' . &printdevice) . ' ' . v:fname_in) . delete(v:fname_in) + v:shell_error" # endif # endif ); #endif /* * Set all the options (except the terminal options) to their default * value. Also set the global value for local options. */ set_options_default(0); #ifdef FEAT_GUI if (found_reverse_arg) set_option_value((char_u *)"bg", 0L, (char_u *)"dark", 0); #endif curbuf->b_p_initialized = TRUE; curbuf->b_p_ar = -1; /* no local 'autoread' value */ check_buf_options(curbuf); check_win_options(curwin); check_options(); /* Must be before option_expand(), because that one needs vim_isIDc() */ didset_options(); #ifdef FEAT_SPELL /* Use the current chartab for the generic chartab. */ init_spell_chartab(); #endif #ifdef FEAT_LINEBREAK /* * initialize the table for 'breakat'. */ fill_breakat_flags(); #endif /* * Expand environment variables and things like "~" for the defaults. * If option_expand() returns non-NULL the variable is expanded. This can * only happen for non-indirect options. * Also set the default to the expanded value, so ":set" does not list * them. * Don't set the P_ALLOCED flag, because we don't want to free the * default. */ for (opt_idx = 0; !istermoption(&options[opt_idx]); opt_idx++) { if ((options[opt_idx].flags & P_GETTEXT) && options[opt_idx].var != NULL) p = (char_u *)_(*(char **)options[opt_idx].var); else p = option_expand(opt_idx, NULL); if (p != NULL && (p = vim_strsave(p)) != NULL) { *(char_u **)options[opt_idx].var = p; /* VIMEXP * Defaults for all expanded options are currently the same for Vi * and Vim. When this changes, add some code here! Also need to * split P_DEF_ALLOCED in two. */ if (options[opt_idx].flags & P_DEF_ALLOCED) vim_free(options[opt_idx].def_val[VI_DEFAULT]); options[opt_idx].def_val[VI_DEFAULT] = p; options[opt_idx].flags |= P_DEF_ALLOCED; } } /* Initialize the highlight_attr[] table. */ highlight_changed(); save_file_ff(curbuf); /* Buffer is unchanged */ /* Parse default for 'wildmode' */ check_opt_wim(); #if defined(FEAT_ARABIC) /* Detect use of mlterm. * Mlterm is a terminal emulator akin to xterm that has some special * abilities (bidi namely). * NOTE: mlterm's author is being asked to 'set' a variable * instead of an environment variable due to inheritance. */ if (mch_getenv((char_u *)"MLTERM") != NULL) set_option_value((char_u *)"tbidi", 1L, NULL, 0); #endif #if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING) /* Parse default for 'fillchars'. */ (void)set_chars_option(&p_fcs); #endif #ifdef FEAT_CLIPBOARD /* Parse default for 'clipboard' */ (void)check_clipboard_option(); #endif #ifdef FEAT_MBYTE # if defined(WIN3264) && defined(FEAT_GETTEXT) /* * If $LANG isn't set, try to get a good value for it. This makes the * right language be used automatically. Don't do this for English. */ if (mch_getenv((char_u *)"LANG") == NULL) { char buf[20]; /* Could use LOCALE_SISO639LANGNAME, but it's not in Win95. * LOCALE_SABBREVLANGNAME gives us three letters, like "enu", we use * only the first two. */ n = GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SABBREVLANGNAME, (LPTSTR)buf, 20); if (n >= 2 && STRNICMP(buf, "en", 2) != 0) { /* There are a few exceptions (probably more) */ if (STRNICMP(buf, "cht", 3) == 0 || STRNICMP(buf, "zht", 3) == 0) STRCPY(buf, "zh_TW"); else if (STRNICMP(buf, "chs", 3) == 0 || STRNICMP(buf, "zhc", 3) == 0) STRCPY(buf, "zh_CN"); else if (STRNICMP(buf, "jp", 2) == 0) STRCPY(buf, "ja"); else buf[2] = NUL; /* truncate to two-letter code */ vim_setenv("LANG", buf); } } # else # ifdef MACOS_CONVERT /* Moved to os_mac_conv.c to avoid dependency problems. */ mac_lang_init(); # endif # endif /* enc_locale() will try to find the encoding of the current locale. */ p = enc_locale(); if (p != NULL) { char_u *save_enc; /* Try setting 'encoding' and check if the value is valid. * If not, go back to the default "latin1". */ save_enc = p_enc; p_enc = p; if (STRCMP(p_enc, "gb18030") == 0) { /* We don't support "gb18030", but "cp936" is a good substitute * for practical purposes, thus use that. It's not an alias to * still support conversion between gb18030 and utf-8. */ p_enc = vim_strsave((char_u *)"cp936"); vim_free(p); } if (mb_init() == NULL) { opt_idx = findoption((char_u *)"encoding"); if (opt_idx >= 0) { options[opt_idx].def_val[VI_DEFAULT] = p_enc; options[opt_idx].flags |= P_DEF_ALLOCED; } #if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(MACOS) \ || defined(VMS) if (STRCMP(p_enc, "latin1") == 0 # ifdef FEAT_MBYTE || enc_utf8 # endif ) { /* Adjust the default for 'isprint' and 'iskeyword' to match * latin1. Also set the defaults for when 'nocompatible' is * set. */ set_string_option_direct((char_u *)"isp", -1, ISP_LATIN1, OPT_FREE, SID_NONE); set_string_option_direct((char_u *)"isk", -1, ISK_LATIN1, OPT_FREE, SID_NONE); opt_idx = findoption((char_u *)"isp"); if (opt_idx >= 0) options[opt_idx].def_val[VIM_DEFAULT] = ISP_LATIN1; opt_idx = findoption((char_u *)"isk"); if (opt_idx >= 0) options[opt_idx].def_val[VIM_DEFAULT] = ISK_LATIN1; (void)init_chartab(); } #endif # if defined(WIN3264) && !defined(FEAT_GUI) /* Win32 console: When GetACP() returns a different value from * GetConsoleCP() set 'termencoding'. */ if (GetACP() != GetConsoleCP()) { char buf[50]; sprintf(buf, "cp%ld", (long)GetConsoleCP()); p_tenc = vim_strsave((char_u *)buf); if (p_tenc != NULL) { opt_idx = findoption((char_u *)"termencoding"); if (opt_idx >= 0) { options[opt_idx].def_val[VI_DEFAULT] = p_tenc; options[opt_idx].flags |= P_DEF_ALLOCED; } convert_setup(&input_conv, p_tenc, p_enc); convert_setup(&output_conv, p_enc, p_tenc); } else p_tenc = empty_option; } # endif # if defined(WIN3264) && defined(FEAT_MBYTE) /* $HOME may have characters in active code page. */ init_homedir(); # endif } else { vim_free(p_enc); p_enc = save_enc; } } #endif #ifdef FEAT_MULTI_LANG /* Set the default for 'helplang'. */ set_helplang_default(get_mess_lang()); #endif } /* * Set an option to its default value. * This does not take care of side effects! */ static void set_option_default(opt_idx, opt_flags, compatible) int opt_idx; int opt_flags; /* OPT_FREE, OPT_LOCAL and/or OPT_GLOBAL */ int compatible; /* use Vi default value */ { char_u *varp; /* pointer to variable for current option */ int dvi; /* index in def_val[] */ long_u flags; long_u *flagsp; int both = (opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0; varp = get_varp_scope(&(options[opt_idx]), both ? OPT_LOCAL : opt_flags); flags = options[opt_idx].flags; if (varp != NULL) /* skip hidden option, nothing to do for it */ { dvi = ((flags & P_VI_DEF) || compatible) ? VI_DEFAULT : VIM_DEFAULT; if (flags & P_STRING) { /* Use set_string_option_direct() for local options to handle * freeing and allocating the value. */ if (options[opt_idx].indir != PV_NONE) set_string_option_direct(NULL, opt_idx, options[opt_idx].def_val[dvi], opt_flags, 0); else { if ((opt_flags & OPT_FREE) && (flags & P_ALLOCED)) free_string_option(*(char_u **)(varp)); *(char_u **)varp = options[opt_idx].def_val[dvi]; options[opt_idx].flags &= ~P_ALLOCED; } } else if (flags & P_NUM) { if (options[opt_idx].indir == PV_SCROLL) win_comp_scroll(curwin); else { *(long *)varp = (long)(long_i)options[opt_idx].def_val[dvi]; /* May also set global value for local option. */ if (both) *(long *)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL) = *(long *)varp; } } else /* P_BOOL */ { /* the cast to long is required for Manx C, long_i is needed for * MSVC */ *(int *)varp = (int)(long)(long_i)options[opt_idx].def_val[dvi]; #ifdef UNIX /* 'modeline' defaults to off for root */ if (options[opt_idx].indir == PV_ML && getuid() == ROOT_UID) *(int *)varp = FALSE; #endif /* May also set global value for local option. */ if (both) *(int *)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL) = *(int *)varp; } /* The default value is not insecure. */ flagsp = insecure_flag(opt_idx, opt_flags); *flagsp = *flagsp & ~P_INSECURE; } #ifdef FEAT_EVAL set_option_scriptID_idx(opt_idx, opt_flags, current_SID); #endif } /* * Set all options (except terminal options) to their default value. */ static void set_options_default(opt_flags) int opt_flags; /* OPT_FREE, OPT_LOCAL and/or OPT_GLOBAL */ { int i; #ifdef FEAT_WINDOWS win_T *wp; tabpage_T *tp; #endif for (i = 0; !istermoption(&options[i]); i++) if (!(options[i].flags & P_NODEFAULT)) set_option_default(i, opt_flags, p_cp); #ifdef FEAT_WINDOWS /* The 'scroll' option must be computed for all windows. */ FOR_ALL_TAB_WINDOWS(tp, wp) win_comp_scroll(wp); #else win_comp_scroll(curwin); #endif } /* * Set the Vi-default value of a string option. * Used for 'sh', 'backupskip' and 'term'. */ void set_string_default(name, val) char *name; char_u *val; { char_u *p; int opt_idx; p = vim_strsave(val); if (p != NULL) /* we don't want a NULL */ { opt_idx = findoption((char_u *)name); if (opt_idx >= 0) { if (options[opt_idx].flags & P_DEF_ALLOCED) vim_free(options[opt_idx].def_val[VI_DEFAULT]); options[opt_idx].def_val[VI_DEFAULT] = p; options[opt_idx].flags |= P_DEF_ALLOCED; } } } /* * Set the Vi-default value of a number option. * Used for 'lines' and 'columns'. */ void set_number_default(name, val) char *name; long val; { int opt_idx; opt_idx = findoption((char_u *)name); if (opt_idx >= 0) options[opt_idx].def_val[VI_DEFAULT] = (char_u *)(long_i)val; } #if defined(EXITFREE) || defined(PROTO) /* * Free all options. */ void free_all_options() { int i; for (i = 0; !istermoption(&options[i]); i++) { if (options[i].indir == PV_NONE) { /* global option: free value and default value. */ if (options[i].flags & P_ALLOCED && options[i].var != NULL) free_string_option(*(char_u **)options[i].var); if (options[i].flags & P_DEF_ALLOCED) free_string_option(options[i].def_val[VI_DEFAULT]); } else if (options[i].var != VAR_WIN && (options[i].flags & P_STRING)) /* buffer-local option: free global value */ free_string_option(*(char_u **)options[i].var); } } #endif /* * Initialize the options, part two: After getting Rows and Columns and * setting 'term'. */ void set_init_2() { int idx; /* * 'scroll' defaults to half the window height. Note that this default is * wrong when the window height changes. */ set_number_default("scroll", (long)((long_u)Rows >> 1)); idx = findoption((char_u *)"scroll"); if (idx >= 0 && !(options[idx].flags & P_WAS_SET)) set_option_default(idx, OPT_LOCAL, p_cp); comp_col(); /* * 'window' is only for backwards compatibility with Vi. * Default is Rows - 1. */ if (!option_was_set((char_u *)"window")) p_window = Rows - 1; set_number_default("window", Rows - 1); /* For DOS console the default is always black. */ #if !((defined(MSDOS) || defined(OS2) || defined(WIN3264)) && !defined(FEAT_GUI)) /* * If 'background' wasn't set by the user, try guessing the value, * depending on the terminal name. Only need to check for terminals * with a dark background, that can handle color. */ idx = findoption((char_u *)"bg"); if (idx >= 0 && !(options[idx].flags & P_WAS_SET) && *term_bg_default() == 'd') { set_string_option_direct(NULL, idx, (char_u *)"dark", OPT_FREE, 0); /* don't mark it as set, when starting the GUI it may be * changed again */ options[idx].flags &= ~P_WAS_SET; } #endif #ifdef CURSOR_SHAPE parse_shape_opt(SHAPE_CURSOR); /* set cursor shapes from 'guicursor' */ #endif #ifdef FEAT_MOUSESHAPE parse_shape_opt(SHAPE_MOUSE); /* set mouse shapes from 'mouseshape' */ #endif #ifdef FEAT_PRINTER (void)parse_printoptions(); /* parse 'printoptions' default value */ #endif } /* * Return "dark" or "light" depending on the kind of terminal. * This is just guessing! Recognized are: * "linux" Linux console * "screen.linux" Linux console with screen * "cygwin" Cygwin shell * "putty" Putty program * We also check the COLORFGBG environment variable, which is set by * rxvt and derivatives. This variable contains either two or three * values separated by semicolons; we want the last value in either * case. If this value is 0-6 or 8, our background is dark. */ static char_u * term_bg_default() { #if defined(MSDOS) || defined(OS2) || defined(WIN3264) /* DOS console nearly always black */ return (char_u *)"dark"; #else char_u *p; if (STRCMP(T_NAME, "linux") == 0 || STRCMP(T_NAME, "screen.linux") == 0 || STRCMP(T_NAME, "cygwin") == 0 || STRCMP(T_NAME, "putty") == 0 || ((p = mch_getenv((char_u *)"COLORFGBG")) != NULL && (p = vim_strrchr(p, ';')) != NULL && ((p[1] >= '0' && p[1] <= '6') || p[1] == '8') && p[2] == NUL)) return (char_u *)"dark"; return (char_u *)"light"; #endif } /* * Initialize the options, part three: After reading the .vimrc */ void set_init_3() { #if defined(UNIX) || defined(OS2) || defined(WIN3264) /* * Set 'shellpipe' and 'shellredir', depending on the 'shell' option. * This is done after other initializations, where 'shell' might have been * set, but only if they have not been set before. */ char_u *p; int idx_srr; int do_srr; #ifdef FEAT_QUICKFIX int idx_sp; int do_sp; #endif idx_srr = findoption((char_u *)"srr"); if (idx_srr < 0) do_srr = FALSE; else do_srr = !(options[idx_srr].flags & P_WAS_SET); #ifdef FEAT_QUICKFIX idx_sp = findoption((char_u *)"sp"); if (idx_sp < 0) do_sp = FALSE; else do_sp = !(options[idx_sp].flags & P_WAS_SET); #endif /* * Isolate the name of the shell: * - Skip beyond any path. E.g., "/usr/bin/csh -f" -> "csh -f". * - Remove any argument. E.g., "csh -f" -> "csh". * But don't allow a space in the path, so that this works: * "/usr/bin/csh --rcfile ~/.cshrc" * But don't do that for Windows, it's common to have a space in the path. */ #ifdef WIN3264 p = gettail(p_sh); p = vim_strnsave(p, (int)(skiptowhite(p) - p)); #else p = skiptowhite(p_sh); if (*p == NUL) { /* No white space, use the tail. */ p = vim_strsave(gettail(p_sh)); } else { char_u *p1, *p2; /* Find the last path separator before the space. */ p1 = p_sh; for (p2 = p_sh; p2 < p; mb_ptr_adv(p2)) if (vim_ispathsep(*p2)) p1 = p2 + 1; p = vim_strnsave(p1, (int)(p - p1)); } #endif if (p != NULL) { /* * Default for p_sp is "| tee", for p_srr is ">". * For known shells it is changed here to include stderr. */ if ( fnamecmp(p, "csh") == 0 || fnamecmp(p, "tcsh") == 0 # if defined(OS2) || defined(WIN3264) /* also check with .exe extension */ || fnamecmp(p, "csh.exe") == 0 || fnamecmp(p, "tcsh.exe") == 0 # endif ) { #if defined(FEAT_QUICKFIX) if (do_sp) { # ifdef WIN3264 p_sp = (char_u *)">&"; # else p_sp = (char_u *)"|& tee"; # endif options[idx_sp].def_val[VI_DEFAULT] = p_sp; } #endif if (do_srr) { p_srr = (char_u *)">&"; options[idx_srr].def_val[VI_DEFAULT] = p_srr; } } else # ifndef OS2 /* Always use bourne shell style redirection if we reach this */ if ( fnamecmp(p, "sh") == 0 || fnamecmp(p, "ksh") == 0 || fnamecmp(p, "mksh") == 0 || fnamecmp(p, "pdksh") == 0 || fnamecmp(p, "zsh") == 0 || fnamecmp(p, "zsh-beta") == 0 || fnamecmp(p, "bash") == 0 # ifdef WIN3264 || fnamecmp(p, "cmd") == 0 || fnamecmp(p, "sh.exe") == 0 || fnamecmp(p, "ksh.exe") == 0 || fnamecmp(p, "mksh.exe") == 0 || fnamecmp(p, "pdksh.exe") == 0 || fnamecmp(p, "zsh.exe") == 0 || fnamecmp(p, "zsh-beta.exe") == 0 || fnamecmp(p, "bash.exe") == 0 || fnamecmp(p, "cmd.exe") == 0 # endif ) # endif { #if defined(FEAT_QUICKFIX) if (do_sp) { # ifdef WIN3264 p_sp = (char_u *)">%s 2>&1"; # else p_sp = (char_u *)"2>&1| tee"; # endif options[idx_sp].def_val[VI_DEFAULT] = p_sp; } #endif if (do_srr) { p_srr = (char_u *)">%s 2>&1"; options[idx_srr].def_val[VI_DEFAULT] = p_srr; } } vim_free(p); } #endif #if defined(MSDOS) || defined(WIN3264) || defined(OS2) /* * Set 'shellcmdflag', 'shellxquote', and 'shellquote' depending on the * 'shell' option. * This is done after other initializations, where 'shell' might have been * set, but only if they have not been set before. Default for p_shcf is * "/c", for p_shq is "". For "sh" like shells it is changed here to * "-c" and "\"", but not for DJGPP, because it starts the shell without * command.com. And for Win32 we need to set p_sxq instead. */ if (strstr((char *)gettail(p_sh), "sh") != NULL) { int idx3; idx3 = findoption((char_u *)"shcf"); if (idx3 >= 0 && !(options[idx3].flags & P_WAS_SET)) { p_shcf = (char_u *)"-c"; options[idx3].def_val[VI_DEFAULT] = p_shcf; } # ifndef DJGPP # ifdef WIN3264 /* Somehow Win32 requires the quotes around the redirection too */ idx3 = findoption((char_u *)"sxq"); if (idx3 >= 0 && !(options[idx3].flags & P_WAS_SET)) { p_sxq = (char_u *)"\""; options[idx3].def_val[VI_DEFAULT] = p_sxq; } # else idx3 = findoption((char_u *)"shq"); if (idx3 >= 0 && !(options[idx3].flags & P_WAS_SET)) { p_shq = (char_u *)"\""; options[idx3].def_val[VI_DEFAULT] = p_shq; } # endif # endif } else if (strstr((char *)gettail(p_sh), "cmd.exe") != NULL) { int idx3; /* * cmd.exe on Windows will strip the first and last double quote given * on the command line, e.g. most of the time things like: * cmd /c "my path/to/echo" "my args to echo" * become: * my path/to/echo" "my args to echo * when executed. * * To avoid this, set shellxquote to surround the command in * parenthesis. This appears to make most commands work, without * breaking commands that worked previously, such as * '"path with spaces/cmd" "a&b"'. */ idx3 = findoption((char_u *)"sxq"); if (idx3 >= 0 && !(options[idx3].flags & P_WAS_SET)) { p_sxq = (char_u *)"("; options[idx3].def_val[VI_DEFAULT] = p_sxq; } idx3 = findoption((char_u *)"shcf"); if (idx3 >= 0 && !(options[idx3].flags & P_WAS_SET)) { p_shcf = (char_u *)"/c"; options[idx3].def_val[VI_DEFAULT] = p_shcf; } } #endif #ifdef FEAT_TITLE set_title_defaults(); #endif } #if defined(FEAT_MULTI_LANG) || defined(PROTO) /* * When 'helplang' is still at its default value, set it to "lang". * Only the first two characters of "lang" are used. */ void set_helplang_default(lang) char_u *lang; { int idx; if (lang == NULL || STRLEN(lang) < 2) /* safety check */ return; idx = findoption((char_u *)"hlg"); if (idx >= 0 && !(options[idx].flags & P_WAS_SET)) { if (options[idx].flags & P_ALLOCED) free_string_option(p_hlg); p_hlg = vim_strsave(lang); if (p_hlg == NULL) p_hlg = empty_option; else { /* zh_CN becomes "cn", zh_TW becomes "tw". */ if (STRNICMP(p_hlg, "zh_", 3) == 0 && STRLEN(p_hlg) >= 5) { p_hlg[0] = TOLOWER_ASC(p_hlg[3]); p_hlg[1] = TOLOWER_ASC(p_hlg[4]); } p_hlg[2] = NUL; } options[idx].flags |= P_ALLOCED; } } #endif #ifdef FEAT_GUI static char_u *gui_bg_default __ARGS((void)); static char_u * gui_bg_default() { if (gui_get_lightness(gui.back_pixel) < 127) return (char_u *)"dark"; return (char_u *)"light"; } /* * Option initializations that can only be done after opening the GUI window. */ void init_gui_options() { /* Set the 'background' option according to the lightness of the * background color, unless the user has set it already. */ if (!option_was_set((char_u *)"bg") && STRCMP(p_bg, gui_bg_default()) != 0) { set_option_value((char_u *)"bg", 0L, gui_bg_default(), 0); highlight_changed(); } } #endif #ifdef FEAT_TITLE /* * 'title' and 'icon' only default to true if they have not been set or reset * in .vimrc and we can read the old value. * When 'title' and 'icon' have been reset in .vimrc, we won't even check if * they can be reset. This reduces startup time when using X on a remote * machine. */ void set_title_defaults() { int idx1; long val; /* * If GUI is (going to be) used, we can always set the window title and * icon name. Saves a bit of time, because the X11 display server does * not need to be contacted. */ idx1 = findoption((char_u *)"title"); if (idx1 >= 0 && !(options[idx1].flags & P_WAS_SET)) { #ifdef FEAT_GUI if (gui.starting || gui.in_use) val = TRUE; else #endif val = mch_can_restore_title(); options[idx1].def_val[VI_DEFAULT] = (char_u *)(long_i)val; p_title = val; } idx1 = findoption((char_u *)"icon"); if (idx1 >= 0 && !(options[idx1].flags & P_WAS_SET)) { #ifdef FEAT_GUI if (gui.starting || gui.in_use) val = TRUE; else #endif val = mch_can_restore_icon(); options[idx1].def_val[VI_DEFAULT] = (char_u *)(long_i)val; p_icon = val; } } #endif /* * Parse 'arg' for option settings. * * 'arg' may be IObuff, but only when no errors can be present and option * does not need to be expanded with option_expand(). * "opt_flags": * 0 for ":set" * OPT_GLOBAL for ":setglobal" * OPT_LOCAL for ":setlocal" and a modeline * OPT_MODELINE for a modeline * OPT_WINONLY to only set window-local options * OPT_NOWIN to skip setting window-local options * * returns FAIL if an error is detected, OK otherwise */ int do_set(arg, opt_flags) char_u *arg; /* option string (may be written to!) */ int opt_flags; { int opt_idx; char_u *errmsg; char_u errbuf[80]; char_u *startarg; int prefix; /* 1: nothing, 0: "no", 2: "inv" in front of name */ int nextchar; /* next non-white char after option name */ int afterchar; /* character just after option name */ int len; int i; long value; int key; long_u flags; /* flags for current option */ char_u *varp = NULL; /* pointer to variable for current option */ int did_show = FALSE; /* already showed one value */ int adding; /* "opt+=arg" */ int prepending; /* "opt^=arg" */ int removing; /* "opt-=arg" */ int cp_val = 0; char_u key_name[2]; if (*arg == NUL) { showoptions(0, opt_flags); did_show = TRUE; goto theend; } while (*arg != NUL) /* loop to process all options */ { errmsg = NULL; startarg = arg; /* remember for error message */ if (STRNCMP(arg, "all", 3) == 0 && !isalpha(arg[3]) && !(opt_flags & OPT_MODELINE)) { /* * ":set all" show all options. * ":set all&" set all options to their default value. */ arg += 3; if (*arg == '&') { ++arg; /* Only for :set command set global value of local options. */ set_options_default(OPT_FREE | opt_flags); } else { showoptions(1, opt_flags); did_show = TRUE; } } else if (STRNCMP(arg, "termcap", 7) == 0 && !(opt_flags & OPT_MODELINE)) { showoptions(2, opt_flags); show_termcodes(); did_show = TRUE; arg += 7; } else { prefix = 1; if (STRNCMP(arg, "no", 2) == 0 && STRNCMP(arg, "novice", 6) != 0) { prefix = 0; arg += 2; } else if (STRNCMP(arg, "inv", 3) == 0) { prefix = 2; arg += 3; } /* find end of name */ key = 0; if (*arg == '<') { nextchar = 0; opt_idx = -1; /* look out for <t_>;> */ if (arg[1] == 't' && arg[2] == '_' && arg[3] && arg[4]) len = 5; else { len = 1; while (arg[len] != NUL && arg[len] != '>') ++len; } if (arg[len] != '>') { errmsg = e_invarg; goto skip; } arg[len] = NUL; /* put NUL after name */ if (arg[1] == 't' && arg[2] == '_') /* could be term code */ opt_idx = findoption(arg + 1); arg[len++] = '>'; /* restore '>' */ if (opt_idx == -1) key = find_key_option(arg + 1); } else { len = 0; /* * The two characters after "t_" may not be alphanumeric. */ if (arg[0] == 't' && arg[1] == '_' && arg[2] && arg[3]) len = 4; else while (ASCII_ISALNUM(arg[len]) || arg[len] == '_') ++len; nextchar = arg[len]; arg[len] = NUL; /* put NUL after name */ opt_idx = findoption(arg); arg[len] = nextchar; /* restore nextchar */ if (opt_idx == -1) key = find_key_option(arg); } /* remember character after option name */ afterchar = arg[len]; /* skip white space, allow ":set ai ?" */ while (vim_iswhite(arg[len])) ++len; adding = FALSE; prepending = FALSE; removing = FALSE; if (arg[len] != NUL && arg[len + 1] == '=') { if (arg[len] == '+') { adding = TRUE; /* "+=" */ ++len; } else if (arg[len] == '^') { prepending = TRUE; /* "^=" */ ++len; } else if (arg[len] == '-') { removing = TRUE; /* "-=" */ ++len; } } nextchar = arg[len]; if (opt_idx == -1 && key == 0) /* found a mismatch: skip */ { errmsg = (char_u *)N_("E518: Unknown option"); goto skip; } if (opt_idx >= 0) { if (options[opt_idx].var == NULL) /* hidden option: skip */ { /* Only give an error message when requesting the value of * a hidden option, ignore setting it. */ if (vim_strchr((char_u *)"=:!&<", nextchar) == NULL && (!(options[opt_idx].flags & P_BOOL) || nextchar == '?')) errmsg = (char_u *)N_("E519: Option not supported"); goto skip; } flags = options[opt_idx].flags; varp = get_varp_scope(&(options[opt_idx]), opt_flags); } else { flags = P_STRING; if (key < 0) { key_name[0] = KEY2TERMCAP0(key); key_name[1] = KEY2TERMCAP1(key); } else { key_name[0] = KS_KEY; key_name[1] = (key & 0xff); } } /* Skip all options that are not window-local (used when showing * an already loaded buffer in a window). */ if ((opt_flags & OPT_WINONLY) && (opt_idx < 0 || options[opt_idx].var != VAR_WIN)) goto skip; /* Skip all options that are window-local (used for :vimgrep). */ if ((opt_flags & OPT_NOWIN) && opt_idx >= 0 && options[opt_idx].var == VAR_WIN) goto skip; /* Disallow changing some options from modelines. */ if (opt_flags & OPT_MODELINE) { if (flags & (P_SECURE | P_NO_ML)) { errmsg = (char_u *)_("E520: Not allowed in a modeline"); goto skip; } #ifdef FEAT_DIFF /* In diff mode some options are overruled. This avoids that * 'foldmethod' becomes "marker" instead of "diff" and that * "wrap" gets set. */ if (curwin->w_p_diff && opt_idx >= 0 /* shut up coverity warning */ && (options[opt_idx].indir == PV_FDM || options[opt_idx].indir == PV_WRAP)) goto skip; #endif } #ifdef HAVE_SANDBOX /* Disallow changing some options in the sandbox */ if (sandbox != 0 && (flags & P_SECURE)) { errmsg = (char_u *)_(e_sandbox); goto skip; } #endif if (vim_strchr((char_u *)"?=:!&<", nextchar) != NULL) { arg += len; cp_val = p_cp; if (nextchar == '&' && arg[1] == 'v' && arg[2] == 'i') { if (arg[3] == 'm') /* "opt&vim": set to Vim default */ { cp_val = FALSE; arg += 3; } else /* "opt&vi": set to Vi default */ { cp_val = TRUE; arg += 2; } } if (vim_strchr((char_u *)"?!&<", nextchar) != NULL && arg[1] != NUL && !vim_iswhite(arg[1])) { errmsg = e_trailing; goto skip; } } /* * allow '=' and ':' as MSDOS command.com allows only one * '=' character per "set" command line. grrr. (jw) */ if (nextchar == '?' || (prefix == 1 && vim_strchr((char_u *)"=:&<", nextchar) == NULL && !(flags & P_BOOL))) { /* * print value */ if (did_show) msg_putchar('\n'); /* cursor below last one */ else { gotocmdline(TRUE); /* cursor at status line */ did_show = TRUE; /* remember that we did a line */ } if (opt_idx >= 0) { showoneopt(&options[opt_idx], opt_flags); #ifdef FEAT_EVAL if (p_verbose > 0) { /* Mention where the option was last set. */ if (varp == options[opt_idx].var) last_set_msg(options[opt_idx].scriptID); else if ((int)options[opt_idx].indir & PV_WIN) last_set_msg(curwin->w_p_scriptID[ (int)options[opt_idx].indir & PV_MASK]); else if ((int)options[opt_idx].indir & PV_BUF) last_set_msg(curbuf->b_p_scriptID[ (int)options[opt_idx].indir & PV_MASK]); } #endif } else { char_u *p; p = find_termcode(key_name); if (p == NULL) { errmsg = (char_u *)N_("E846: Key code not set"); goto skip; } else (void)show_one_termcode(key_name, p, TRUE); } if (nextchar != '?' && nextchar != NUL && !vim_iswhite(afterchar)) errmsg = e_trailing; } else { if (flags & P_BOOL) /* boolean */ { if (nextchar == '=' || nextchar == ':') { errmsg = e_invarg; goto skip; } /* * ":set opt!": invert * ":set opt&": reset to default value * ":set opt<": reset to global value */ if (nextchar == '!') value = *(int *)(varp) ^ 1; else if (nextchar == '&') value = (int)(long)(long_i)options[opt_idx].def_val[ ((flags & P_VI_DEF) || cp_val) ? VI_DEFAULT : VIM_DEFAULT]; else if (nextchar == '<') { /* For 'autoread' -1 means to use global value. */ if ((int *)varp == &curbuf->b_p_ar && opt_flags == OPT_LOCAL) value = -1; else value = *(int *)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL); } else { /* * ":set invopt": invert * ":set opt" or ":set noopt": set or reset */ if (nextchar != NUL && !vim_iswhite(afterchar)) { errmsg = e_trailing; goto skip; } if (prefix == 2) /* inv */ value = *(int *)(varp) ^ 1; else value = prefix; } errmsg = set_bool_option(opt_idx, varp, (int)value, opt_flags); } else /* numeric or string */ { if (vim_strchr((char_u *)"=:&<", nextchar) == NULL || prefix != 1) { errmsg = e_invarg; goto skip; } if (flags & P_NUM) /* numeric */ { /* * Different ways to set a number option: * & set to default value * < set to global value * <xx> accept special key codes for 'wildchar' * c accept any non-digit for 'wildchar' * [-]0-9 set number * other error */ ++arg; if (nextchar == '&') value = (long)(long_i)options[opt_idx].def_val[ ((flags & P_VI_DEF) || cp_val) ? VI_DEFAULT : VIM_DEFAULT]; else if (nextchar == '<') value = *(long *)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL); else if (((long *)varp == &p_wc || (long *)varp == &p_wcm) && (*arg == '<' || *arg == '^' || ((!arg[1] || vim_iswhite(arg[1])) && !VIM_ISDIGIT(*arg)))) { value = string_to_key(arg); if (value == 0 && (long *)varp != &p_wcm) { errmsg = e_invarg; goto skip; } } /* allow negative numbers (for 'undolevels') */ else if (*arg == '-' || VIM_ISDIGIT(*arg)) { i = 0; if (*arg == '-') i = 1; #ifdef HAVE_STRTOL value = strtol((char *)arg, NULL, 0); if (arg[i] == '0' && TOLOWER_ASC(arg[i + 1]) == 'x') i += 2; #else value = atol((char *)arg); #endif while (VIM_ISDIGIT(arg[i])) ++i; if (arg[i] != NUL && !vim_iswhite(arg[i])) { errmsg = e_invarg; goto skip; } } else { errmsg = (char_u *)N_("E521: Number required after ="); goto skip; } if (adding) value = *(long *)varp + value; if (prepending) value = *(long *)varp * value; if (removing) value = *(long *)varp - value; errmsg = set_num_option(opt_idx, varp, value, errbuf, sizeof(errbuf), opt_flags); } else if (opt_idx >= 0) /* string */ { char_u *save_arg = NULL; char_u *s = NULL; char_u *oldval; /* previous value if *varp */ char_u *newval; char_u *origval; unsigned newlen; int comma; int bs; int new_value_alloced; /* new string option was allocated */ /* When using ":set opt=val" for a global option * with a local value the local value will be * reset, use the global value here. */ if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0 && ((int)options[opt_idx].indir & PV_BOTH)) varp = options[opt_idx].var; /* The old value is kept until we are sure that the * new value is valid. */ oldval = *(char_u **)varp; if (nextchar == '&') /* set to default val */ { newval = options[opt_idx].def_val[ ((flags & P_VI_DEF) || cp_val) ? VI_DEFAULT : VIM_DEFAULT]; if ((char_u **)varp == &p_bg) { /* guess the value of 'background' */ #ifdef FEAT_GUI if (gui.in_use) newval = gui_bg_default(); else #endif newval = term_bg_default(); } /* expand environment variables and ~ (since the * default value was already expanded, only * required when an environment variable was set * later */ if (newval == NULL) newval = empty_option; else { s = option_expand(opt_idx, newval); if (s == NULL) s = newval; newval = vim_strsave(s); } new_value_alloced = TRUE; } else if (nextchar == '<') /* set to global val */ { newval = vim_strsave(*(char_u **)get_varp_scope( &(options[opt_idx]), OPT_GLOBAL)); new_value_alloced = TRUE; } else { ++arg; /* jump to after the '=' or ':' */ /* * Set 'keywordprg' to ":help" if an empty * value was passed to :set by the user. * Misuse errbuf[] for the resulting string. */ if (varp == (char_u *)&p_kp && (*arg == NUL || *arg == ' ')) { STRCPY(errbuf, ":help"); save_arg = arg; arg = errbuf; } /* * Convert 'backspace' number to string, for * adding, prepending and removing string. */ else if (varp == (char_u *)&p_bs && VIM_ISDIGIT(**(char_u **)varp)) { i = getdigits((char_u **)varp); switch (i) { case 0: *(char_u **)varp = empty_option; break; case 1: *(char_u **)varp = vim_strsave( (char_u *)"indent,eol"); break; case 2: *(char_u **)varp = vim_strsave( (char_u *)"indent,eol,start"); break; } vim_free(oldval); oldval = *(char_u **)varp; } /* * Convert 'whichwrap' number to string, for * backwards compatibility with Vim 3.0. * Misuse errbuf[] for the resulting string. */ else if (varp == (char_u *)&p_ww && VIM_ISDIGIT(*arg)) { *errbuf = NUL; i = getdigits(&arg); if (i & 1) STRCAT(errbuf, "b,"); if (i & 2) STRCAT(errbuf, "s,"); if (i & 4) STRCAT(errbuf, "h,l,"); if (i & 8) STRCAT(errbuf, "<,>,"); if (i & 16) STRCAT(errbuf, "[,],"); if (*errbuf != NUL) /* remove trailing , */ errbuf[STRLEN(errbuf) - 1] = NUL; save_arg = arg; arg = errbuf; } /* * Remove '>' before 'dir' and 'bdir', for * backwards compatibility with version 3.0 */ else if ( *arg == '>' && (varp == (char_u *)&p_dir || varp == (char_u *)&p_bdir)) { ++arg; } /* When setting the local value of a global * option, the old value may be the global value. */ if (((int)options[opt_idx].indir & PV_BOTH) && (opt_flags & OPT_LOCAL)) origval = *(char_u **)get_varp( &options[opt_idx]); else origval = oldval; /* * Copy the new string into allocated memory. * Can't use set_string_option_direct(), because * we need to remove the backslashes. */ /* get a bit too much */ newlen = (unsigned)STRLEN(arg) + 1; if (adding || prepending || removing) newlen += (unsigned)STRLEN(origval) + 1; newval = alloc(newlen); if (newval == NULL) /* out of mem, don't change */ break; s = newval; /* * Copy the string, skip over escaped chars. * For MS-DOS and WIN32 backslashes before normal * file name characters are not removed, and keep * backslash at start, for "\\machine\path", but * do remove it for "\\\\machine\\path". * The reverse is found in ExpandOldSetting(). */ while (*arg && !vim_iswhite(*arg)) { if (*arg == '\\' && arg[1] != NUL #ifdef BACKSLASH_IN_FILENAME && !((flags & P_EXPAND) && vim_isfilec(arg[1]) && (arg[1] != '\\' || (s == newval && arg[2] != '\\'))) #endif ) ++arg; /* remove backslash */ #ifdef FEAT_MBYTE if (has_mbyte && (i = (*mb_ptr2len)(arg)) > 1) { /* copy multibyte char */ mch_memmove(s, arg, (size_t)i); arg += i; s += i; } else #endif *s++ = *arg++; } *s = NUL; /* * Expand environment variables and ~. * Don't do it when adding without inserting a * comma. */ if (!(adding || prepending || removing) || (flags & P_COMMA)) { s = option_expand(opt_idx, newval); if (s != NULL) { vim_free(newval); newlen = (unsigned)STRLEN(s) + 1; if (adding || prepending || removing) newlen += (unsigned)STRLEN(origval) + 1; newval = alloc(newlen); if (newval == NULL) break; STRCPY(newval, s); } } /* locate newval[] in origval[] when removing it * and when adding to avoid duplicates */ i = 0; /* init for GCC */ if (removing || (flags & P_NODUP)) { i = (int)STRLEN(newval); bs = 0; for (s = origval; *s; ++s) { if ((!(flags & P_COMMA) || s == origval || (s[-1] == ',' && !(bs & 1))) && STRNCMP(s, newval, i) == 0 && (!(flags & P_COMMA) || s[i] == ',' || s[i] == NUL)) break; /* Count backslashes. Only a comma with an * even number of backslashes before it is * recognized as a separator */ if (s > origval && s[-1] == '\\') ++bs; else bs = 0; } /* do not add if already there */ if ((adding || prepending) && *s) { prepending = FALSE; adding = FALSE; STRCPY(newval, origval); } } /* concatenate the two strings; add a ',' if * needed */ if (adding || prepending) { comma = ((flags & P_COMMA) && *origval != NUL && *newval != NUL); if (adding) { i = (int)STRLEN(origval); mch_memmove(newval + i + comma, newval, STRLEN(newval) + 1); mch_memmove(newval, origval, (size_t)i); } else { i = (int)STRLEN(newval); STRMOVE(newval + i + comma, origval); } if (comma) newval[i] = ','; } /* Remove newval[] from origval[]. (Note: "i" has * been set above and is used here). */ if (removing) { STRCPY(newval, origval); if (*s) { /* may need to remove a comma */ if (flags & P_COMMA) { if (s == origval) { /* include comma after string */ if (s[i] == ',') ++i; } else { /* include comma before string */ --s; ++i; } } STRMOVE(newval + (s - origval), s + i); } } if (flags & P_FLAGLIST) { /* Remove flags that appear twice. */ for (s = newval; *s; ++s) if ((!(flags & P_COMMA) || *s != ',') && vim_strchr(s + 1, *s) != NULL) { STRMOVE(s, s + 1); --s; } } if (save_arg != NULL) /* number for 'whichwrap' */ arg = save_arg; new_value_alloced = TRUE; } /* Set the new value. */ *(char_u **)(varp) = newval; /* Handle side effects, and set the global value for * ":set" on local options. */ errmsg = did_set_string_option(opt_idx, (char_u **)varp, new_value_alloced, oldval, errbuf, opt_flags); /* If error detected, print the error message. */ if (errmsg != NULL) goto skip; } else /* key code option */ { char_u *p; if (nextchar == '&') { if (add_termcap_entry(key_name, TRUE) == FAIL) errmsg = (char_u *)N_("E522: Not found in termcap"); } else { ++arg; /* jump to after the '=' or ':' */ for (p = arg; *p && !vim_iswhite(*p); ++p) if (*p == '\\' && p[1] != NUL) ++p; nextchar = *p; *p = NUL; add_termcode(key_name, arg, FALSE); *p = nextchar; } if (full_screen) ttest(FALSE); redraw_all_later(CLEAR); } } if (opt_idx >= 0) did_set_option(opt_idx, opt_flags, !prepending && !adding && !removing); } skip: /* * Advance to next argument. * - skip until a blank found, taking care of backslashes * - skip blanks * - skip one "=val" argument (for hidden options ":set gfn =xx") */ for (i = 0; i < 2 ; ++i) { while (*arg != NUL && !vim_iswhite(*arg)) if (*arg++ == '\\' && *arg != NUL) ++arg; arg = skipwhite(arg); if (*arg != '=') break; } } if (errmsg != NULL) { vim_strncpy(IObuff, (char_u *)_(errmsg), IOSIZE - 1); i = (int)STRLEN(IObuff) + 2; if (i + (arg - startarg) < IOSIZE) { /* append the argument with the error */ STRCAT(IObuff, ": "); mch_memmove(IObuff + i, startarg, (arg - startarg)); IObuff[i + (arg - startarg)] = NUL; } /* make sure all characters are printable */ trans_characters(IObuff, IOSIZE); ++no_wait_return; /* wait_return done later */ emsg(IObuff); /* show error highlighted */ --no_wait_return; return FAIL; } arg = skipwhite(arg); } theend: if (silent_mode && did_show) { /* After displaying option values in silent mode. */ silent_mode = FALSE; info_message = TRUE; /* use mch_msg(), not mch_errmsg() */ msg_putchar('\n'); cursor_on(); /* msg_start() switches it off */ out_flush(); silent_mode = TRUE; info_message = FALSE; /* use mch_msg(), not mch_errmsg() */ } return OK; } /* * Call this when an option has been given a new value through a user command. * Sets the P_WAS_SET flag and takes care of the P_INSECURE flag. */ static void did_set_option(opt_idx, opt_flags, new_value) int opt_idx; int opt_flags; /* possibly with OPT_MODELINE */ int new_value; /* value was replaced completely */ { long_u *p; options[opt_idx].flags |= P_WAS_SET; /* When an option is set in the sandbox, from a modeline or in secure mode * set the P_INSECURE flag. Otherwise, if a new value is stored reset the * flag. */ p = insecure_flag(opt_idx, opt_flags); if (secure #ifdef HAVE_SANDBOX || sandbox != 0 #endif || (opt_flags & OPT_MODELINE)) *p = *p | P_INSECURE; else if (new_value) *p = *p & ~P_INSECURE; } static char_u * illegal_char(errbuf, c) char_u *errbuf; int c; { if (errbuf == NULL) return (char_u *)""; sprintf((char *)errbuf, _("E539: Illegal character <%s>"), (char *)transchar(c)); return errbuf; } /* * Convert a key name or string into a key value. * Used for 'wildchar' and 'cedit' options. */ static int string_to_key(arg) char_u *arg; { if (*arg == '<') return find_key_option(arg + 1); if (*arg == '^') return Ctrl_chr(arg[1]); return *arg; } #ifdef FEAT_CMDWIN /* * Check value of 'cedit' and set cedit_key. * Returns NULL if value is OK, error message otherwise. */ static char_u * check_cedit() { int n; if (*p_cedit == NUL) cedit_key = -1; else { n = string_to_key(p_cedit); if (vim_isprintc(n)) return e_invarg; cedit_key = n; } return NULL; } #endif #ifdef FEAT_TITLE /* * When changing 'title', 'titlestring', 'icon' or 'iconstring', call * maketitle() to create and display it. * When switching the title or icon off, call mch_restore_title() to get * the old value back. */ static void did_set_title(icon) int icon; /* Did set icon instead of title */ { if (starting != NO_SCREEN #ifdef FEAT_GUI && !gui.starting #endif ) { maketitle(); if (icon) { if (!p_icon) mch_restore_title(2); } else { if (!p_title) mch_restore_title(1); } } } #endif /* * set_options_bin - called when 'bin' changes value. */ void set_options_bin(oldval, newval, opt_flags) int oldval; int newval; int opt_flags; /* OPT_LOCAL and/or OPT_GLOBAL */ { /* * The option values that are changed when 'bin' changes are * copied when 'bin is set and restored when 'bin' is reset. */ if (newval) { if (!oldval) /* switched on */ { if (!(opt_flags & OPT_GLOBAL)) { curbuf->b_p_tw_nobin = curbuf->b_p_tw; curbuf->b_p_wm_nobin = curbuf->b_p_wm; curbuf->b_p_ml_nobin = curbuf->b_p_ml; curbuf->b_p_et_nobin = curbuf->b_p_et; } if (!(opt_flags & OPT_LOCAL)) { p_tw_nobin = p_tw; p_wm_nobin = p_wm; p_ml_nobin = p_ml; p_et_nobin = p_et; } } if (!(opt_flags & OPT_GLOBAL)) { curbuf->b_p_tw = 0; /* no automatic line wrap */ curbuf->b_p_wm = 0; /* no automatic line wrap */ curbuf->b_p_ml = 0; /* no modelines */ curbuf->b_p_et = 0; /* no expandtab */ } if (!(opt_flags & OPT_LOCAL)) { p_tw = 0; p_wm = 0; p_ml = FALSE; p_et = FALSE; p_bin = TRUE; /* needed when called for the "-b" argument */ } } else if (oldval) /* switched off */ { if (!(opt_flags & OPT_GLOBAL)) { curbuf->b_p_tw = curbuf->b_p_tw_nobin; curbuf->b_p_wm = curbuf->b_p_wm_nobin; curbuf->b_p_ml = curbuf->b_p_ml_nobin; curbuf->b_p_et = curbuf->b_p_et_nobin; } if (!(opt_flags & OPT_LOCAL)) { p_tw = p_tw_nobin; p_wm = p_wm_nobin; p_ml = p_ml_nobin; p_et = p_et_nobin; } } } #ifdef FEAT_VIMINFO /* * Find the parameter represented by the given character (eg ', :, ", or /), * and return its associated value in the 'viminfo' string. * Only works for number parameters, not for 'r' or 'n'. * If the parameter is not specified in the string or there is no following * number, return -1. */ int get_viminfo_parameter(type) int type; { char_u *p; p = find_viminfo_parameter(type); if (p != NULL && VIM_ISDIGIT(*p)) return atoi((char *)p); return -1; } /* * Find the parameter represented by the given character (eg ''', ':', '"', or * '/') in the 'viminfo' option and return a pointer to the string after it. * Return NULL if the parameter is not specified in the string. */ char_u * find_viminfo_parameter(type) int type; { char_u *p; for (p = p_viminfo; *p; ++p) { if (*p == type) return p + 1; if (*p == 'n') /* 'n' is always the last one */ break; p = vim_strchr(p, ','); /* skip until next ',' */ if (p == NULL) /* hit the end without finding parameter */ break; } return NULL; } #endif /* * Expand environment variables for some string options. * These string options cannot be indirect! * If "val" is NULL expand the current value of the option. * Return pointer to NameBuff, or NULL when not expanded. */ static char_u * option_expand(opt_idx, val) int opt_idx; char_u *val; { /* if option doesn't need expansion nothing to do */ if (!(options[opt_idx].flags & P_EXPAND) || options[opt_idx].var == NULL) return NULL; /* If val is longer than MAXPATHL no meaningful expansion can be done, * expand_env() would truncate the string. */ if (val != NULL && STRLEN(val) > MAXPATHL) return NULL; if (val == NULL) val = *(char_u **)options[opt_idx].var; /* * Expanding this with NameBuff, expand_env() must not be passed IObuff. * Escape spaces when expanding 'tags', they are used to separate file * names. * For 'spellsuggest' expand after "file:". */ expand_env_esc(val, NameBuff, MAXPATHL, (char_u **)options[opt_idx].var == &p_tags, FALSE, #ifdef FEAT_SPELL (char_u **)options[opt_idx].var == &p_sps ? (char_u *)"file:" : #endif NULL); if (STRCMP(NameBuff, val) == 0) /* they are the same */ return NULL; return NameBuff; } /* * After setting various option values: recompute variables that depend on * option values. */ static void didset_options() { /* initialize the table for 'iskeyword' et.al. */ (void)init_chartab(); #ifdef FEAT_MBYTE (void)opt_strings_flags(p_cmp, p_cmp_values, &cmp_flags, TRUE); #endif (void)opt_strings_flags(p_bkc, p_bkc_values, &bkc_flags, TRUE); #ifdef FEAT_SESSION (void)opt_strings_flags(p_ssop, p_ssop_values, &ssop_flags, TRUE); (void)opt_strings_flags(p_vop, p_ssop_values, &vop_flags, TRUE); #endif #ifdef FEAT_FOLDING (void)opt_strings_flags(p_fdo, p_fdo_values, &fdo_flags, TRUE); #endif (void)opt_strings_flags(p_dy, p_dy_values, &dy_flags, TRUE); #ifdef FEAT_VIRTUALEDIT (void)opt_strings_flags(p_ve, p_ve_values, &ve_flags, TRUE); #endif #if defined(FEAT_MOUSE) && (defined(UNIX) || defined(VMS)) (void)opt_strings_flags(p_ttym, p_ttym_values, &ttym_flags, FALSE); #endif #ifdef FEAT_SPELL (void)spell_check_msm(); (void)spell_check_sps(); (void)compile_cap_prog(curwin->w_s); #endif #if defined(FEAT_TOOLBAR) && !defined(FEAT_GUI_W32) (void)opt_strings_flags(p_toolbar, p_toolbar_values, &toolbar_flags, TRUE); #endif #if defined(FEAT_TOOLBAR) && defined(FEAT_GUI_GTK) (void)opt_strings_flags(p_tbis, p_tbis_values, &tbis_flags, FALSE); #endif #ifdef FEAT_CMDWIN /* set cedit_key */ (void)check_cedit(); #endif } /* * Check for string options that are NULL (normally only termcap options). */ void check_options() { int opt_idx; for (opt_idx = 0; options[opt_idx].fullname != NULL; opt_idx++) if ((options[opt_idx].flags & P_STRING) && options[opt_idx].var != NULL) check_string_option((char_u **)get_varp(&(options[opt_idx]))); } /* * Check string options in a buffer for NULL value. */ void check_buf_options(buf) buf_T *buf; { #if defined(FEAT_QUICKFIX) check_string_option(&buf->b_p_bh); check_string_option(&buf->b_p_bt); #endif #ifdef FEAT_MBYTE check_string_option(&buf->b_p_fenc); #endif check_string_option(&buf->b_p_ff); #ifdef FEAT_FIND_ID check_string_option(&buf->b_p_def); check_string_option(&buf->b_p_inc); # ifdef FEAT_EVAL check_string_option(&buf->b_p_inex); # endif #endif #if defined(FEAT_CINDENT) && defined(FEAT_EVAL) check_string_option(&buf->b_p_inde); check_string_option(&buf->b_p_indk); #endif #if defined(FEAT_BEVAL) && defined(FEAT_EVAL) check_string_option(&buf->b_p_bexpr); #endif #if defined(FEAT_CRYPT) check_string_option(&buf->b_p_cm); #endif #if defined(FEAT_EVAL) check_string_option(&buf->b_p_fex); #endif #ifdef FEAT_CRYPT check_string_option(&buf->b_p_key); #endif check_string_option(&buf->b_p_kp); check_string_option(&buf->b_p_mps); check_string_option(&buf->b_p_fo); check_string_option(&buf->b_p_flp); check_string_option(&buf->b_p_isk); #ifdef FEAT_COMMENTS check_string_option(&buf->b_p_com); #endif #ifdef FEAT_FOLDING check_string_option(&buf->b_p_cms); #endif check_string_option(&buf->b_p_nf); #ifdef FEAT_TEXTOBJ check_string_option(&buf->b_p_qe); #endif #ifdef FEAT_SYN_HL check_string_option(&buf->b_p_syn); #endif #ifdef FEAT_SPELL check_string_option(&buf->b_s.b_p_spc); check_string_option(&buf->b_s.b_p_spf); check_string_option(&buf->b_s.b_p_spl); #endif #ifdef FEAT_SEARCHPATH check_string_option(&buf->b_p_sua); #endif #ifdef FEAT_CINDENT check_string_option(&buf->b_p_cink); check_string_option(&buf->b_p_cino); #endif #ifdef FEAT_AUTOCMD check_string_option(&buf->b_p_ft); #endif #if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT) check_string_option(&buf->b_p_cinw); #endif #ifdef FEAT_INS_EXPAND check_string_option(&buf->b_p_cpt); #endif #ifdef FEAT_COMPL_FUNC check_string_option(&buf->b_p_cfu); check_string_option(&buf->b_p_ofu); #endif #ifdef FEAT_KEYMAP check_string_option(&buf->b_p_keymap); #endif #ifdef FEAT_QUICKFIX check_string_option(&buf->b_p_gp); check_string_option(&buf->b_p_mp); check_string_option(&buf->b_p_efm); #endif check_string_option(&buf->b_p_ep); check_string_option(&buf->b_p_path); check_string_option(&buf->b_p_tags); #ifdef FEAT_INS_EXPAND check_string_option(&buf->b_p_dict); check_string_option(&buf->b_p_tsr); #endif } /* * Free the string allocated for an option. * Checks for the string being empty_option. This may happen if we're out of * memory, vim_strsave() returned NULL, which was replaced by empty_option by * check_options(). * Does NOT check for P_ALLOCED flag! */ void free_string_option(p) char_u *p; { if (p != empty_option) vim_free(p); } void clear_string_option(pp) char_u **pp; { if (*pp != empty_option) vim_free(*pp); *pp = empty_option; } static void check_string_option(pp) char_u **pp; { if (*pp == NULL) *pp = empty_option; } /* * Mark a terminal option as allocated, found by a pointer into term_strings[]. */ void set_term_option_alloced(p) char_u **p; { int opt_idx; for (opt_idx = 1; options[opt_idx].fullname != NULL; opt_idx++) if (options[opt_idx].var == (char_u *)p) { options[opt_idx].flags |= P_ALLOCED; return; } return; /* cannot happen: didn't find it! */ } #if defined(FEAT_EVAL) || defined(PROTO) /* * Return TRUE when option "opt" was set from a modeline or in secure mode. * Return FALSE when it wasn't. * Return -1 for an unknown option. */ int was_set_insecurely(opt, opt_flags) char_u *opt; int opt_flags; { int idx = findoption(opt); long_u *flagp; if (idx >= 0) { flagp = insecure_flag(idx, opt_flags); return (*flagp & P_INSECURE) != 0; } EMSG2(_(e_intern2), "was_set_insecurely()"); return -1; } /* * Get a pointer to the flags used for the P_INSECURE flag of option * "opt_idx". For some local options a local flags field is used. */ static long_u * insecure_flag(opt_idx, opt_flags) int opt_idx; int opt_flags; { if (opt_flags & OPT_LOCAL) switch ((int)options[opt_idx].indir) { #ifdef FEAT_STL_OPT case PV_STL: return &curwin->w_p_stl_flags; #endif #ifdef FEAT_EVAL # ifdef FEAT_FOLDING case PV_FDE: return &curwin->w_p_fde_flags; case PV_FDT: return &curwin->w_p_fdt_flags; # endif # ifdef FEAT_BEVAL case PV_BEXPR: return &curbuf->b_p_bexpr_flags; # endif # if defined(FEAT_CINDENT) case PV_INDE: return &curbuf->b_p_inde_flags; # endif case PV_FEX: return &curbuf->b_p_fex_flags; # ifdef FEAT_FIND_ID case PV_INEX: return &curbuf->b_p_inex_flags; # endif #endif } /* Nothing special, return global flags field. */ return &options[opt_idx].flags; } #endif #ifdef FEAT_TITLE static void redraw_titles __ARGS((void)); /* * Redraw the window title and/or tab page text later. */ static void redraw_titles() { need_maketitle = TRUE; # ifdef FEAT_WINDOWS redraw_tabline = TRUE; # endif } #endif /* * Set a string option to a new value (without checking the effect). * The string is copied into allocated memory. * if ("opt_idx" == -1) "name" is used, otherwise "opt_idx" is used. * When "set_sid" is zero set the scriptID to current_SID. When "set_sid" is * SID_NONE don't set the scriptID. Otherwise set the scriptID to "set_sid". */ void set_string_option_direct(name, opt_idx, val, opt_flags, set_sid) char_u *name; int opt_idx; char_u *val; int opt_flags; /* OPT_FREE, OPT_LOCAL and/or OPT_GLOBAL */ int set_sid UNUSED; { char_u *s; char_u **varp; int both = (opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0; int idx = opt_idx; if (idx == -1) /* use name */ { idx = findoption(name); if (idx < 0) /* not found (should not happen) */ { EMSG2(_(e_intern2), "set_string_option_direct()"); return; } } if (options[idx].var == NULL) /* can't set hidden option */ return; s = vim_strsave(val); if (s != NULL) { varp = (char_u **)get_varp_scope(&(options[idx]), both ? OPT_LOCAL : opt_flags); if ((opt_flags & OPT_FREE) && (options[idx].flags & P_ALLOCED)) free_string_option(*varp); *varp = s; /* For buffer/window local option may also set the global value. */ if (both) set_string_option_global(idx, varp); options[idx].flags |= P_ALLOCED; /* When setting both values of a global option with a local value, * make the local value empty, so that the global value is used. */ if (((int)options[idx].indir & PV_BOTH) && both) { free_string_option(*varp); *varp = empty_option; } # ifdef FEAT_EVAL if (set_sid != SID_NONE) set_option_scriptID_idx(idx, opt_flags, set_sid == 0 ? current_SID : set_sid); # endif } } /* * Set global value for string option when it's a local option. */ static void set_string_option_global(opt_idx, varp) int opt_idx; /* option index */ char_u **varp; /* pointer to option variable */ { char_u **p, *s; /* the global value is always allocated */ if (options[opt_idx].var == VAR_WIN) p = (char_u **)GLOBAL_WO(varp); else p = (char_u **)options[opt_idx].var; if (options[opt_idx].indir != PV_NONE && p != varp && (s = vim_strsave(*varp)) != NULL) { free_string_option(*p); *p = s; } } /* * Set a string option to a new value, and handle the effects. */ static void set_string_option(opt_idx, value, opt_flags) int opt_idx; char_u *value; int opt_flags; /* OPT_LOCAL and/or OPT_GLOBAL */ { char_u *s; char_u **varp; char_u *oldval; if (options[opt_idx].var == NULL) /* don't set hidden option */ return; s = vim_strsave(value); if (s != NULL) { varp = (char_u **)get_varp_scope(&(options[opt_idx]), (opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0 ? (((int)options[opt_idx].indir & PV_BOTH) ? OPT_GLOBAL : OPT_LOCAL) : opt_flags); oldval = *varp; *varp = s; if (did_set_string_option(opt_idx, varp, TRUE, oldval, NULL, opt_flags) == NULL) did_set_option(opt_idx, opt_flags, TRUE); } } /* * Handle string options that need some action to perform when changed. * Returns NULL for success, or an error message for an error. */ static char_u * did_set_string_option(opt_idx, varp, new_value_alloced, oldval, errbuf, opt_flags) int opt_idx; /* index in options[] table */ char_u **varp; /* pointer to the option variable */ int new_value_alloced; /* new value was allocated */ char_u *oldval; /* previous value of the option */ char_u *errbuf; /* buffer for errors, or NULL */ int opt_flags; /* OPT_LOCAL and/or OPT_GLOBAL */ { char_u *errmsg = NULL; char_u *s, *p; int did_chartab = FALSE; char_u **gvarp; long_u free_oldval = (options[opt_idx].flags & P_ALLOCED); #ifdef FEAT_GUI /* set when changing an option that only requires a redraw in the GUI */ int redraw_gui_only = FALSE; #endif /* Get the global option to compare with, otherwise we would have to check * two values for all local options. */ gvarp = (char_u **)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL); /* Disallow changing some options from secure mode */ if ((secure #ifdef HAVE_SANDBOX || sandbox != 0 #endif ) && (options[opt_idx].flags & P_SECURE)) { errmsg = e_secure; } /* Check for a "normal" file name in some options. Disallow a path * separator (slash and/or backslash), wildcards and characters that are * often illegal in a file name. */ else if ((options[opt_idx].flags & P_NFNAME) && vim_strpbrk(*varp, (char_u *)"/\\*?[|<>") != NULL) { errmsg = e_invarg; } /* 'term' */ else if (varp == &T_NAME) { if (T_NAME[0] == NUL) errmsg = (char_u *)N_("E529: Cannot set 'term' to empty string"); #ifdef FEAT_GUI if (gui.in_use) errmsg = (char_u *)N_("E530: Cannot change term in GUI"); else if (term_is_gui(T_NAME)) errmsg = (char_u *)N_("E531: Use \":gui\" to start the GUI"); #endif else if (set_termname(T_NAME) == FAIL) errmsg = (char_u *)N_("E522: Not found in termcap"); else /* Screen colors may have changed. */ redraw_later_clear(); } /* 'backupcopy' */ else if (varp == &p_bkc) { if (opt_strings_flags(p_bkc, p_bkc_values, &bkc_flags, TRUE) != OK) errmsg = e_invarg; if (((bkc_flags & BKC_AUTO) != 0) + ((bkc_flags & BKC_YES) != 0) + ((bkc_flags & BKC_NO) != 0) != 1) { /* Must have exactly one of "auto", "yes" and "no". */ (void)opt_strings_flags(oldval, p_bkc_values, &bkc_flags, TRUE); errmsg = e_invarg; } } /* 'backupext' and 'patchmode' */ else if (varp == &p_bex || varp == &p_pm) { if (STRCMP(*p_bex == '.' ? p_bex + 1 : p_bex, *p_pm == '.' ? p_pm + 1 : p_pm) == 0) errmsg = (char_u *)N_("E589: 'backupext' and 'patchmode' are equal"); } /* * 'isident', 'iskeyword', 'isprint or 'isfname' option: refill chartab[] * If the new option is invalid, use old value. 'lisp' option: refill * chartab[] for '-' char */ else if ( varp == &p_isi || varp == &(curbuf->b_p_isk) || varp == &p_isp || varp == &p_isf) { if (init_chartab() == FAIL) { did_chartab = TRUE; /* need to restore it below */ errmsg = e_invarg; /* error in value */ } } /* 'helpfile' */ else if (varp == &p_hf) { /* May compute new values for $VIM and $VIMRUNTIME */ if (didset_vim) { vim_setenv((char_u *)"VIM", (char_u *)""); didset_vim = FALSE; } if (didset_vimruntime) { vim_setenv((char_u *)"VIMRUNTIME", (char_u *)""); didset_vimruntime = FALSE; } } #ifdef FEAT_SYN_HL /* 'colorcolumn' */ else if (varp == &curwin->w_p_cc) errmsg = check_colorcolumn(curwin); #endif #ifdef FEAT_MULTI_LANG /* 'helplang' */ else if (varp == &p_hlg) { /* Check for "", "ab", "ab,cd", etc. */ for (s = p_hlg; *s != NUL; s += 3) { if (s[1] == NUL || ((s[2] != ',' || s[3] == NUL) && s[2] != NUL)) { errmsg = e_invarg; break; } if (s[2] == NUL) break; } } #endif /* 'highlight' */ else if (varp == &p_hl) { if (highlight_changed() == FAIL) errmsg = e_invarg; /* invalid flags */ } /* 'nrformats' */ else if (gvarp == &p_nf) { if (check_opt_strings(*varp, p_nf_values, TRUE) != OK) errmsg = e_invarg; } #ifdef FEAT_SESSION /* 'sessionoptions' */ else if (varp == &p_ssop) { if (opt_strings_flags(p_ssop, p_ssop_values, &ssop_flags, TRUE) != OK) errmsg = e_invarg; if ((ssop_flags & SSOP_CURDIR) && (ssop_flags & SSOP_SESDIR)) { /* Don't allow both "sesdir" and "curdir". */ (void)opt_strings_flags(oldval, p_ssop_values, &ssop_flags, TRUE); errmsg = e_invarg; } } /* 'viewoptions' */ else if (varp == &p_vop) { if (opt_strings_flags(p_vop, p_ssop_values, &vop_flags, TRUE) != OK) errmsg = e_invarg; } #endif /* 'scrollopt' */ #ifdef FEAT_SCROLLBIND else if (varp == &p_sbo) { if (check_opt_strings(p_sbo, p_scbopt_values, TRUE) != OK) errmsg = e_invarg; } #endif /* 'ambiwidth' */ #ifdef FEAT_MBYTE else if (varp == &p_ambw) { if (check_opt_strings(p_ambw, p_ambw_values, FALSE) != OK) errmsg = e_invarg; else if (set_chars_option(&p_lcs) != NULL) errmsg = (char_u *)_("E834: Conflicts with value of 'listchars'"); # if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING) else if (set_chars_option(&p_fcs) != NULL) errmsg = (char_u *)_("E835: Conflicts with value of 'fillchars'"); # endif } #endif /* 'background' */ else if (varp == &p_bg) { if (check_opt_strings(p_bg, p_bg_values, FALSE) == OK) { #ifdef FEAT_EVAL int dark = (*p_bg == 'd'); #endif init_highlight(FALSE, FALSE); #ifdef FEAT_EVAL if (dark != (*p_bg == 'd') && get_var_value((char_u *)"g:colors_name") != NULL) { /* The color scheme must have set 'background' back to another * value, that's not what we want here. Disable the color * scheme and set the colors again. */ do_unlet((char_u *)"g:colors_name", TRUE); free_string_option(p_bg); p_bg = vim_strsave((char_u *)(dark ? "dark" : "light")); check_string_option(&p_bg); init_highlight(FALSE, FALSE); } #endif } else errmsg = e_invarg; } /* 'wildmode' */ else if (varp == &p_wim) { if (check_opt_wim() == FAIL) errmsg = e_invarg; } #ifdef FEAT_CMDL_COMPL /* 'wildoptions' */ else if (varp == &p_wop) { if (check_opt_strings(p_wop, p_wop_values, TRUE) != OK) errmsg = e_invarg; } #endif #ifdef FEAT_WAK /* 'winaltkeys' */ else if (varp == &p_wak) { if (*p_wak == NUL || check_opt_strings(p_wak, p_wak_values, FALSE) != OK) errmsg = e_invarg; # ifdef FEAT_MENU # ifdef FEAT_GUI_MOTIF else if (gui.in_use) gui_motif_set_mnemonics(p_wak[0] == 'y' || p_wak[0] == 'm'); # else # ifdef FEAT_GUI_GTK else if (gui.in_use) gui_gtk_set_mnemonics(p_wak[0] == 'y' || p_wak[0] == 'm'); # endif # endif # endif } #endif #ifdef FEAT_AUTOCMD /* 'eventignore' */ else if (varp == &p_ei) { if (check_ei() == FAIL) errmsg = e_invarg; } #endif #ifdef FEAT_MBYTE /* 'encoding' and 'fileencoding' */ else if (varp == &p_enc || gvarp == &p_fenc || varp == &p_tenc) { if (gvarp == &p_fenc) { if (!curbuf->b_p_ma && opt_flags != OPT_GLOBAL) errmsg = e_modifiable; else if (vim_strchr(*varp, ',') != NULL) /* No comma allowed in 'fileencoding'; catches confusing it * with 'fileencodings'. */ errmsg = e_invarg; else { # ifdef FEAT_TITLE /* May show a "+" in the title now. */ redraw_titles(); # endif /* Add 'fileencoding' to the swap file. */ ml_setflags(curbuf); } } if (errmsg == NULL) { /* canonize the value, so that STRCMP() can be used on it */ p = enc_canonize(*varp); if (p != NULL) { vim_free(*varp); *varp = p; } if (varp == &p_enc) { errmsg = mb_init(); # ifdef FEAT_TITLE redraw_titles(); # endif } } # if defined(FEAT_GUI_GTK) if (errmsg == NULL && varp == &p_tenc && gui.in_use) { /* GTK+ 2 uses only a single encoding, and that is UTF-8. */ if (STRCMP(p_tenc, "utf-8") != 0) errmsg = (char_u *)N_("E617: Cannot be changed in the GTK+ 2 GUI"); } # endif if (errmsg == NULL) { # ifdef FEAT_KEYMAP /* When 'keymap' is used and 'encoding' changes, reload the keymap * (with another encoding). */ if (varp == &p_enc && *curbuf->b_p_keymap != NUL) (void)keymap_init(); # endif /* When 'termencoding' is not empty and 'encoding' changes or when * 'termencoding' changes, need to setup for keyboard input and * display output conversion. */ if (((varp == &p_enc && *p_tenc != NUL) || varp == &p_tenc)) { convert_setup(&input_conv, p_tenc, p_enc); convert_setup(&output_conv, p_enc, p_tenc); } # if defined(WIN3264) && defined(FEAT_MBYTE) /* $HOME may have characters in active code page. */ if (varp == &p_enc) init_homedir(); # endif } } #endif #if defined(FEAT_POSTSCRIPT) else if (varp == &p_penc) { /* Canonize printencoding if VIM standard one */ p = enc_canonize(p_penc); if (p != NULL) { vim_free(p_penc); p_penc = p; } else { /* Ensure lower case and '-' for '_' */ for (s = p_penc; *s != NUL; s++) { if (*s == '_') *s = '-'; else *s = TOLOWER_ASC(*s); } } } #endif #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK) else if (varp == &p_imak) { if (gui.in_use && !im_xim_isvalid_imactivate()) errmsg = e_invarg; } #endif #ifdef FEAT_KEYMAP else if (varp == &curbuf->b_p_keymap) { /* load or unload key mapping tables */ errmsg = keymap_init(); if (errmsg == NULL) { if (*curbuf->b_p_keymap != NUL) { /* Installed a new keymap, switch on using it. */ curbuf->b_p_iminsert = B_IMODE_LMAP; if (curbuf->b_p_imsearch != B_IMODE_USE_INSERT) curbuf->b_p_imsearch = B_IMODE_LMAP; } else { /* Cleared the keymap, may reset 'iminsert' and 'imsearch'. */ if (curbuf->b_p_iminsert == B_IMODE_LMAP) curbuf->b_p_iminsert = B_IMODE_NONE; if (curbuf->b_p_imsearch == B_IMODE_LMAP) curbuf->b_p_imsearch = B_IMODE_USE_INSERT; } if ((opt_flags & OPT_LOCAL) == 0) { set_iminsert_global(); set_imsearch_global(); } # ifdef FEAT_WINDOWS status_redraw_curbuf(); # endif } } #endif /* 'fileformat' */ else if (gvarp == &p_ff) { if (!curbuf->b_p_ma && !(opt_flags & OPT_GLOBAL)) errmsg = e_modifiable; else if (check_opt_strings(*varp, p_ff_values, FALSE) != OK) errmsg = e_invarg; else { /* may also change 'textmode' */ if (get_fileformat(curbuf) == EOL_DOS) curbuf->b_p_tx = TRUE; else curbuf->b_p_tx = FALSE; #ifdef FEAT_TITLE redraw_titles(); #endif /* update flag in swap file */ ml_setflags(curbuf); /* Redraw needed when switching to/from "mac": a CR in the text * will be displayed differently. */ if (get_fileformat(curbuf) == EOL_MAC || *oldval == 'm') redraw_curbuf_later(NOT_VALID); } } /* 'fileformats' */ else if (varp == &p_ffs) { if (check_opt_strings(p_ffs, p_ff_values, TRUE) != OK) errmsg = e_invarg; else { /* also change 'textauto' */ if (*p_ffs == NUL) p_ta = FALSE; else p_ta = TRUE; } } #if defined(FEAT_CRYPT) /* 'cryptkey' */ else if (gvarp == &p_key) { # if defined(FEAT_CMDHIST) /* Make sure the ":set" command doesn't show the new value in the * history. */ remove_key_from_history(); # endif if (STRCMP(curbuf->b_p_key, oldval) != 0) /* Need to update the swapfile. */ ml_set_crypt_key(curbuf, oldval, get_crypt_method(curbuf)); } else if (gvarp == &p_cm) { if (opt_flags & OPT_LOCAL) p = curbuf->b_p_cm; else p = p_cm; if (check_opt_strings(p, p_cm_values, TRUE) != OK) errmsg = e_invarg; else if (get_crypt_method(curbuf) > 0 && blowfish_self_test() == FAIL) errmsg = e_invarg; else { /* When setting the global value to empty, make it "zip". */ if (*p_cm == NUL) { if (new_value_alloced) free_string_option(p_cm); p_cm = vim_strsave((char_u *)"zip"); new_value_alloced = TRUE; } /* Need to update the swapfile when the effective method changed. * Set "s" to the effective old value, "p" to the effective new * method and compare. */ if ((opt_flags & OPT_LOCAL) && *oldval == NUL) s = p_cm; /* was previously using the global value */ else s = oldval; if (*curbuf->b_p_cm == NUL) p = p_cm; /* is now using the global value */ else p = curbuf->b_p_cm; if (STRCMP(s, p) != 0) ml_set_crypt_key(curbuf, curbuf->b_p_key, crypt_method_from_string(s)); /* If the global value changes need to update the swapfile for all * buffers using that value. */ if ((opt_flags & OPT_GLOBAL) && STRCMP(p_cm, oldval) != 0) { buf_T *buf; for (buf = firstbuf; buf != NULL; buf = buf->b_next) if (buf != curbuf && *buf->b_p_cm == NUL) ml_set_crypt_key(buf, buf->b_p_key, crypt_method_from_string(oldval)); } } } #endif /* 'matchpairs' */ else if (gvarp == &p_mps) { /* Check for "x:y,x:y" */ for (p = *varp; *p != NUL; p += 4) { if (p[1] != ':' || p[2] == NUL || (p[3] != NUL && p[3] != ',')) { errmsg = e_invarg; break; } if (p[3] == NUL) break; } } #ifdef FEAT_COMMENTS /* 'comments' */ else if (gvarp == &p_com) { for (s = *varp; *s; ) { while (*s && *s != ':') { if (vim_strchr((char_u *)COM_ALL, *s) == NULL && !VIM_ISDIGIT(*s) && *s != '-') { errmsg = illegal_char(errbuf, *s); break; } ++s; } if (*s++ == NUL) errmsg = (char_u *)N_("E524: Missing colon"); else if (*s == ',' || *s == NUL) errmsg = (char_u *)N_("E525: Zero length string"); if (errmsg != NULL) break; while (*s && *s != ',') { if (*s == '\\' && s[1] != NUL) ++s; ++s; } s = skip_to_option_part(s); } } #endif /* 'listchars' */ else if (varp == &p_lcs) { errmsg = set_chars_option(varp); } #if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING) /* 'fillchars' */ else if (varp == &p_fcs) { errmsg = set_chars_option(varp); } #endif #ifdef FEAT_CMDWIN /* 'cedit' */ else if (varp == &p_cedit) { errmsg = check_cedit(); } #endif /* 'verbosefile' */ else if (varp == &p_vfile) { verbose_stop(); if (*p_vfile != NUL && verbose_open() == FAIL) errmsg = e_invarg; } #ifdef FEAT_VIMINFO /* 'viminfo' */ else if (varp == &p_viminfo) { for (s = p_viminfo; *s;) { /* Check it's a valid character */ if (vim_strchr((char_u *)"!\"%'/:<@cfhnrs", *s) == NULL) { errmsg = illegal_char(errbuf, *s); break; } if (*s == 'n') /* name is always last one */ { break; } else if (*s == 'r') /* skip until next ',' */ { while (*++s && *s != ',') ; } else if (*s == '%') { /* optional number */ while (vim_isdigit(*++s)) ; } else if (*s == '!' || *s == 'h' || *s == 'c') ++s; /* no extra chars */ else /* must have a number */ { while (vim_isdigit(*++s)) ; if (!VIM_ISDIGIT(*(s - 1))) { if (errbuf != NULL) { sprintf((char *)errbuf, _("E526: Missing number after <%s>"), transchar_byte(*(s - 1))); errmsg = errbuf; } else errmsg = (char_u *)""; break; } } if (*s == ',') ++s; else if (*s) { if (errbuf != NULL) errmsg = (char_u *)N_("E527: Missing comma"); else errmsg = (char_u *)""; break; } } if (*p_viminfo && errmsg == NULL && get_viminfo_parameter('\'') < 0) errmsg = (char_u *)N_("E528: Must specify a ' value"); } #endif /* FEAT_VIMINFO */ /* terminal options */ else if (istermoption(&options[opt_idx]) && full_screen) { /* ":set t_Co=0" and ":set t_Co=1" do ":set t_Co=" */ if (varp == &T_CCO) { int colors = atoi((char *)T_CCO); /* Only reinitialize colors if t_Co value has really changed to * avoid expensive reload of colorscheme if t_Co is set to the * same value multiple times. */ if (colors != t_colors) { t_colors = colors; if (t_colors <= 1) { if (new_value_alloced) vim_free(T_CCO); T_CCO = empty_option; } /* We now have a different color setup, initialize it again. */ init_highlight(TRUE, FALSE); } } ttest(FALSE); if (varp == &T_ME) { out_str(T_ME); redraw_later(CLEAR); #if defined(MSDOS) || (defined(WIN3264) && !defined(FEAT_GUI_W32)) /* Since t_me has been set, this probably means that the user * wants to use this as default colors. Need to reset default * background/foreground colors. */ mch_set_normal_colors(); #endif } } #ifdef FEAT_LINEBREAK /* 'showbreak' */ else if (varp == &p_sbr) { for (s = p_sbr; *s; ) { if (ptr2cells(s) != 1) errmsg = (char_u *)N_("E595: contains unprintable or wide character"); mb_ptr_adv(s); } } #endif #ifdef FEAT_GUI /* 'guifont' */ else if (varp == &p_guifont) { if (gui.in_use) { p = p_guifont; # if defined(FEAT_GUI_GTK) /* * Put up a font dialog and let the user select a new value. * If this is cancelled go back to the old value but don't * give an error message. */ if (STRCMP(p, "*") == 0) { p = gui_mch_font_dialog(oldval); if (new_value_alloced) free_string_option(p_guifont); p_guifont = (p != NULL) ? p : vim_strsave(oldval); new_value_alloced = TRUE; } # endif if (p != NULL && gui_init_font(p_guifont, FALSE) != OK) { # if defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_PHOTON) if (STRCMP(p_guifont, "*") == 0) { /* Dialog was cancelled: Keep the old value without giving * an error message. */ if (new_value_alloced) free_string_option(p_guifont); p_guifont = vim_strsave(oldval); new_value_alloced = TRUE; } else # endif errmsg = (char_u *)N_("E596: Invalid font(s)"); } } redraw_gui_only = TRUE; } # ifdef FEAT_XFONTSET else if (varp == &p_guifontset) { if (STRCMP(p_guifontset, "*") == 0) errmsg = (char_u *)N_("E597: can't select fontset"); else if (gui.in_use && gui_init_font(p_guifontset, TRUE) != OK) errmsg = (char_u *)N_("E598: Invalid fontset"); redraw_gui_only = TRUE; } # endif # ifdef FEAT_MBYTE else if (varp == &p_guifontwide) { if (STRCMP(p_guifontwide, "*") == 0) errmsg = (char_u *)N_("E533: can't select wide font"); else if (gui_get_wide_font() == FAIL) errmsg = (char_u *)N_("E534: Invalid wide font"); redraw_gui_only = TRUE; } # endif #endif #ifdef CURSOR_SHAPE /* 'guicursor' */ else if (varp == &p_guicursor) errmsg = parse_shape_opt(SHAPE_CURSOR); #endif #ifdef FEAT_MOUSESHAPE /* 'mouseshape' */ else if (varp == &p_mouseshape) { errmsg = parse_shape_opt(SHAPE_MOUSE); update_mouseshape(-1); } #endif #ifdef FEAT_PRINTER else if (varp == &p_popt) errmsg = parse_printoptions(); # if defined(FEAT_MBYTE) && defined(FEAT_POSTSCRIPT) else if (varp == &p_pmfn) errmsg = parse_printmbfont(); # endif #endif #ifdef FEAT_LANGMAP /* 'langmap' */ else if (varp == &p_langmap) langmap_set(); #endif #ifdef FEAT_LINEBREAK /* 'breakat' */ else if (varp == &p_breakat) fill_breakat_flags(); #endif #ifdef FEAT_TITLE /* 'titlestring' and 'iconstring' */ else if (varp == &p_titlestring || varp == &p_iconstring) { # ifdef FEAT_STL_OPT int flagval = (varp == &p_titlestring) ? STL_IN_TITLE : STL_IN_ICON; /* NULL => statusline syntax */ if (vim_strchr(*varp, '%') && check_stl_option(*varp) == NULL) stl_syntax |= flagval; else stl_syntax &= ~flagval; # endif did_set_title(varp == &p_iconstring); } #endif #ifdef FEAT_GUI /* 'guioptions' */ else if (varp == &p_go) { gui_init_which_components(oldval); redraw_gui_only = TRUE; } #endif #if defined(FEAT_GUI_TABLINE) /* 'guitablabel' */ else if (varp == &p_gtl) { redraw_tabline = TRUE; redraw_gui_only = TRUE; } /* 'guitabtooltip' */ else if (varp == &p_gtt) { redraw_gui_only = TRUE; } #endif #if defined(FEAT_MOUSE_TTY) && (defined(UNIX) || defined(VMS)) /* 'ttymouse' */ else if (varp == &p_ttym) { /* Switch the mouse off before changing the escape sequences used for * that. */ mch_setmouse(FALSE); if (opt_strings_flags(p_ttym, p_ttym_values, &ttym_flags, FALSE) != OK) errmsg = e_invarg; else check_mouse_termcode(); if (termcap_active) setmouse(); /* may switch it on again */ } #endif #ifdef FEAT_VISUAL /* 'selection' */ else if (varp == &p_sel) { if (*p_sel == NUL || check_opt_strings(p_sel, p_sel_values, FALSE) != OK) errmsg = e_invarg; } /* 'selectmode' */ else if (varp == &p_slm) { if (check_opt_strings(p_slm, p_slm_values, TRUE) != OK) errmsg = e_invarg; } #endif #ifdef FEAT_BROWSE /* 'browsedir' */ else if (varp == &p_bsdir) { if (check_opt_strings(p_bsdir, p_bsdir_values, FALSE) != OK && !mch_isdir(p_bsdir)) errmsg = e_invarg; } #endif #ifdef FEAT_VISUAL /* 'keymodel' */ else if (varp == &p_km) { if (check_opt_strings(p_km, p_km_values, TRUE) != OK) errmsg = e_invarg; else { km_stopsel = (vim_strchr(p_km, 'o') != NULL); km_startsel = (vim_strchr(p_km, 'a') != NULL); } } #endif /* 'mousemodel' */ else if (varp == &p_mousem) { if (check_opt_strings(p_mousem, p_mousem_values, FALSE) != OK) errmsg = e_invarg; #if defined(FEAT_GUI_MOTIF) && defined(FEAT_MENU) && (XmVersion <= 1002) else if (*p_mousem != *oldval) /* Changed from "extend" to "popup" or "popup_setpos" or vv: need * to create or delete the popup menus. */ gui_motif_update_mousemodel(root_menu); #endif } /* 'switchbuf' */ else if (varp == &p_swb) { if (opt_strings_flags(p_swb, p_swb_values, &swb_flags, TRUE) != OK) errmsg = e_invarg; } /* 'debug' */ else if (varp == &p_debug) { if (check_opt_strings(p_debug, p_debug_values, TRUE) != OK) errmsg = e_invarg; } /* 'display' */ else if (varp == &p_dy) { if (opt_strings_flags(p_dy, p_dy_values, &dy_flags, TRUE) != OK) errmsg = e_invarg; else (void)init_chartab(); } #ifdef FEAT_VERTSPLIT /* 'eadirection' */ else if (varp == &p_ead) { if (check_opt_strings(p_ead, p_ead_values, FALSE) != OK) errmsg = e_invarg; } #endif #ifdef FEAT_CLIPBOARD /* 'clipboard' */ else if (varp == &p_cb) errmsg = check_clipboard_option(); #endif #ifdef FEAT_SPELL /* When 'spelllang' or 'spellfile' is set and there is a window for this * buffer in which 'spell' is set load the wordlists. */ else if (varp == &(curbuf->b_s.b_p_spl) || varp == &(curbuf->b_s.b_p_spf)) { win_T *wp; int l; if (varp == &(curbuf->b_s.b_p_spf)) { l = (int)STRLEN(curbuf->b_s.b_p_spf); if (l > 0 && (l < 4 || STRCMP(curbuf->b_s.b_p_spf + l - 4, ".add") != 0)) errmsg = e_invarg; } if (errmsg == NULL) { FOR_ALL_WINDOWS(wp) if (wp->w_buffer == curbuf && wp->w_p_spell) { errmsg = did_set_spelllang(wp); # ifdef FEAT_WINDOWS break; # endif } } } /* When 'spellcapcheck' is set compile the regexp program. */ else if (varp == &(curwin->w_s->b_p_spc)) { errmsg = compile_cap_prog(curwin->w_s); } /* 'spellsuggest' */ else if (varp == &p_sps) { if (spell_check_sps() != OK) errmsg = e_invarg; } /* 'mkspellmem' */ else if (varp == &p_msm) { if (spell_check_msm() != OK) errmsg = e_invarg; } #endif #ifdef FEAT_QUICKFIX /* When 'bufhidden' is set, check for valid value. */ else if (gvarp == &p_bh) { if (check_opt_strings(curbuf->b_p_bh, p_bufhidden_values, FALSE) != OK) errmsg = e_invarg; } /* When 'buftype' is set, check for valid value. */ else if (gvarp == &p_bt) { if (check_opt_strings(curbuf->b_p_bt, p_buftype_values, FALSE) != OK) errmsg = e_invarg; else { # ifdef FEAT_WINDOWS if (curwin->w_status_height) { curwin->w_redr_status = TRUE; redraw_later(VALID); } # endif curbuf->b_help = (curbuf->b_p_bt[0] == 'h'); # ifdef FEAT_TITLE redraw_titles(); # endif } } #endif #ifdef FEAT_STL_OPT /* 'statusline' or 'rulerformat' */ else if (gvarp == &p_stl || varp == &p_ruf) { int wid; if (varp == &p_ruf) /* reset ru_wid first */ ru_wid = 0; s = *varp; if (varp == &p_ruf && *s == '%') { /* set ru_wid if 'ruf' starts with "%99(" */ if (*++s == '-') /* ignore a '-' */ s++; wid = getdigits(&s); if (wid && *s == '(' && (errmsg = check_stl_option(p_ruf)) == NULL) ru_wid = wid; else errmsg = check_stl_option(p_ruf); } /* check 'statusline' only if it doesn't start with "%!" */ else if (varp == &p_ruf || s[0] != '%' || s[1] != '!') errmsg = check_stl_option(s); if (varp == &p_ruf && errmsg == NULL) comp_col(); } #endif #ifdef FEAT_INS_EXPAND /* check if it is a valid value for 'complete' -- Acevedo */ else if (gvarp == &p_cpt) { for (s = *varp; *s;) { while(*s == ',' || *s == ' ') s++; if (!*s) break; if (vim_strchr((char_u *)".wbuksid]tU", *s) == NULL) { errmsg = illegal_char(errbuf, *s); break; } if (*++s != NUL && *s != ',' && *s != ' ') { if (s[-1] == 'k' || s[-1] == 's') { /* skip optional filename after 'k' and 's' */ while (*s && *s != ',' && *s != ' ') { if (*s == '\\') ++s; ++s; } } else { if (errbuf != NULL) { sprintf((char *)errbuf, _("E535: Illegal character after <%c>"), *--s); errmsg = errbuf; } else errmsg = (char_u *)""; break; } } } } /* 'completeopt' */ else if (varp == &p_cot) { if (check_opt_strings(p_cot, p_cot_values, TRUE) != OK) errmsg = e_invarg; } #endif /* FEAT_INS_EXPAND */ #if defined(FEAT_TOOLBAR) && !defined(FEAT_GUI_W32) else if (varp == &p_toolbar) { if (opt_strings_flags(p_toolbar, p_toolbar_values, &toolbar_flags, TRUE) != OK) errmsg = e_invarg; else { out_flush(); gui_mch_show_toolbar((toolbar_flags & (TOOLBAR_TEXT | TOOLBAR_ICONS)) != 0); } } #endif #if defined(FEAT_TOOLBAR) && defined(FEAT_GUI_GTK) /* 'toolbariconsize': GTK+ 2 only */ else if (varp == &p_tbis) { if (opt_strings_flags(p_tbis, p_tbis_values, &tbis_flags, FALSE) != OK) errmsg = e_invarg; else { out_flush(); gui_mch_show_toolbar((toolbar_flags & (TOOLBAR_TEXT | TOOLBAR_ICONS)) != 0); } } #endif /* 'pastetoggle': translate key codes like in a mapping */ else if (varp == &p_pt) { if (*p_pt) { (void)replace_termcodes(p_pt, &p, TRUE, TRUE, FALSE); if (p != NULL) { if (new_value_alloced) free_string_option(p_pt); p_pt = p; new_value_alloced = TRUE; } } } /* 'backspace' */ else if (varp == &p_bs) { if (VIM_ISDIGIT(*p_bs)) { if (*p_bs >'2' || p_bs[1] != NUL) errmsg = e_invarg; } else if (check_opt_strings(p_bs, p_bs_values, TRUE) != OK) errmsg = e_invarg; } #ifdef FEAT_MBYTE /* 'casemap' */ else if (varp == &p_cmp) { if (opt_strings_flags(p_cmp, p_cmp_values, &cmp_flags, TRUE) != OK) errmsg = e_invarg; } #endif #ifdef FEAT_DIFF /* 'diffopt' */ else if (varp == &p_dip) { if (diffopt_changed() == FAIL) errmsg = e_invarg; } #endif #ifdef FEAT_FOLDING /* 'foldmethod' */ else if (gvarp == &curwin->w_allbuf_opt.wo_fdm) { if (check_opt_strings(*varp, p_fdm_values, FALSE) != OK || *curwin->w_p_fdm == NUL) errmsg = e_invarg; else { foldUpdateAll(curwin); if (foldmethodIsDiff(curwin)) newFoldLevel(); } } # ifdef FEAT_EVAL /* 'foldexpr' */ else if (varp == &curwin->w_p_fde) { if (foldmethodIsExpr(curwin)) foldUpdateAll(curwin); } # endif /* 'foldmarker' */ else if (gvarp == &curwin->w_allbuf_opt.wo_fmr) { p = vim_strchr(*varp, ','); if (p == NULL) errmsg = (char_u *)N_("E536: comma required"); else if (p == *varp || p[1] == NUL) errmsg = e_invarg; else if (foldmethodIsMarker(curwin)) foldUpdateAll(curwin); } /* 'commentstring' */ else if (gvarp == &p_cms) { if (**varp != NUL && strstr((char *)*varp, "%s") == NULL) errmsg = (char_u *)N_("E537: 'commentstring' must be empty or contain %s"); } /* 'foldopen' */ else if (varp == &p_fdo) { if (opt_strings_flags(p_fdo, p_fdo_values, &fdo_flags, TRUE) != OK) errmsg = e_invarg; } /* 'foldclose' */ else if (varp == &p_fcl) { if (check_opt_strings(p_fcl, p_fcl_values, TRUE) != OK) errmsg = e_invarg; } /* 'foldignore' */ else if (gvarp == &curwin->w_allbuf_opt.wo_fdi) { if (foldmethodIsIndent(curwin)) foldUpdateAll(curwin); } #endif #ifdef FEAT_VIRTUALEDIT /* 'virtualedit' */ else if (varp == &p_ve) { if (opt_strings_flags(p_ve, p_ve_values, &ve_flags, TRUE) != OK) errmsg = e_invarg; else if (STRCMP(p_ve, oldval) != 0) { /* Recompute cursor position in case the new 've' setting * changes something. */ validate_virtcol(); coladvance(curwin->w_virtcol); } } #endif #if defined(FEAT_CSCOPE) && defined(FEAT_QUICKFIX) else if (varp == &p_csqf) { if (p_csqf != NULL) { p = p_csqf; while (*p != NUL) { if (vim_strchr((char_u *)CSQF_CMDS, *p) == NULL || p[1] == NUL || vim_strchr((char_u *)CSQF_FLAGS, p[1]) == NULL || (p[2] != NUL && p[2] != ',')) { errmsg = e_invarg; break; } else if (p[2] == NUL) break; else p += 3; } } } #endif /* Options that are a list of flags. */ else { p = NULL; if (varp == &p_ww) p = (char_u *)WW_ALL; if (varp == &p_shm) p = (char_u *)SHM_ALL; else if (varp == &(p_cpo)) p = (char_u *)CPO_ALL; else if (varp == &(curbuf->b_p_fo)) p = (char_u *)FO_ALL; #ifdef FEAT_CONCEAL else if (varp == &curwin->w_p_cocu) p = (char_u *)COCU_ALL; #endif else if (varp == &p_mouse) { #ifdef FEAT_MOUSE p = (char_u *)MOUSE_ALL; #else if (*p_mouse != NUL) errmsg = (char_u *)N_("E538: No mouse support"); #endif } #if defined(FEAT_GUI) else if (varp == &p_go) p = (char_u *)GO_ALL; #endif if (p != NULL) { for (s = *varp; *s; ++s) if (vim_strchr(p, *s) == NULL) { errmsg = illegal_char(errbuf, *s); break; } } } /* * If error detected, restore the previous value. */ if (errmsg != NULL) { if (new_value_alloced) free_string_option(*varp); *varp = oldval; /* * When resetting some values, need to act on it. */ if (did_chartab) (void)init_chartab(); if (varp == &p_hl) (void)highlight_changed(); } else { #ifdef FEAT_EVAL /* Remember where the option was set. */ set_option_scriptID_idx(opt_idx, opt_flags, current_SID); #endif /* * Free string options that are in allocated memory. * Use "free_oldval", because recursiveness may change the flags under * our fingers (esp. init_highlight()). */ if (free_oldval) free_string_option(oldval); if (new_value_alloced) options[opt_idx].flags |= P_ALLOCED; else options[opt_idx].flags &= ~P_ALLOCED; if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0 && ((int)options[opt_idx].indir & PV_BOTH)) { /* global option with local value set to use global value; free * the local value and make it empty */ p = get_varp_scope(&(options[opt_idx]), OPT_LOCAL); free_string_option(*(char_u **)p); *(char_u **)p = empty_option; } /* May set global value for local option. */ else if (!(opt_flags & OPT_LOCAL) && opt_flags != OPT_GLOBAL) set_string_option_global(opt_idx, varp); #ifdef FEAT_AUTOCMD /* * Trigger the autocommand only after setting the flags. */ # ifdef FEAT_SYN_HL /* When 'syntax' is set, load the syntax of that name */ if (varp == &(curbuf->b_p_syn)) { apply_autocmds(EVENT_SYNTAX, curbuf->b_p_syn, curbuf->b_fname, TRUE, curbuf); } # endif else if (varp == &(curbuf->b_p_ft)) { /* 'filetype' is set, trigger the FileType autocommand */ did_filetype = TRUE; apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname, TRUE, curbuf); } #endif #ifdef FEAT_SPELL if (varp == &(curwin->w_s->b_p_spl)) { char_u fname[200]; /* * Source the spell/LANG.vim in 'runtimepath'. * They could set 'spellcapcheck' depending on the language. * Use the first name in 'spelllang' up to '_region' or * '.encoding'. */ for (p = curwin->w_s->b_p_spl; *p != NUL; ++p) if (vim_strchr((char_u *)"_.,", *p) != NULL) break; vim_snprintf((char *)fname, 200, "spell/%.*s.vim", (int)(p - curwin->w_s->b_p_spl), curwin->w_s->b_p_spl); source_runtime(fname, TRUE); } #endif } #ifdef FEAT_MOUSE if (varp == &p_mouse) { # ifdef FEAT_MOUSE_TTY if (*p_mouse == NUL) mch_setmouse(FALSE); /* switch mouse off */ else # endif setmouse(); /* in case 'mouse' changed */ } #endif if (curwin->w_curswant != MAXCOL && (options[opt_idx].flags & (P_CURSWANT | P_RCLR)) != 0) curwin->w_set_curswant = TRUE; #ifdef FEAT_GUI /* check redraw when it's not a GUI option or the GUI is active. */ if (!redraw_gui_only || gui.in_use) #endif check_redraw(options[opt_idx].flags); return errmsg; } #ifdef FEAT_SYN_HL /* * Simple int comparison function for use with qsort() */ static int int_cmp(a, b) const void *a; const void *b; { return *(const int *)a - *(const int *)b; } /* * Handle setting 'colorcolumn' or 'textwidth' in window "wp". * Returns error message, NULL if it's OK. */ char_u * check_colorcolumn(wp) win_T *wp; { char_u *s; int col; int count = 0; int color_cols[256]; int i; int j = 0; if (wp->w_buffer == NULL) return NULL; /* buffer was closed */ for (s = wp->w_p_cc; *s != NUL && count < 255;) { if (*s == '-' || *s == '+') { /* -N and +N: add to 'textwidth' */ col = (*s == '-') ? -1 : 1; ++s; if (!VIM_ISDIGIT(*s)) return e_invarg; col = col * getdigits(&s); if (wp->w_buffer->b_p_tw == 0) goto skip; /* 'textwidth' not set, skip this item */ col += wp->w_buffer->b_p_tw; if (col < 0) goto skip; } else if (VIM_ISDIGIT(*s)) col = getdigits(&s); else return e_invarg; color_cols[count++] = col - 1; /* 1-based to 0-based */ skip: if (*s == NUL) break; if (*s != ',') return e_invarg; if (*++s == NUL) return e_invarg; /* illegal trailing comma as in "set cc=80," */ } vim_free(wp->w_p_cc_cols); if (count == 0) wp->w_p_cc_cols = NULL; else { wp->w_p_cc_cols = (int *)alloc((unsigned)sizeof(int) * (count + 1)); if (wp->w_p_cc_cols != NULL) { /* sort the columns for faster usage on screen redraw inside * win_line() */ qsort(color_cols, count, sizeof(int), int_cmp); for (i = 0; i < count; ++i) /* skip duplicates */ if (j == 0 || wp->w_p_cc_cols[j - 1] != color_cols[i]) wp->w_p_cc_cols[j++] = color_cols[i]; wp->w_p_cc_cols[j] = -1; /* end marker */ } } return NULL; /* no error */ } #endif /* * Handle setting 'listchars' or 'fillchars'. * Returns error message, NULL if it's OK. */ static char_u * set_chars_option(varp) char_u **varp; { int round, i, len, entries; char_u *p, *s; int c1, c2 = 0; struct charstab { int *cp; char *name; }; #if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING) static struct charstab filltab[] = { {&fill_stl, "stl"}, {&fill_stlnc, "stlnc"}, {&fill_vert, "vert"}, {&fill_fold, "fold"}, {&fill_diff, "diff"}, }; #endif static struct charstab lcstab[] = { {&lcs_eol, "eol"}, {&lcs_ext, "extends"}, {&lcs_nbsp, "nbsp"}, {&lcs_prec, "precedes"}, {&lcs_tab2, "tab"}, {&lcs_trail, "trail"}, #ifdef FEAT_CONCEAL {&lcs_conceal, "conceal"}, #else {NULL, "conceal"}, #endif }; struct charstab *tab; #if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING) if (varp == &p_lcs) #endif { tab = lcstab; entries = sizeof(lcstab) / sizeof(struct charstab); } #if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING) else { tab = filltab; entries = sizeof(filltab) / sizeof(struct charstab); } #endif /* first round: check for valid value, second round: assign values */ for (round = 0; round <= 1; ++round) { if (round > 0) { /* After checking that the value is valid: set defaults: space for * 'fillchars', NUL for 'listchars' */ for (i = 0; i < entries; ++i) if (tab[i].cp != NULL) *(tab[i].cp) = (varp == &p_lcs ? NUL : ' '); if (varp == &p_lcs) lcs_tab1 = NUL; #if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING) else fill_diff = '-'; #endif } p = *varp; while (*p) { for (i = 0; i < entries; ++i) { len = (int)STRLEN(tab[i].name); if (STRNCMP(p, tab[i].name, len) == 0 && p[len] == ':' && p[len + 1] != NUL) { s = p + len + 1; #ifdef FEAT_MBYTE c1 = mb_ptr2char_adv(&s); if (mb_char2cells(c1) > 1) continue; #else c1 = *s++; #endif if (tab[i].cp == &lcs_tab2) { if (*s == NUL) continue; #ifdef FEAT_MBYTE c2 = mb_ptr2char_adv(&s); if (mb_char2cells(c2) > 1) continue; #else c2 = *s++; #endif } if (*s == ',' || *s == NUL) { if (round) { if (tab[i].cp == &lcs_tab2) { lcs_tab1 = c1; lcs_tab2 = c2; } else if (tab[i].cp != NULL) *(tab[i].cp) = c1; } p = s; break; } } } if (i == entries) return e_invarg; if (*p == ',') ++p; } } return NULL; /* no error */ } #ifdef FEAT_STL_OPT /* * Check validity of options with the 'statusline' format. * Return error message or NULL. */ char_u * check_stl_option(s) char_u *s; { int itemcnt = 0; int groupdepth = 0; static char_u errbuf[80]; while (*s && itemcnt < STL_MAX_ITEM) { /* Check for valid keys after % sequences */ while (*s && *s != '%') s++; if (!*s) break; s++; if (*s != '%' && *s != ')') ++itemcnt; if (*s == '%' || *s == STL_TRUNCMARK || *s == STL_MIDDLEMARK) { s++; continue; } if (*s == ')') { s++; if (--groupdepth < 0) break; continue; } if (*s == '-') s++; while (VIM_ISDIGIT(*s)) s++; if (*s == STL_USER_HL) continue; if (*s == '.') { s++; while (*s && VIM_ISDIGIT(*s)) s++; } if (*s == '(') { groupdepth++; continue; } if (vim_strchr(STL_ALL, *s) == NULL) { return illegal_char(errbuf, *s); } if (*s == '{') { s++; while (*s != '}' && *s) s++; if (*s != '}') return (char_u *)N_("E540: Unclosed expression sequence"); } } if (itemcnt >= STL_MAX_ITEM) return (char_u *)N_("E541: too many items"); if (groupdepth != 0) return (char_u *)N_("E542: unbalanced groups"); return NULL; } #endif #ifdef FEAT_CLIPBOARD /* * Extract the items in the 'clipboard' option and set global values. */ static char_u * check_clipboard_option() { int new_unnamed = 0; int new_autoselect = FALSE; int new_autoselectml = FALSE; int new_html = FALSE; regprog_T *new_exclude_prog = NULL; char_u *errmsg = NULL; char_u *p; for (p = p_cb; *p != NUL; ) { if (STRNCMP(p, "unnamed", 7) == 0 && (p[7] == ',' || p[7] == NUL)) { new_unnamed |= CLIP_UNNAMED; p += 7; } else if (STRNCMP(p, "unnamedplus", 11) == 0 && (p[11] == ',' || p[11] == NUL)) { new_unnamed |= CLIP_UNNAMED_PLUS; p += 11; } else if (STRNCMP(p, "autoselect", 10) == 0 && (p[10] == ',' || p[10] == NUL)) { new_autoselect = TRUE; p += 10; } else if (STRNCMP(p, "autoselectml", 12) == 0 && (p[12] == ',' || p[12] == NUL)) { new_autoselectml = TRUE; p += 12; } else if (STRNCMP(p, "html", 4) == 0 && (p[4] == ',' || p[4] == NUL)) { new_html = TRUE; p += 4; } else if (STRNCMP(p, "exclude:", 8) == 0 && new_exclude_prog == NULL) { p += 8; new_exclude_prog = vim_regcomp(p, RE_MAGIC); if (new_exclude_prog == NULL) errmsg = e_invarg; break; } else { errmsg = e_invarg; break; } if (*p == ',') ++p; } if (errmsg == NULL) { clip_unnamed = new_unnamed; clip_autoselect = new_autoselect; clip_autoselectml = new_autoselectml; clip_html = new_html; vim_free(clip_exclude_prog); clip_exclude_prog = new_exclude_prog; #ifdef FEAT_GUI_GTK if (gui.in_use) { gui_gtk_set_selection_targets(); gui_gtk_set_dnd_targets(); } #endif } else vim_free(new_exclude_prog); return errmsg; } #endif #ifdef FEAT_SPELL /* * Set curbuf->b_cap_prog to the regexp program for 'spellcapcheck'. * Return error message when failed, NULL when OK. */ static char_u * compile_cap_prog(synblock) synblock_T *synblock; { regprog_T *rp = synblock->b_cap_prog; char_u *re; if (*synblock->b_p_spc == NUL) synblock->b_cap_prog = NULL; else { /* Prepend a ^ so that we only match at one column */ re = concat_str((char_u *)"^", synblock->b_p_spc); if (re != NULL) { synblock->b_cap_prog = vim_regcomp(re, RE_MAGIC); if (synblock->b_cap_prog == NULL) { synblock->b_cap_prog = rp; /* restore the previous program */ return e_invarg; } vim_free(re); } } vim_free(rp); return NULL; } #endif #if defined(FEAT_EVAL) || defined(PROTO) /* * Set the scriptID for an option, taking care of setting the buffer- or * window-local value. */ static void set_option_scriptID_idx(opt_idx, opt_flags, id) int opt_idx; int opt_flags; int id; { int both = (opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0; int indir = (int)options[opt_idx].indir; /* Remember where the option was set. For local options need to do that * in the buffer or window structure. */ if (both || (opt_flags & OPT_GLOBAL) || (indir & (PV_BUF|PV_WIN)) == 0) options[opt_idx].scriptID = id; if (both || (opt_flags & OPT_LOCAL)) { if (indir & PV_BUF) curbuf->b_p_scriptID[indir & PV_MASK] = id; else if (indir & PV_WIN) curwin->w_p_scriptID[indir & PV_MASK] = id; } } #endif /* * Set the value of a boolean option, and take care of side effects. * Returns NULL for success, or an error message for an error. */ static char_u * set_bool_option(opt_idx, varp, value, opt_flags) int opt_idx; /* index in options[] table */ char_u *varp; /* pointer to the option variable */ int value; /* new value */ int opt_flags; /* OPT_LOCAL and/or OPT_GLOBAL */ { int old_value = *(int *)varp; /* Disallow changing some options from secure mode */ if ((secure #ifdef HAVE_SANDBOX || sandbox != 0 #endif ) && (options[opt_idx].flags & P_SECURE)) return e_secure; *(int *)varp = value; /* set the new value */ #ifdef FEAT_EVAL /* Remember where the option was set. */ set_option_scriptID_idx(opt_idx, opt_flags, current_SID); #endif #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif /* May set global value for local option. */ if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0) *(int *)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL) = value; /* * Handle side effects of changing a bool option. */ /* 'compatible' */ if ((int *)varp == &p_cp) { compatible_set(); } #ifdef FEAT_PERSISTENT_UNDO /* 'undofile' */ else if ((int *)varp == &curbuf->b_p_udf || (int *)varp == &p_udf) { char_u hash[UNDO_HASH_SIZE]; buf_T *save_curbuf = curbuf; for (curbuf = firstbuf; curbuf != NULL; curbuf = curbuf->b_next) { /* When 'undofile' is set globally: for every buffer, otherwise * only for the current buffer: Try to read in the undofile, if * one exists and the buffer wasn't changed and the buffer was * loaded. */ if ((curbuf == save_curbuf || (opt_flags & OPT_GLOBAL) || opt_flags == 0) && !curbufIsChanged() && curbuf->b_ml.ml_mfp != NULL) { u_compute_hash(hash); u_read_undo(NULL, hash, curbuf->b_fname); } } curbuf = save_curbuf; } #endif /* 'list', 'number' */ else if ((int *)varp == &curwin->w_p_list || (int *)varp == &curwin->w_p_nu || (int *)varp == &curwin->w_p_rnu) { /* If 'number' is set, reset 'relativenumber'. */ /* If 'relativenumber' is set, reset 'number'. */ if ((int *)varp == &curwin->w_p_nu && curwin->w_p_nu) curwin->w_p_rnu = FALSE; if ((int *)varp == &curwin->w_p_rnu && curwin->w_p_rnu) curwin->w_p_nu = FALSE; } else if ((int *)varp == &curbuf->b_p_ro) { /* when 'readonly' is reset globally, also reset readonlymode */ if (!curbuf->b_p_ro && (opt_flags & OPT_LOCAL) == 0) readonlymode = FALSE; /* when 'readonly' is set may give W10 again */ if (curbuf->b_p_ro) curbuf->b_did_warn = FALSE; #ifdef FEAT_TITLE redraw_titles(); #endif } #ifdef FEAT_GUI else if ((int *)varp == &p_mh) { if (!p_mh) gui_mch_mousehide(FALSE); } #endif #ifdef FEAT_TITLE /* when 'modifiable' is changed, redraw the window title */ else if ((int *)varp == &curbuf->b_p_ma) { redraw_titles(); } /* when 'endofline' is changed, redraw the window title */ else if ((int *)varp == &curbuf->b_p_eol) { redraw_titles(); } # ifdef FEAT_MBYTE /* when 'bomb' is changed, redraw the window title and tab page text */ else if ((int *)varp == &curbuf->b_p_bomb) { redraw_titles(); } # endif #endif /* when 'bin' is set also set some other options */ else if ((int *)varp == &curbuf->b_p_bin) { set_options_bin(old_value, curbuf->b_p_bin, opt_flags); #ifdef FEAT_TITLE redraw_titles(); #endif } #ifdef FEAT_AUTOCMD /* when 'buflisted' changes, trigger autocommands */ else if ((int *)varp == &curbuf->b_p_bl && old_value != curbuf->b_p_bl) { apply_autocmds(curbuf->b_p_bl ? EVENT_BUFADD : EVENT_BUFDELETE, NULL, NULL, TRUE, curbuf); } #endif /* when 'swf' is set, create swapfile, when reset remove swapfile */ else if ((int *)varp == &curbuf->b_p_swf) { if (curbuf->b_p_swf && p_uc) ml_open_file(curbuf); /* create the swap file */ else /* no need to reset curbuf->b_may_swap, ml_open_file() will check * buf->b_p_swf */ mf_close_file(curbuf, TRUE); /* remove the swap file */ } /* when 'terse' is set change 'shortmess' */ else if ((int *)varp == &p_terse) { char_u *p; p = vim_strchr(p_shm, SHM_SEARCH); /* insert 's' in p_shm */ if (p_terse && p == NULL) { STRCPY(IObuff, p_shm); STRCAT(IObuff, "s"); set_string_option_direct((char_u *)"shm", -1, IObuff, OPT_FREE, 0); } /* remove 's' from p_shm */ else if (!p_terse && p != NULL) STRMOVE(p, p + 1); } /* when 'paste' is set or reset also change other options */ else if ((int *)varp == &p_paste) { paste_option_changed(); } /* when 'insertmode' is set from an autocommand need to do work here */ else if ((int *)varp == &p_im) { if (p_im) { if ((State & INSERT) == 0) need_start_insertmode = TRUE; stop_insert_mode = FALSE; } else { need_start_insertmode = FALSE; stop_insert_mode = TRUE; if (restart_edit != 0 && mode_displayed) clear_cmdline = TRUE; /* remove "(insert)" */ restart_edit = 0; } } /* when 'ignorecase' is set or reset and 'hlsearch' is set, redraw */ else if ((int *)varp == &p_ic && p_hls) { redraw_all_later(SOME_VALID); } #ifdef FEAT_SEARCH_EXTRA /* when 'hlsearch' is set or reset: reset no_hlsearch */ else if ((int *)varp == &p_hls) { no_hlsearch = FALSE; } #endif #ifdef FEAT_SCROLLBIND /* when 'scrollbind' is set: snapshot the current position to avoid a jump * at the end of normal_cmd() */ else if ((int *)varp == &curwin->w_p_scb) { if (curwin->w_p_scb) do_check_scrollbind(FALSE); } #endif #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX) /* There can be only one window with 'previewwindow' set. */ else if ((int *)varp == &curwin->w_p_pvw) { if (curwin->w_p_pvw) { win_T *win; for (win = firstwin; win != NULL; win = win->w_next) if (win->w_p_pvw && win != curwin) { curwin->w_p_pvw = FALSE; return (char_u *)N_("E590: A preview window already exists"); } } } #endif /* when 'textmode' is set or reset also change 'fileformat' */ else if ((int *)varp == &curbuf->b_p_tx) { set_fileformat(curbuf->b_p_tx ? EOL_DOS : EOL_UNIX, opt_flags); } /* when 'textauto' is set or reset also change 'fileformats' */ else if ((int *)varp == &p_ta) set_string_option_direct((char_u *)"ffs", -1, p_ta ? (char_u *)DFLT_FFS_VIM : (char_u *)"", OPT_FREE | opt_flags, 0); /* * When 'lisp' option changes include/exclude '-' in * keyword characters. */ #ifdef FEAT_LISP else if (varp == (char_u *)&(curbuf->b_p_lisp)) { (void)buf_init_chartab(curbuf, FALSE); /* ignore errors */ } #endif #ifdef FEAT_TITLE /* when 'title' changed, may need to change the title; same for 'icon' */ else if ((int *)varp == &p_title) { did_set_title(FALSE); } else if ((int *)varp == &p_icon) { did_set_title(TRUE); } #endif else if ((int *)varp == &curbuf->b_changed) { if (!value) save_file_ff(curbuf); /* Buffer is unchanged */ #ifdef FEAT_TITLE redraw_titles(); #endif #ifdef FEAT_AUTOCMD modified_was_set = value; #endif } #ifdef BACKSLASH_IN_FILENAME else if ((int *)varp == &p_ssl) { if (p_ssl) { psepc = '/'; psepcN = '\\'; pseps[0] = '/'; } else { psepc = '\\'; psepcN = '/'; pseps[0] = '\\'; } /* need to adjust the file name arguments and buffer names. */ buflist_slash_adjust(); alist_slash_adjust(); # ifdef FEAT_EVAL scriptnames_slash_adjust(); # endif } #endif /* If 'wrap' is set, set w_leftcol to zero. */ else if ((int *)varp == &curwin->w_p_wrap) { if (curwin->w_p_wrap) curwin->w_leftcol = 0; } #ifdef FEAT_WINDOWS else if ((int *)varp == &p_ea) { if (p_ea && !old_value) win_equal(curwin, FALSE, 0); } #endif else if ((int *)varp == &p_wiv) { /* * When 'weirdinvert' changed, set/reset 't_xs'. * Then set 'weirdinvert' according to value of 't_xs'. */ if (p_wiv && !old_value) T_XS = (char_u *)"y"; else if (!p_wiv && old_value) T_XS = empty_option; p_wiv = (*T_XS != NUL); } #ifdef FEAT_BEVAL else if ((int *)varp == &p_beval) { if (p_beval && !old_value) gui_mch_enable_beval_area(balloonEval); else if (!p_beval && old_value) gui_mch_disable_beval_area(balloonEval); } #endif #ifdef FEAT_AUTOCHDIR else if ((int *)varp == &p_acd) { /* Change directories when the 'acd' option is set now. */ DO_AUTOCHDIR } #endif #ifdef FEAT_DIFF /* 'diff' */ else if ((int *)varp == &curwin->w_p_diff) { /* May add or remove the buffer from the list of diff buffers. */ diff_buf_adjust(curwin); # ifdef FEAT_FOLDING if (foldmethodIsDiff(curwin)) foldUpdateAll(curwin); # endif } #endif #ifdef USE_IM_CONTROL /* 'imdisable' */ else if ((int *)varp == &p_imdisable) { /* Only de-activate it here, it will be enabled when changing mode. */ if (p_imdisable) im_set_active(FALSE); else if (State & INSERT) /* When the option is set from an autocommand, it may need to take * effect right away. */ im_set_active(curbuf->b_p_iminsert == B_IMODE_IM); } #endif #ifdef FEAT_SPELL /* 'spell' */ else if ((int *)varp == &curwin->w_p_spell) { if (curwin->w_p_spell) { char_u *errmsg = did_set_spelllang(curwin); if (errmsg != NULL) EMSG(_(errmsg)); } } #endif #ifdef FEAT_FKMAP else if ((int *)varp == &p_altkeymap) { if (old_value != p_altkeymap) { if (!p_altkeymap) { p_hkmap = p_fkmap; p_fkmap = 0; } else { p_fkmap = p_hkmap; p_hkmap = 0; } (void)init_chartab(); } } /* * In case some second language keymapping options have changed, check * and correct the setting in a consistent way. */ /* * If hkmap or fkmap are set, reset Arabic keymapping. */ if ((p_hkmap || p_fkmap) && p_altkeymap) { p_altkeymap = p_fkmap; # ifdef FEAT_ARABIC curwin->w_p_arab = FALSE; # endif (void)init_chartab(); } /* * If hkmap set, reset Farsi keymapping. */ if (p_hkmap && p_altkeymap) { p_altkeymap = 0; p_fkmap = 0; # ifdef FEAT_ARABIC curwin->w_p_arab = FALSE; # endif (void)init_chartab(); } /* * If fkmap set, reset Hebrew keymapping. */ if (p_fkmap && !p_altkeymap) { p_altkeymap = 1; p_hkmap = 0; # ifdef FEAT_ARABIC curwin->w_p_arab = FALSE; # endif (void)init_chartab(); } #endif #ifdef FEAT_ARABIC if ((int *)varp == &curwin->w_p_arab) { if (curwin->w_p_arab) { /* * 'arabic' is set, handle various sub-settings. */ if (!p_tbidi) { /* set rightleft mode */ if (!curwin->w_p_rl) { curwin->w_p_rl = TRUE; changed_window_setting(); } /* Enable Arabic shaping (major part of what Arabic requires) */ if (!p_arshape) { p_arshape = TRUE; redraw_later_clear(); } } /* Arabic requires a utf-8 encoding, inform the user if its not * set. */ if (STRCMP(p_enc, "utf-8") != 0) { static char *w_arabic = N_("W17: Arabic requires UTF-8, do ':set encoding=utf-8'"); msg_source(hl_attr(HLF_W)); MSG_ATTR(_(w_arabic), hl_attr(HLF_W)); #ifdef FEAT_EVAL set_vim_var_string(VV_WARNINGMSG, (char_u *)_(w_arabic), -1); #endif } # ifdef FEAT_MBYTE /* set 'delcombine' */ p_deco = TRUE; # endif # ifdef FEAT_KEYMAP /* Force-set the necessary keymap for arabic */ set_option_value((char_u *)"keymap", 0L, (char_u *)"arabic", OPT_LOCAL); # endif # ifdef FEAT_FKMAP p_altkeymap = 0; p_hkmap = 0; p_fkmap = 0; (void)init_chartab(); # endif } else { /* * 'arabic' is reset, handle various sub-settings. */ if (!p_tbidi) { /* reset rightleft mode */ if (curwin->w_p_rl) { curwin->w_p_rl = FALSE; changed_window_setting(); } /* 'arabicshape' isn't reset, it is a global option and * another window may still need it "on". */ } /* 'delcombine' isn't reset, it is a global option and another * window may still want it "on". */ # ifdef FEAT_KEYMAP /* Revert to the default keymap */ curbuf->b_p_iminsert = B_IMODE_NONE; curbuf->b_p_imsearch = B_IMODE_USE_INSERT; # endif } } #endif /* * End of handling side effects for bool options. */ options[opt_idx].flags |= P_WAS_SET; comp_col(); /* in case 'ruler' or 'showcmd' changed */ if (curwin->w_curswant != MAXCOL && (options[opt_idx].flags & (P_CURSWANT | P_RCLR)) != 0) curwin->w_set_curswant = TRUE; check_redraw(options[opt_idx].flags); return NULL; } /* * Set the value of a number option, and take care of side effects. * Returns NULL for success, or an error message for an error. */ static char_u * set_num_option(opt_idx, varp, value, errbuf, errbuflen, opt_flags) int opt_idx; /* index in options[] table */ char_u *varp; /* pointer to the option variable */ long value; /* new value */ char_u *errbuf; /* buffer for error messages */ size_t errbuflen; /* length of "errbuf" */ int opt_flags; /* OPT_LOCAL, OPT_GLOBAL and OPT_MODELINE */ { char_u *errmsg = NULL; long old_value = *(long *)varp; long old_Rows = Rows; /* remember old Rows */ long old_Columns = Columns; /* remember old Columns */ long *pp = (long *)varp; /* Disallow changing some options from secure mode. */ if ((secure #ifdef HAVE_SANDBOX || sandbox != 0 #endif ) && (options[opt_idx].flags & P_SECURE)) return e_secure; *pp = value; #ifdef FEAT_EVAL /* Remember where the option was set. */ set_option_scriptID_idx(opt_idx, opt_flags, current_SID); #endif #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif if (curbuf->b_p_sw <= 0) { errmsg = e_positive; curbuf->b_p_sw = curbuf->b_p_ts; } /* * Number options that need some action when changed */ #ifdef FEAT_WINDOWS if (pp == &p_wh || pp == &p_hh) { if (p_wh < 1) { errmsg = e_positive; p_wh = 1; } if (p_wmh > p_wh) { errmsg = e_winheight; p_wh = p_wmh; } if (p_hh < 0) { errmsg = e_positive; p_hh = 0; } /* Change window height NOW */ if (lastwin != firstwin) { if (pp == &p_wh && curwin->w_height < p_wh) win_setheight((int)p_wh); if (pp == &p_hh && curbuf->b_help && curwin->w_height < p_hh) win_setheight((int)p_hh); } } /* 'winminheight' */ else if (pp == &p_wmh) { if (p_wmh < 0) { errmsg = e_positive; p_wmh = 0; } if (p_wmh > p_wh) { errmsg = e_winheight; p_wmh = p_wh; } win_setminheight(); } # ifdef FEAT_VERTSPLIT else if (pp == &p_wiw) { if (p_wiw < 1) { errmsg = e_positive; p_wiw = 1; } if (p_wmw > p_wiw) { errmsg = e_winwidth; p_wiw = p_wmw; } /* Change window width NOW */ if (lastwin != firstwin && curwin->w_width < p_wiw) win_setwidth((int)p_wiw); } /* 'winminwidth' */ else if (pp == &p_wmw) { if (p_wmw < 0) { errmsg = e_positive; p_wmw = 0; } if (p_wmw > p_wiw) { errmsg = e_winwidth; p_wmw = p_wiw; } win_setminheight(); } # endif #endif #ifdef FEAT_WINDOWS /* (re)set last window status line */ else if (pp == &p_ls) { last_status(FALSE); } /* (re)set tab page line */ else if (pp == &p_stal) { shell_new_rows(); /* recompute window positions and heights */ } #endif #ifdef FEAT_GUI else if (pp == &p_linespace) { /* Recompute gui.char_height and resize the Vim window to keep the * same number of lines. */ if (gui.in_use && gui_mch_adjust_charheight() == OK) gui_set_shellsize(FALSE, FALSE, RESIZE_VERT); } #endif #ifdef FEAT_FOLDING /* 'foldlevel' */ else if (pp == &curwin->w_p_fdl) { if (curwin->w_p_fdl < 0) curwin->w_p_fdl = 0; newFoldLevel(); } /* 'foldminlines' */ else if (pp == &curwin->w_p_fml) { foldUpdateAll(curwin); } /* 'foldnestmax' */ else if (pp == &curwin->w_p_fdn) { if (foldmethodIsSyntax(curwin) || foldmethodIsIndent(curwin)) foldUpdateAll(curwin); } /* 'foldcolumn' */ else if (pp == &curwin->w_p_fdc) { if (curwin->w_p_fdc < 0) { errmsg = e_positive; curwin->w_p_fdc = 0; } else if (curwin->w_p_fdc > 12) { errmsg = e_invarg; curwin->w_p_fdc = 12; } } /* 'shiftwidth' or 'tabstop' */ else if (pp == &curbuf->b_p_sw || pp == &curbuf->b_p_ts) { if (foldmethodIsIndent(curwin)) foldUpdateAll(curwin); } #endif /* FEAT_FOLDING */ #ifdef FEAT_MBYTE /* 'maxcombine' */ else if (pp == &p_mco) { if (p_mco > MAX_MCO) p_mco = MAX_MCO; else if (p_mco < 0) p_mco = 0; screenclear(); /* will re-allocate the screen */ } #endif else if (pp == &curbuf->b_p_iminsert) { if (curbuf->b_p_iminsert < 0 || curbuf->b_p_iminsert > B_IMODE_LAST) { errmsg = e_invarg; curbuf->b_p_iminsert = B_IMODE_NONE; } p_iminsert = curbuf->b_p_iminsert; if (termcap_active) /* don't do this in the alternate screen */ showmode(); #if defined(FEAT_WINDOWS) && defined(FEAT_KEYMAP) /* Show/unshow value of 'keymap' in status lines. */ status_redraw_curbuf(); #endif } else if (pp == &p_window) { if (p_window < 1) p_window = 1; else if (p_window >= Rows) p_window = Rows - 1; } else if (pp == &curbuf->b_p_imsearch) { if (curbuf->b_p_imsearch < -1 || curbuf->b_p_imsearch > B_IMODE_LAST) { errmsg = e_invarg; curbuf->b_p_imsearch = B_IMODE_NONE; } p_imsearch = curbuf->b_p_imsearch; } #ifdef FEAT_TITLE /* if 'titlelen' has changed, redraw the title */ else if (pp == &p_titlelen) { if (p_titlelen < 0) { errmsg = e_positive; p_titlelen = 85; } if (starting != NO_SCREEN && old_value != p_titlelen) need_maketitle = TRUE; } #endif /* if p_ch changed value, change the command line height */ else if (pp == &p_ch) { if (p_ch < 1) { errmsg = e_positive; p_ch = 1; } if (p_ch > Rows - min_rows() + 1) p_ch = Rows - min_rows() + 1; /* Only compute the new window layout when startup has been * completed. Otherwise the frame sizes may be wrong. */ if (p_ch != old_value && full_screen #ifdef FEAT_GUI && !gui.starting #endif ) command_height(); } /* when 'updatecount' changes from zero to non-zero, open swap files */ else if (pp == &p_uc) { if (p_uc < 0) { errmsg = e_positive; p_uc = 100; } if (p_uc && !old_value) ml_open_files(); } #ifdef FEAT_CONCEAL else if (pp == &curwin->w_p_cole) { if (curwin->w_p_cole < 0) { errmsg = e_positive; curwin->w_p_cole = 0; } else if (curwin->w_p_cole > 3) { errmsg = e_invarg; curwin->w_p_cole = 3; } } #endif #ifdef MZSCHEME_GUI_THREADS else if (pp == &p_mzq) mzvim_reset_timer(); #endif /* sync undo before 'undolevels' changes */ else if (pp == &p_ul) { /* use the old value, otherwise u_sync() may not work properly */ p_ul = old_value; u_sync(TRUE); p_ul = value; } #ifdef FEAT_LINEBREAK /* 'numberwidth' must be positive */ else if (pp == &curwin->w_p_nuw) { if (curwin->w_p_nuw < 1) { errmsg = e_positive; curwin->w_p_nuw = 1; } if (curwin->w_p_nuw > 10) { errmsg = e_invarg; curwin->w_p_nuw = 10; } curwin->w_nrwidth_line_count = 0; } #endif else if (pp == &curbuf->b_p_tw) { if (curbuf->b_p_tw < 0) { errmsg = e_positive; curbuf->b_p_tw = 0; } #ifdef FEAT_SYN_HL # ifdef FEAT_WINDOWS { win_T *wp; tabpage_T *tp; FOR_ALL_TAB_WINDOWS(tp, wp) check_colorcolumn(wp); } # else check_colorcolumn(curwin); # endif #endif } /* * Check the bounds for numeric options here */ if (Rows < min_rows() && full_screen) { if (errbuf != NULL) { vim_snprintf((char *)errbuf, errbuflen, _("E593: Need at least %d lines"), min_rows()); errmsg = errbuf; } Rows = min_rows(); } if (Columns < MIN_COLUMNS && full_screen) { if (errbuf != NULL) { vim_snprintf((char *)errbuf, errbuflen, _("E594: Need at least %d columns"), MIN_COLUMNS); errmsg = errbuf; } Columns = MIN_COLUMNS; } /* Limit the values to avoid an overflow in Rows * Columns. */ if (Columns > 10000) Columns = 10000; if (Rows > 1000) Rows = 1000; #ifdef DJGPP /* avoid a crash by checking for a too large value of 'columns' */ if (old_Columns != Columns && full_screen && term_console) mch_check_columns(); #endif /* * If the screen (shell) height has been changed, assume it is the * physical screenheight. */ if (old_Rows != Rows || old_Columns != Columns) { /* Changing the screen size is not allowed while updating the screen. */ if (updating_screen) *pp = old_value; else if (full_screen #ifdef FEAT_GUI && !gui.starting #endif ) set_shellsize((int)Columns, (int)Rows, TRUE); else { /* Postpone the resizing; check the size and cmdline position for * messages. */ check_shellsize(); if (cmdline_row > Rows - p_ch && Rows > p_ch) cmdline_row = Rows - p_ch; } if (p_window >= Rows || !option_was_set((char_u *)"window")) p_window = Rows - 1; } if (curbuf->b_p_sts < 0) { errmsg = e_positive; curbuf->b_p_sts = 0; } if (curbuf->b_p_ts <= 0) { errmsg = e_positive; curbuf->b_p_ts = 8; } if (p_tm < 0) { errmsg = e_positive; p_tm = 0; } if ((curwin->w_p_scr <= 0 || (curwin->w_p_scr > curwin->w_height && curwin->w_height > 0)) && full_screen) { if (pp == &(curwin->w_p_scr)) { if (curwin->w_p_scr != 0) errmsg = e_scroll; win_comp_scroll(curwin); } /* If 'scroll' became invalid because of a side effect silently adjust * it. */ else if (curwin->w_p_scr <= 0) curwin->w_p_scr = 1; else /* curwin->w_p_scr > curwin->w_height */ curwin->w_p_scr = curwin->w_height; } if (p_hi < 0) { errmsg = e_positive; p_hi = 0; } if (p_report < 0) { errmsg = e_positive; p_report = 1; } if ((p_sj < -100 || p_sj >= Rows) && full_screen) { if (Rows != old_Rows) /* Rows changed, just adjust p_sj */ p_sj = Rows / 2; else { errmsg = e_scroll; p_sj = 1; } } if (p_so < 0 && full_screen) { errmsg = e_scroll; p_so = 0; } if (p_siso < 0 && full_screen) { errmsg = e_positive; p_siso = 0; } #ifdef FEAT_CMDWIN if (p_cwh < 1) { errmsg = e_positive; p_cwh = 1; } #endif if (p_ut < 0) { errmsg = e_positive; p_ut = 2000; } if (p_ss < 0) { errmsg = e_positive; p_ss = 0; } /* May set global value for local option. */ if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0) *(long *)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL) = *pp; options[opt_idx].flags |= P_WAS_SET; comp_col(); /* in case 'columns' or 'ls' changed */ if (curwin->w_curswant != MAXCOL && (options[opt_idx].flags & (P_CURSWANT | P_RCLR)) != 0) curwin->w_set_curswant = TRUE; check_redraw(options[opt_idx].flags); return errmsg; } /* * Called after an option changed: check if something needs to be redrawn. */ static void check_redraw(flags) long_u flags; { /* Careful: P_RCLR and P_RALL are a combination of other P_ flags */ int doclear = (flags & P_RCLR) == P_RCLR; int all = ((flags & P_RALL) == P_RALL || doclear); #ifdef FEAT_WINDOWS if ((flags & P_RSTAT) || all) /* mark all status lines dirty */ status_redraw_all(); #endif if ((flags & P_RBUF) || (flags & P_RWIN) || all) changed_window_setting(); if (flags & P_RBUF) redraw_curbuf_later(NOT_VALID); if (doclear) redraw_all_later(CLEAR); else if (all) redraw_all_later(NOT_VALID); } /* * Find index for option 'arg'. * Return -1 if not found. */ static int findoption(arg) char_u *arg; { int opt_idx; char *s, *p; static short quick_tab[27] = {0, 0}; /* quick access table */ int is_term_opt; /* * For first call: Initialize the quick-access table. * It contains the index for the first option that starts with a certain * letter. There are 26 letters, plus the first "t_" option. */ if (quick_tab[1] == 0) { p = options[0].fullname; for (opt_idx = 1; (s = options[opt_idx].fullname) != NULL; opt_idx++) { if (s[0] != p[0]) { if (s[0] == 't' && s[1] == '_') quick_tab[26] = opt_idx; else quick_tab[CharOrdLow(s[0])] = opt_idx; } p = s; } } /* * Check for name starting with an illegal character. */ #ifdef EBCDIC if (!islower(arg[0])) #else if (arg[0] < 'a' || arg[0] > 'z') #endif return -1; is_term_opt = (arg[0] == 't' && arg[1] == '_'); if (is_term_opt) opt_idx = quick_tab[26]; else opt_idx = quick_tab[CharOrdLow(arg[0])]; for ( ; (s = options[opt_idx].fullname) != NULL; opt_idx++) { if (STRCMP(arg, s) == 0) /* match full name */ break; } if (s == NULL && !is_term_opt) { opt_idx = quick_tab[CharOrdLow(arg[0])]; for ( ; options[opt_idx].fullname != NULL; opt_idx++) { s = options[opt_idx].shortname; if (s != NULL && STRCMP(arg, s) == 0) /* match short name */ break; s = NULL; } } if (s == NULL) opt_idx = -1; return opt_idx; } #if defined(FEAT_EVAL) || defined(FEAT_TCL) || defined(FEAT_MZSCHEME) /* * Get the value for an option. * * Returns: * Number or Toggle option: 1, *numval gets value. * String option: 0, *stringval gets allocated string. * Hidden Number or Toggle option: -1. * hidden String option: -2. * unknown option: -3. */ int get_option_value(name, numval, stringval, opt_flags) char_u *name; long *numval; char_u **stringval; /* NULL when only checking existence */ int opt_flags; { int opt_idx; char_u *varp; opt_idx = findoption(name); if (opt_idx < 0) /* unknown option */ return -3; varp = get_varp_scope(&(options[opt_idx]), opt_flags); if (options[opt_idx].flags & P_STRING) { if (varp == NULL) /* hidden option */ return -2; if (stringval != NULL) { #ifdef FEAT_CRYPT /* never return the value of the crypt key */ if ((char_u **)varp == &curbuf->b_p_key && **(char_u **)(varp) != NUL) *stringval = vim_strsave((char_u *)"*****"); else #endif *stringval = vim_strsave(*(char_u **)(varp)); } return 0; } if (varp == NULL) /* hidden option */ return -1; if (options[opt_idx].flags & P_NUM) *numval = *(long *)varp; else { /* Special case: 'modified' is b_changed, but we also want to consider * it set when 'ff' or 'fenc' changed. */ if ((int *)varp == &curbuf->b_changed) *numval = curbufIsChanged(); else *numval = *(int *)varp; } return 1; } #endif /* * Set the value of option "name". * Use "string" for string options, use "number" for other options. */ void set_option_value(name, number, string, opt_flags) char_u *name; long number; char_u *string; int opt_flags; /* OPT_LOCAL or 0 (both) */ { int opt_idx; char_u *varp; long_u flags; opt_idx = findoption(name); if (opt_idx < 0) EMSG2(_("E355: Unknown option: %s"), name); else { flags = options[opt_idx].flags; #ifdef HAVE_SANDBOX /* Disallow changing some options in the sandbox */ if (sandbox > 0 && (flags & P_SECURE)) { EMSG(_(e_sandbox)); return; } #endif if (flags & P_STRING) set_string_option(opt_idx, string, opt_flags); else { varp = get_varp_scope(&(options[opt_idx]), opt_flags); if (varp != NULL) /* hidden option is not changed */ { if (number == 0 && string != NULL) { int idx; /* Either we are given a string or we are setting option * to zero. */ for (idx = 0; string[idx] == '0'; ++idx) ; if (string[idx] != NUL || idx == 0) { /* There's another character after zeros or the string * is empty. In both cases, we are trying to set a * num option using a string. */ EMSG3(_("E521: Number required: &%s = '%s'"), name, string); return; /* do nothing as we hit an error */ } } if (flags & P_NUM) (void)set_num_option(opt_idx, varp, number, NULL, 0, opt_flags); else (void)set_bool_option(opt_idx, varp, (int)number, opt_flags); } } } } /* * Get the terminal code for a terminal option. * Returns NULL when not found. */ char_u * get_term_code(tname) char_u *tname; { int opt_idx; char_u *varp; if (tname[0] != 't' || tname[1] != '_' || tname[2] == NUL || tname[3] == NUL) return NULL; if ((opt_idx = findoption(tname)) >= 0) { varp = get_varp(&(options[opt_idx])); if (varp != NULL) varp = *(char_u **)(varp); return varp; } return find_termcode(tname + 2); } char_u * get_highlight_default() { int i; i = findoption((char_u *)"hl"); if (i >= 0) return options[i].def_val[VI_DEFAULT]; return (char_u *)NULL; } #if defined(FEAT_MBYTE) || defined(PROTO) char_u * get_encoding_default() { int i; i = findoption((char_u *)"enc"); if (i >= 0) return options[i].def_val[VI_DEFAULT]; return (char_u *)NULL; } #endif /* * Translate a string like "t_xx", "<t_xx>" or "<S-Tab>" to a key number. */ static int find_key_option(arg) char_u *arg; { int key; int modifiers; /* * Don't use get_special_key_code() for t_xx, we don't want it to call * add_termcap_entry(). */ if (arg[0] == 't' && arg[1] == '_' && arg[2] && arg[3]) key = TERMCAP2KEY(arg[2], arg[3]); else { --arg; /* put arg at the '<' */ modifiers = 0; key = find_special_key(&arg, &modifiers, TRUE, TRUE); if (modifiers) /* can't handle modifiers here */ key = 0; } return key; } /* * if 'all' == 0: show changed options * if 'all' == 1: show all normal options * if 'all' == 2: show all terminal options */ static void showoptions(all, opt_flags) int all; int opt_flags; /* OPT_LOCAL and/or OPT_GLOBAL */ { struct vimoption *p; int col; int isterm; char_u *varp; struct vimoption **items; int item_count; int run; int row, rows; int cols; int i; int len; #define INC 20 #define GAP 3 items = (struct vimoption **)alloc((unsigned)(sizeof(struct vimoption *) * PARAM_COUNT)); if (items == NULL) return; /* Highlight title */ if (all == 2) MSG_PUTS_TITLE(_("\n--- Terminal codes ---")); else if (opt_flags & OPT_GLOBAL) MSG_PUTS_TITLE(_("\n--- Global option values ---")); else if (opt_flags & OPT_LOCAL) MSG_PUTS_TITLE(_("\n--- Local option values ---")); else MSG_PUTS_TITLE(_("\n--- Options ---")); /* * do the loop two times: * 1. display the short items * 2. display the long items (only strings and numbers) */ for (run = 1; run <= 2 && !got_int; ++run) { /* * collect the items in items[] */ item_count = 0; for (p = &options[0]; p->fullname != NULL; p++) { varp = NULL; isterm = istermoption(p); if (opt_flags != 0) { if (p->indir != PV_NONE && !isterm) varp = get_varp_scope(p, opt_flags); } else varp = get_varp(p); if (varp != NULL && ((all == 2 && isterm) || (all == 1 && !isterm) || (all == 0 && !optval_default(p, varp)))) { if (p->flags & P_BOOL) len = 1; /* a toggle option fits always */ else { option_value2string(p, opt_flags); len = (int)STRLEN(p->fullname) + vim_strsize(NameBuff) + 1; } if ((len <= INC - GAP && run == 1) || (len > INC - GAP && run == 2)) items[item_count++] = p; } } /* * display the items */ if (run == 1) { cols = (Columns + GAP - 3) / INC; if (cols == 0) cols = 1; rows = (item_count + cols - 1) / cols; } else /* run == 2 */ rows = item_count; for (row = 0; row < rows && !got_int; ++row) { msg_putchar('\n'); /* go to next line */ if (got_int) /* 'q' typed in more */ break; col = 0; for (i = row; i < item_count; i += rows) { msg_col = col; /* make columns */ showoneopt(items[i], opt_flags); col += INC; } out_flush(); ui_breakcheck(); } } vim_free(items); } /* * Return TRUE if option "p" has its default value. */ static int optval_default(p, varp) struct vimoption *p; char_u *varp; { int dvi; if (varp == NULL) return TRUE; /* hidden option is always at default */ dvi = ((p->flags & P_VI_DEF) || p_cp) ? VI_DEFAULT : VIM_DEFAULT; if (p->flags & P_NUM) return (*(long *)varp == (long)(long_i)p->def_val[dvi]); if (p->flags & P_BOOL) /* the cast to long is required for Manx C, long_i is * needed for MSVC */ return (*(int *)varp == (int)(long)(long_i)p->def_val[dvi]); /* P_STRING */ return (STRCMP(*(char_u **)varp, p->def_val[dvi]) == 0); } /* * showoneopt: show the value of one option * must not be called with a hidden option! */ static void showoneopt(p, opt_flags) struct vimoption *p; int opt_flags; /* OPT_LOCAL or OPT_GLOBAL */ { char_u *varp; int save_silent = silent_mode; silent_mode = FALSE; info_message = TRUE; /* use mch_msg(), not mch_errmsg() */ varp = get_varp_scope(p, opt_flags); /* for 'modified' we also need to check if 'ff' or 'fenc' changed. */ if ((p->flags & P_BOOL) && ((int *)varp == &curbuf->b_changed ? !curbufIsChanged() : !*(int *)varp)) MSG_PUTS("no"); else if ((p->flags & P_BOOL) && *(int *)varp < 0) MSG_PUTS("--"); else MSG_PUTS(" "); MSG_PUTS(p->fullname); if (!(p->flags & P_BOOL)) { msg_putchar('='); /* put value string in NameBuff */ option_value2string(p, opt_flags); msg_outtrans(NameBuff); } silent_mode = save_silent; info_message = FALSE; } /* * Write modified options as ":set" commands to a file. * * There are three values for "opt_flags": * OPT_GLOBAL: Write global option values and fresh values of * buffer-local options (used for start of a session * file). * OPT_GLOBAL + OPT_LOCAL: Idem, add fresh values of window-local options for * curwin (used for a vimrc file). * OPT_LOCAL: Write buffer-local option values for curbuf, fresh * and local values for window-local options of * curwin. Local values are also written when at the * default value, because a modeline or autocommand * may have set them when doing ":edit file" and the * user has set them back at the default or fresh * value. * When "local_only" is TRUE, don't write fresh * values, only local values (for ":mkview"). * (fresh value = value used for a new buffer or window for a local option). * * Return FAIL on error, OK otherwise. */ int makeset(fd, opt_flags, local_only) FILE *fd; int opt_flags; int local_only; { struct vimoption *p; char_u *varp; /* currently used value */ char_u *varp_fresh; /* local value */ char_u *varp_local = NULL; /* fresh value */ char *cmd; int round; int pri; /* * The options that don't have a default (terminal name, columns, lines) * are never written. Terminal options are also not written. * Do the loop over "options[]" twice: once for options with the * P_PRI_MKRC flag and once without. */ for (pri = 1; pri >= 0; --pri) { for (p = &options[0]; !istermoption(p); p++) if (!(p->flags & P_NO_MKRC) && !istermoption(p) && ((pri == 1) == ((p->flags & P_PRI_MKRC) != 0))) { /* skip global option when only doing locals */ if (p->indir == PV_NONE && !(opt_flags & OPT_GLOBAL)) continue; /* Do not store options like 'bufhidden' and 'syntax' in a vimrc * file, they are always buffer-specific. */ if ((opt_flags & OPT_GLOBAL) && (p->flags & P_NOGLOB)) continue; /* Global values are only written when not at the default value. */ varp = get_varp_scope(p, opt_flags); if ((opt_flags & OPT_GLOBAL) && optval_default(p, varp)) continue; round = 2; if (p->indir != PV_NONE) { if (p->var == VAR_WIN) { /* skip window-local option when only doing globals */ if (!(opt_flags & OPT_LOCAL)) continue; /* When fresh value of window-local option is not at the * default, need to write it too. */ if (!(opt_flags & OPT_GLOBAL) && !local_only) { varp_fresh = get_varp_scope(p, OPT_GLOBAL); if (!optval_default(p, varp_fresh)) { round = 1; varp_local = varp; varp = varp_fresh; } } } } /* Round 1: fresh value for window-local options. * Round 2: other values */ for ( ; round <= 2; varp = varp_local, ++round) { if (round == 1 || (opt_flags & OPT_GLOBAL)) cmd = "set"; else cmd = "setlocal"; if (p->flags & P_BOOL) { if (put_setbool(fd, cmd, p->fullname, *(int *)varp) == FAIL) return FAIL; } else if (p->flags & P_NUM) { if (put_setnum(fd, cmd, p->fullname, (long *)varp) == FAIL) return FAIL; } else /* P_STRING */ { #if defined(FEAT_SYN_HL) || defined(FEAT_AUTOCMD) int do_endif = FALSE; /* Don't set 'syntax' and 'filetype' again if the value is * already right, avoids reloading the syntax file. */ if ( # if defined(FEAT_SYN_HL) p->indir == PV_SYN # if defined(FEAT_AUTOCMD) || # endif # endif # if defined(FEAT_AUTOCMD) p->indir == PV_FT # endif ) { if (fprintf(fd, "if &%s != '%s'", p->fullname, *(char_u **)(varp)) < 0 || put_eol(fd) < 0) return FAIL; do_endif = TRUE; } #endif if (put_setstring(fd, cmd, p->fullname, (char_u **)varp, (p->flags & P_EXPAND) != 0) == FAIL) return FAIL; #if defined(FEAT_SYN_HL) || defined(FEAT_AUTOCMD) if (do_endif) { if (put_line(fd, "endif") == FAIL) return FAIL; } #endif } } } } return OK; } #if defined(FEAT_FOLDING) || defined(PROTO) /* * Generate set commands for the local fold options only. Used when * 'sessionoptions' or 'viewoptions' contains "folds" but not "options". */ int makefoldset(fd) FILE *fd; { if (put_setstring(fd, "setlocal", "fdm", &curwin->w_p_fdm, FALSE) == FAIL # ifdef FEAT_EVAL || put_setstring(fd, "setlocal", "fde", &curwin->w_p_fde, FALSE) == FAIL # endif || put_setstring(fd, "setlocal", "fmr", &curwin->w_p_fmr, FALSE) == FAIL || put_setstring(fd, "setlocal", "fdi", &curwin->w_p_fdi, FALSE) == FAIL || put_setnum(fd, "setlocal", "fdl", &curwin->w_p_fdl) == FAIL || put_setnum(fd, "setlocal", "fml", &curwin->w_p_fml) == FAIL || put_setnum(fd, "setlocal", "fdn", &curwin->w_p_fdn) == FAIL || put_setbool(fd, "setlocal", "fen", curwin->w_p_fen) == FAIL ) return FAIL; return OK; } #endif static int put_setstring(fd, cmd, name, valuep, expand) FILE *fd; char *cmd; char *name; char_u **valuep; int expand; { char_u *s; char_u *buf; if (fprintf(fd, "%s %s=", cmd, name) < 0) return FAIL; if (*valuep != NULL) { /* Output 'pastetoggle' as key names. For other * options some characters have to be escaped with * CTRL-V or backslash */ if (valuep == &p_pt) { s = *valuep; while (*s != NUL) if (put_escstr(fd, str2special(&s, FALSE), 2) == FAIL) return FAIL; } else if (expand) { buf = alloc(MAXPATHL); if (buf == NULL) return FAIL; home_replace(NULL, *valuep, buf, MAXPATHL, FALSE); if (put_escstr(fd, buf, 2) == FAIL) { vim_free(buf); return FAIL; } vim_free(buf); } else if (put_escstr(fd, *valuep, 2) == FAIL) return FAIL; } if (put_eol(fd) < 0) return FAIL; return OK; } static int put_setnum(fd, cmd, name, valuep) FILE *fd; char *cmd; char *name; long *valuep; { long wc; if (fprintf(fd, "%s %s=", cmd, name) < 0) return FAIL; if (wc_use_keyname((char_u *)valuep, &wc)) { /* print 'wildchar' and 'wildcharm' as a key name */ if (fputs((char *)get_special_key_name((int)wc, 0), fd) < 0) return FAIL; } else if (fprintf(fd, "%ld", *valuep) < 0) return FAIL; if (put_eol(fd) < 0) return FAIL; return OK; } static int put_setbool(fd, cmd, name, value) FILE *fd; char *cmd; char *name; int value; { if (value < 0) /* global/local option using global value */ return OK; if (fprintf(fd, "%s %s%s", cmd, value ? "" : "no", name) < 0 || put_eol(fd) < 0) return FAIL; return OK; } /* * Clear all the terminal options. * If the option has been allocated, free the memory. * Terminal options are never hidden or indirect. */ void clear_termoptions() { /* * Reset a few things before clearing the old options. This may cause * outputting a few things that the terminal doesn't understand, but the * screen will be cleared later, so this is OK. */ #ifdef FEAT_MOUSE_TTY mch_setmouse(FALSE); /* switch mouse off */ #endif #ifdef FEAT_TITLE mch_restore_title(3); /* restore window titles */ #endif #if defined(FEAT_XCLIPBOARD) && defined(FEAT_GUI) /* When starting the GUI close the display opened for the clipboard. * After restoring the title, because that will need the display. */ if (gui.starting) clear_xterm_clip(); #endif #ifdef WIN3264 /* * Check if this is allowed now. */ if (can_end_termcap_mode(FALSE) == TRUE) #endif stoptermcap(); /* stop termcap mode */ free_termoptions(); } void free_termoptions() { struct vimoption *p; for (p = &options[0]; p->fullname != NULL; p++) if (istermoption(p)) { if (p->flags & P_ALLOCED) free_string_option(*(char_u **)(p->var)); if (p->flags & P_DEF_ALLOCED) free_string_option(p->def_val[VI_DEFAULT]); *(char_u **)(p->var) = empty_option; p->def_val[VI_DEFAULT] = empty_option; p->flags &= ~(P_ALLOCED|P_DEF_ALLOCED); } clear_termcodes(); } /* * Free the string for one term option, if it was allocated. * Set the string to empty_option and clear allocated flag. * "var" points to the option value. */ void free_one_termoption(var) char_u *var; { struct vimoption *p; for (p = &options[0]; p->fullname != NULL; p++) if (p->var == var) { if (p->flags & P_ALLOCED) free_string_option(*(char_u **)(p->var)); *(char_u **)(p->var) = empty_option; p->flags &= ~P_ALLOCED; break; } } /* * Set the terminal option defaults to the current value. * Used after setting the terminal name. */ void set_term_defaults() { struct vimoption *p; for (p = &options[0]; p->fullname != NULL; p++) { if (istermoption(p) && p->def_val[VI_DEFAULT] != *(char_u **)(p->var)) { if (p->flags & P_DEF_ALLOCED) { free_string_option(p->def_val[VI_DEFAULT]); p->flags &= ~P_DEF_ALLOCED; } p->def_val[VI_DEFAULT] = *(char_u **)(p->var); if (p->flags & P_ALLOCED) { p->flags |= P_DEF_ALLOCED; p->flags &= ~P_ALLOCED; /* don't free the value now */ } } } } /* * return TRUE if 'p' starts with 't_' */ static int istermoption(p) struct vimoption *p; { return (p->fullname[0] == 't' && p->fullname[1] == '_'); } /* * Compute columns for ruler and shown command. 'sc_col' is also used to * decide what the maximum length of a message on the status line can be. * If there is a status line for the last window, 'sc_col' is independent * of 'ru_col'. */ #define COL_RULER 17 /* columns needed by standard ruler */ void comp_col() { #if defined(FEAT_CMDL_INFO) && defined(FEAT_WINDOWS) int last_has_status = (p_ls == 2 || (p_ls == 1 && firstwin != lastwin)); sc_col = 0; ru_col = 0; if (p_ru) { #ifdef FEAT_STL_OPT ru_col = (ru_wid ? ru_wid : COL_RULER) + 1; #else ru_col = COL_RULER + 1; #endif /* no last status line, adjust sc_col */ if (!last_has_status) sc_col = ru_col; } if (p_sc) { sc_col += SHOWCMD_COLS; if (!p_ru || last_has_status) /* no need for separating space */ ++sc_col; } sc_col = Columns - sc_col; ru_col = Columns - ru_col; if (sc_col <= 0) /* screen too narrow, will become a mess */ sc_col = 1; if (ru_col <= 0) ru_col = 1; #else sc_col = Columns; ru_col = Columns; #endif } /* * Get pointer to option variable, depending on local or global scope. */ static char_u * get_varp_scope(p, opt_flags) struct vimoption *p; int opt_flags; { if ((opt_flags & OPT_GLOBAL) && p->indir != PV_NONE) { if (p->var == VAR_WIN) return (char_u *)GLOBAL_WO(get_varp(p)); return p->var; } if ((opt_flags & OPT_LOCAL) && ((int)p->indir & PV_BOTH)) { switch ((int)p->indir) { #ifdef FEAT_QUICKFIX case PV_EFM: return (char_u *)&(curbuf->b_p_efm); case PV_GP: return (char_u *)&(curbuf->b_p_gp); case PV_MP: return (char_u *)&(curbuf->b_p_mp); #endif case PV_EP: return (char_u *)&(curbuf->b_p_ep); case PV_KP: return (char_u *)&(curbuf->b_p_kp); case PV_PATH: return (char_u *)&(curbuf->b_p_path); case PV_AR: return (char_u *)&(curbuf->b_p_ar); case PV_TAGS: return (char_u *)&(curbuf->b_p_tags); #ifdef FEAT_FIND_ID case PV_DEF: return (char_u *)&(curbuf->b_p_def); case PV_INC: return (char_u *)&(curbuf->b_p_inc); #endif #ifdef FEAT_INS_EXPAND case PV_DICT: return (char_u *)&(curbuf->b_p_dict); case PV_TSR: return (char_u *)&(curbuf->b_p_tsr); #endif #if defined(FEAT_BEVAL) && defined(FEAT_EVAL) case PV_BEXPR: return (char_u *)&(curbuf->b_p_bexpr); #endif #if defined(FEAT_CRYPT) case PV_CM: return (char_u *)&(curbuf->b_p_cm); #endif #ifdef FEAT_STL_OPT case PV_STL: return (char_u *)&(curwin->w_p_stl); #endif } return NULL; /* "cannot happen" */ } return get_varp(p); } /* * Get pointer to option variable. */ static char_u * get_varp(p) struct vimoption *p; { /* hidden option, always return NULL */ if (p->var == NULL) return NULL; switch ((int)p->indir) { case PV_NONE: return p->var; /* global option with local value: use local value if it's been set */ case PV_EP: return *curbuf->b_p_ep != NUL ? (char_u *)&curbuf->b_p_ep : p->var; case PV_KP: return *curbuf->b_p_kp != NUL ? (char_u *)&curbuf->b_p_kp : p->var; case PV_PATH: return *curbuf->b_p_path != NUL ? (char_u *)&(curbuf->b_p_path) : p->var; case PV_AR: return curbuf->b_p_ar >= 0 ? (char_u *)&(curbuf->b_p_ar) : p->var; case PV_TAGS: return *curbuf->b_p_tags != NUL ? (char_u *)&(curbuf->b_p_tags) : p->var; #ifdef FEAT_FIND_ID case PV_DEF: return *curbuf->b_p_def != NUL ? (char_u *)&(curbuf->b_p_def) : p->var; case PV_INC: return *curbuf->b_p_inc != NUL ? (char_u *)&(curbuf->b_p_inc) : p->var; #endif #ifdef FEAT_INS_EXPAND case PV_DICT: return *curbuf->b_p_dict != NUL ? (char_u *)&(curbuf->b_p_dict) : p->var; case PV_TSR: return *curbuf->b_p_tsr != NUL ? (char_u *)&(curbuf->b_p_tsr) : p->var; #endif #ifdef FEAT_QUICKFIX case PV_EFM: return *curbuf->b_p_efm != NUL ? (char_u *)&(curbuf->b_p_efm) : p->var; case PV_GP: return *curbuf->b_p_gp != NUL ? (char_u *)&(curbuf->b_p_gp) : p->var; case PV_MP: return *curbuf->b_p_mp != NUL ? (char_u *)&(curbuf->b_p_mp) : p->var; #endif #if defined(FEAT_BEVAL) && defined(FEAT_EVAL) case PV_BEXPR: return *curbuf->b_p_bexpr != NUL ? (char_u *)&(curbuf->b_p_bexpr) : p->var; #endif #if defined(FEAT_CRYPT) case PV_CM: return *curbuf->b_p_cm != NUL ? (char_u *)&(curbuf->b_p_cm) : p->var; #endif #ifdef FEAT_STL_OPT case PV_STL: return *curwin->w_p_stl != NUL ? (char_u *)&(curwin->w_p_stl) : p->var; #endif #ifdef FEAT_ARABIC case PV_ARAB: return (char_u *)&(curwin->w_p_arab); #endif case PV_LIST: return (char_u *)&(curwin->w_p_list); #ifdef FEAT_SPELL case PV_SPELL: return (char_u *)&(curwin->w_p_spell); #endif #ifdef FEAT_SYN_HL case PV_CUC: return (char_u *)&(curwin->w_p_cuc); case PV_CUL: return (char_u *)&(curwin->w_p_cul); case PV_CC: return (char_u *)&(curwin->w_p_cc); #endif #ifdef FEAT_DIFF case PV_DIFF: return (char_u *)&(curwin->w_p_diff); #endif #ifdef FEAT_FOLDING case PV_FDC: return (char_u *)&(curwin->w_p_fdc); case PV_FEN: return (char_u *)&(curwin->w_p_fen); case PV_FDI: return (char_u *)&(curwin->w_p_fdi); case PV_FDL: return (char_u *)&(curwin->w_p_fdl); case PV_FDM: return (char_u *)&(curwin->w_p_fdm); case PV_FML: return (char_u *)&(curwin->w_p_fml); case PV_FDN: return (char_u *)&(curwin->w_p_fdn); # ifdef FEAT_EVAL case PV_FDE: return (char_u *)&(curwin->w_p_fde); case PV_FDT: return (char_u *)&(curwin->w_p_fdt); # endif case PV_FMR: return (char_u *)&(curwin->w_p_fmr); #endif case PV_NU: return (char_u *)&(curwin->w_p_nu); case PV_RNU: return (char_u *)&(curwin->w_p_rnu); #ifdef FEAT_LINEBREAK case PV_NUW: return (char_u *)&(curwin->w_p_nuw); #endif #ifdef FEAT_WINDOWS case PV_WFH: return (char_u *)&(curwin->w_p_wfh); #endif #ifdef FEAT_VERTSPLIT case PV_WFW: return (char_u *)&(curwin->w_p_wfw); #endif #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX) case PV_PVW: return (char_u *)&(curwin->w_p_pvw); #endif #ifdef FEAT_RIGHTLEFT case PV_RL: return (char_u *)&(curwin->w_p_rl); case PV_RLC: return (char_u *)&(curwin->w_p_rlc); #endif case PV_SCROLL: return (char_u *)&(curwin->w_p_scr); case PV_WRAP: return (char_u *)&(curwin->w_p_wrap); #ifdef FEAT_LINEBREAK case PV_LBR: return (char_u *)&(curwin->w_p_lbr); #endif #ifdef FEAT_SCROLLBIND case PV_SCBIND: return (char_u *)&(curwin->w_p_scb); #endif #ifdef FEAT_CURSORBIND case PV_CRBIND: return (char_u *)&(curwin->w_p_crb); #endif #ifdef FEAT_CONCEAL case PV_COCU: return (char_u *)&(curwin->w_p_cocu); case PV_COLE: return (char_u *)&(curwin->w_p_cole); #endif case PV_AI: return (char_u *)&(curbuf->b_p_ai); case PV_BIN: return (char_u *)&(curbuf->b_p_bin); #ifdef FEAT_MBYTE case PV_BOMB: return (char_u *)&(curbuf->b_p_bomb); #endif #if defined(FEAT_QUICKFIX) case PV_BH: return (char_u *)&(curbuf->b_p_bh); case PV_BT: return (char_u *)&(curbuf->b_p_bt); #endif case PV_BL: return (char_u *)&(curbuf->b_p_bl); case PV_CI: return (char_u *)&(curbuf->b_p_ci); #ifdef FEAT_CINDENT case PV_CIN: return (char_u *)&(curbuf->b_p_cin); case PV_CINK: return (char_u *)&(curbuf->b_p_cink); case PV_CINO: return (char_u *)&(curbuf->b_p_cino); #endif #if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT) case PV_CINW: return (char_u *)&(curbuf->b_p_cinw); #endif #ifdef FEAT_COMMENTS case PV_COM: return (char_u *)&(curbuf->b_p_com); #endif #ifdef FEAT_FOLDING case PV_CMS: return (char_u *)&(curbuf->b_p_cms); #endif #ifdef FEAT_INS_EXPAND case PV_CPT: return (char_u *)&(curbuf->b_p_cpt); #endif #ifdef FEAT_COMPL_FUNC case PV_CFU: return (char_u *)&(curbuf->b_p_cfu); case PV_OFU: return (char_u *)&(curbuf->b_p_ofu); #endif case PV_EOL: return (char_u *)&(curbuf->b_p_eol); case PV_ET: return (char_u *)&(curbuf->b_p_et); #ifdef FEAT_MBYTE case PV_FENC: return (char_u *)&(curbuf->b_p_fenc); #endif case PV_FF: return (char_u *)&(curbuf->b_p_ff); #ifdef FEAT_AUTOCMD case PV_FT: return (char_u *)&(curbuf->b_p_ft); #endif case PV_FO: return (char_u *)&(curbuf->b_p_fo); case PV_FLP: return (char_u *)&(curbuf->b_p_flp); case PV_IMI: return (char_u *)&(curbuf->b_p_iminsert); case PV_IMS: return (char_u *)&(curbuf->b_p_imsearch); case PV_INF: return (char_u *)&(curbuf->b_p_inf); case PV_ISK: return (char_u *)&(curbuf->b_p_isk); #ifdef FEAT_FIND_ID # ifdef FEAT_EVAL case PV_INEX: return (char_u *)&(curbuf->b_p_inex); # endif #endif #if defined(FEAT_CINDENT) && defined(FEAT_EVAL) case PV_INDE: return (char_u *)&(curbuf->b_p_inde); case PV_INDK: return (char_u *)&(curbuf->b_p_indk); #endif #ifdef FEAT_EVAL case PV_FEX: return (char_u *)&(curbuf->b_p_fex); #endif #ifdef FEAT_CRYPT case PV_KEY: return (char_u *)&(curbuf->b_p_key); #endif #ifdef FEAT_LISP case PV_LISP: return (char_u *)&(curbuf->b_p_lisp); #endif case PV_ML: return (char_u *)&(curbuf->b_p_ml); case PV_MPS: return (char_u *)&(curbuf->b_p_mps); case PV_MA: return (char_u *)&(curbuf->b_p_ma); case PV_MOD: return (char_u *)&(curbuf->b_changed); case PV_NF: return (char_u *)&(curbuf->b_p_nf); case PV_PI: return (char_u *)&(curbuf->b_p_pi); #ifdef FEAT_TEXTOBJ case PV_QE: return (char_u *)&(curbuf->b_p_qe); #endif case PV_RO: return (char_u *)&(curbuf->b_p_ro); #ifdef FEAT_SMARTINDENT case PV_SI: return (char_u *)&(curbuf->b_p_si); #endif #ifndef SHORT_FNAME case PV_SN: return (char_u *)&(curbuf->b_p_sn); #endif case PV_STS: return (char_u *)&(curbuf->b_p_sts); #ifdef FEAT_SEARCHPATH case PV_SUA: return (char_u *)&(curbuf->b_p_sua); #endif case PV_SWF: return (char_u *)&(curbuf->b_p_swf); #ifdef FEAT_SYN_HL case PV_SMC: return (char_u *)&(curbuf->b_p_smc); case PV_SYN: return (char_u *)&(curbuf->b_p_syn); #endif #ifdef FEAT_SPELL case PV_SPC: return (char_u *)&(curwin->w_s->b_p_spc); case PV_SPF: return (char_u *)&(curwin->w_s->b_p_spf); case PV_SPL: return (char_u *)&(curwin->w_s->b_p_spl); #endif case PV_SW: return (char_u *)&(curbuf->b_p_sw); case PV_TS: return (char_u *)&(curbuf->b_p_ts); case PV_TW: return (char_u *)&(curbuf->b_p_tw); case PV_TX: return (char_u *)&(curbuf->b_p_tx); #ifdef FEAT_PERSISTENT_UNDO case PV_UDF: return (char_u *)&(curbuf->b_p_udf); #endif case PV_WM: return (char_u *)&(curbuf->b_p_wm); #ifdef FEAT_KEYMAP case PV_KMAP: return (char_u *)&(curbuf->b_p_keymap); #endif default: EMSG(_("E356: get_varp ERROR")); } /* always return a valid pointer to avoid a crash! */ return (char_u *)&(curbuf->b_p_wm); } /* * Get the value of 'equalprg', either the buffer-local one or the global one. */ char_u * get_equalprg() { if (*curbuf->b_p_ep == NUL) return p_ep; return curbuf->b_p_ep; } #if defined(FEAT_WINDOWS) || defined(PROTO) /* * Copy options from one window to another. * Used when splitting a window. */ void win_copy_options(wp_from, wp_to) win_T *wp_from; win_T *wp_to; { copy_winopt(&wp_from->w_onebuf_opt, &wp_to->w_onebuf_opt); copy_winopt(&wp_from->w_allbuf_opt, &wp_to->w_allbuf_opt); # ifdef FEAT_RIGHTLEFT # ifdef FEAT_FKMAP /* Is this right? */ wp_to->w_farsi = wp_from->w_farsi; # endif # endif } #endif /* * Copy the options from one winopt_T to another. * Doesn't free the old option values in "to", use clear_winopt() for that. * The 'scroll' option is not copied, because it depends on the window height. * The 'previewwindow' option is reset, there can be only one preview window. */ void copy_winopt(from, to) winopt_T *from; winopt_T *to; { #ifdef FEAT_ARABIC to->wo_arab = from->wo_arab; #endif to->wo_list = from->wo_list; to->wo_nu = from->wo_nu; to->wo_rnu = from->wo_rnu; #ifdef FEAT_LINEBREAK to->wo_nuw = from->wo_nuw; #endif #ifdef FEAT_RIGHTLEFT to->wo_rl = from->wo_rl; to->wo_rlc = vim_strsave(from->wo_rlc); #endif #ifdef FEAT_STL_OPT to->wo_stl = vim_strsave(from->wo_stl); #endif to->wo_wrap = from->wo_wrap; #ifdef FEAT_LINEBREAK to->wo_lbr = from->wo_lbr; #endif #ifdef FEAT_SCROLLBIND to->wo_scb = from->wo_scb; #endif #ifdef FEAT_CURSORBIND to->wo_crb = from->wo_crb; #endif #ifdef FEAT_SPELL to->wo_spell = from->wo_spell; #endif #ifdef FEAT_SYN_HL to->wo_cuc = from->wo_cuc; to->wo_cul = from->wo_cul; to->wo_cc = vim_strsave(from->wo_cc); #endif #ifdef FEAT_DIFF to->wo_diff = from->wo_diff; #endif #ifdef FEAT_CONCEAL to->wo_cocu = vim_strsave(from->wo_cocu); to->wo_cole = from->wo_cole; #endif #ifdef FEAT_FOLDING to->wo_fdc = from->wo_fdc; to->wo_fen = from->wo_fen; to->wo_fdi = vim_strsave(from->wo_fdi); to->wo_fml = from->wo_fml; to->wo_fdl = from->wo_fdl; to->wo_fdm = vim_strsave(from->wo_fdm); to->wo_fdn = from->wo_fdn; # ifdef FEAT_EVAL to->wo_fde = vim_strsave(from->wo_fde); to->wo_fdt = vim_strsave(from->wo_fdt); # endif to->wo_fmr = vim_strsave(from->wo_fmr); #endif check_winopt(to); /* don't want NULL pointers */ } /* * Check string options in a window for a NULL value. */ void check_win_options(win) win_T *win; { check_winopt(&win->w_onebuf_opt); check_winopt(&win->w_allbuf_opt); } /* * Check for NULL pointers in a winopt_T and replace them with empty_option. */ void check_winopt(wop) winopt_T *wop UNUSED; { #ifdef FEAT_FOLDING check_string_option(&wop->wo_fdi); check_string_option(&wop->wo_fdm); # ifdef FEAT_EVAL check_string_option(&wop->wo_fde); check_string_option(&wop->wo_fdt); # endif check_string_option(&wop->wo_fmr); #endif #ifdef FEAT_RIGHTLEFT check_string_option(&wop->wo_rlc); #endif #ifdef FEAT_STL_OPT check_string_option(&wop->wo_stl); #endif #ifdef FEAT_SYN_HL check_string_option(&wop->wo_cc); #endif #ifdef FEAT_CONCEAL check_string_option(&wop->wo_cocu); #endif } /* * Free the allocated memory inside a winopt_T. */ void clear_winopt(wop) winopt_T *wop UNUSED; { #ifdef FEAT_FOLDING clear_string_option(&wop->wo_fdi); clear_string_option(&wop->wo_fdm); # ifdef FEAT_EVAL clear_string_option(&wop->wo_fde); clear_string_option(&wop->wo_fdt); # endif clear_string_option(&wop->wo_fmr); #endif #ifdef FEAT_RIGHTLEFT clear_string_option(&wop->wo_rlc); #endif #ifdef FEAT_STL_OPT clear_string_option(&wop->wo_stl); #endif #ifdef FEAT_SYN_HL clear_string_option(&wop->wo_cc); #endif #ifdef FEAT_CONCEAL clear_string_option(&wop->wo_cocu); #endif } /* * Copy global option values to local options for one buffer. * Used when creating a new buffer and sometimes when entering a buffer. * flags: * BCO_ENTER We will enter the buf buffer. * BCO_ALWAYS Always copy the options, but only set b_p_initialized when * appropriate. * BCO_NOHELP Don't copy the values to a help buffer. */ void buf_copy_options(buf, flags) buf_T *buf; int flags; { int should_copy = TRUE; char_u *save_p_isk = NULL; /* init for GCC */ int dont_do_help; int did_isk = FALSE; /* * Don't do anything if the buffer is invalid. */ if (buf == NULL || !buf_valid(buf)) return; /* * Skip this when the option defaults have not been set yet. Happens when * main() allocates the first buffer. */ if (p_cpo != NULL) { /* * Always copy when entering and 'cpo' contains 'S'. * Don't copy when already initialized. * Don't copy when 'cpo' contains 's' and not entering. * 'S' BCO_ENTER initialized 's' should_copy * yes yes X X TRUE * yes no yes X FALSE * no X yes X FALSE * X no no yes FALSE * X no no no TRUE * no yes no X TRUE */ if ((vim_strchr(p_cpo, CPO_BUFOPTGLOB) == NULL || !(flags & BCO_ENTER)) && (buf->b_p_initialized || (!(flags & BCO_ENTER) && vim_strchr(p_cpo, CPO_BUFOPT) != NULL))) should_copy = FALSE; if (should_copy || (flags & BCO_ALWAYS)) { /* Don't copy the options specific to a help buffer when * BCO_NOHELP is given or the options were initialized already * (jumping back to a help file with CTRL-T or CTRL-O) */ dont_do_help = ((flags & BCO_NOHELP) && buf->b_help) || buf->b_p_initialized; if (dont_do_help) /* don't free b_p_isk */ { save_p_isk = buf->b_p_isk; buf->b_p_isk = NULL; } /* * Always free the allocated strings. * If not already initialized, set 'readonly' and copy 'fileformat'. */ if (!buf->b_p_initialized) { free_buf_options(buf, TRUE); buf->b_p_ro = FALSE; /* don't copy readonly */ buf->b_p_tx = p_tx; #ifdef FEAT_MBYTE buf->b_p_fenc = vim_strsave(p_fenc); #endif buf->b_p_ff = vim_strsave(p_ff); #if defined(FEAT_QUICKFIX) buf->b_p_bh = empty_option; buf->b_p_bt = empty_option; #endif } else free_buf_options(buf, FALSE); buf->b_p_ai = p_ai; buf->b_p_ai_nopaste = p_ai_nopaste; buf->b_p_sw = p_sw; buf->b_p_tw = p_tw; buf->b_p_tw_nopaste = p_tw_nopaste; buf->b_p_tw_nobin = p_tw_nobin; buf->b_p_wm = p_wm; buf->b_p_wm_nopaste = p_wm_nopaste; buf->b_p_wm_nobin = p_wm_nobin; buf->b_p_bin = p_bin; #ifdef FEAT_MBYTE buf->b_p_bomb = p_bomb; #endif buf->b_p_et = p_et; buf->b_p_et_nobin = p_et_nobin; buf->b_p_ml = p_ml; buf->b_p_ml_nobin = p_ml_nobin; buf->b_p_inf = p_inf; buf->b_p_swf = p_swf; #ifdef FEAT_INS_EXPAND buf->b_p_cpt = vim_strsave(p_cpt); #endif #ifdef FEAT_COMPL_FUNC buf->b_p_cfu = vim_strsave(p_cfu); buf->b_p_ofu = vim_strsave(p_ofu); #endif buf->b_p_sts = p_sts; buf->b_p_sts_nopaste = p_sts_nopaste; #ifndef SHORT_FNAME buf->b_p_sn = p_sn; #endif #ifdef FEAT_COMMENTS buf->b_p_com = vim_strsave(p_com); #endif #ifdef FEAT_FOLDING buf->b_p_cms = vim_strsave(p_cms); #endif buf->b_p_fo = vim_strsave(p_fo); buf->b_p_flp = vim_strsave(p_flp); buf->b_p_nf = vim_strsave(p_nf); buf->b_p_mps = vim_strsave(p_mps); #ifdef FEAT_SMARTINDENT buf->b_p_si = p_si; #endif buf->b_p_ci = p_ci; #ifdef FEAT_CINDENT buf->b_p_cin = p_cin; buf->b_p_cink = vim_strsave(p_cink); buf->b_p_cino = vim_strsave(p_cino); #endif #ifdef FEAT_AUTOCMD /* Don't copy 'filetype', it must be detected */ buf->b_p_ft = empty_option; #endif buf->b_p_pi = p_pi; #if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT) buf->b_p_cinw = vim_strsave(p_cinw); #endif #ifdef FEAT_LISP buf->b_p_lisp = p_lisp; #endif #ifdef FEAT_SYN_HL /* Don't copy 'syntax', it must be set */ buf->b_p_syn = empty_option; buf->b_p_smc = p_smc; #endif #ifdef FEAT_SPELL buf->b_s.b_p_spc = vim_strsave(p_spc); (void)compile_cap_prog(&buf->b_s); buf->b_s.b_p_spf = vim_strsave(p_spf); buf->b_s.b_p_spl = vim_strsave(p_spl); #endif #if defined(FEAT_CINDENT) && defined(FEAT_EVAL) buf->b_p_inde = vim_strsave(p_inde); buf->b_p_indk = vim_strsave(p_indk); #endif #if defined(FEAT_EVAL) buf->b_p_fex = vim_strsave(p_fex); #endif #ifdef FEAT_CRYPT buf->b_p_key = vim_strsave(p_key); #endif #ifdef FEAT_SEARCHPATH buf->b_p_sua = vim_strsave(p_sua); #endif #ifdef FEAT_KEYMAP buf->b_p_keymap = vim_strsave(p_keymap); buf->b_kmap_state |= KEYMAP_INIT; #endif /* This isn't really an option, but copying the langmap and IME * state from the current buffer is better than resetting it. */ buf->b_p_iminsert = p_iminsert; buf->b_p_imsearch = p_imsearch; /* options that are normally global but also have a local value * are not copied, start using the global value */ buf->b_p_ar = -1; #ifdef FEAT_QUICKFIX buf->b_p_gp = empty_option; buf->b_p_mp = empty_option; buf->b_p_efm = empty_option; #endif buf->b_p_ep = empty_option; buf->b_p_kp = empty_option; buf->b_p_path = empty_option; buf->b_p_tags = empty_option; #ifdef FEAT_FIND_ID buf->b_p_def = empty_option; buf->b_p_inc = empty_option; # ifdef FEAT_EVAL buf->b_p_inex = vim_strsave(p_inex); # endif #endif #ifdef FEAT_INS_EXPAND buf->b_p_dict = empty_option; buf->b_p_tsr = empty_option; #endif #ifdef FEAT_TEXTOBJ buf->b_p_qe = vim_strsave(p_qe); #endif #if defined(FEAT_BEVAL) && defined(FEAT_EVAL) buf->b_p_bexpr = empty_option; #endif #if defined(FEAT_CRYPT) buf->b_p_cm = empty_option; #endif #ifdef FEAT_PERSISTENT_UNDO buf->b_p_udf = p_udf; #endif /* * Don't copy the options set by ex_help(), use the saved values, * when going from a help buffer to a non-help buffer. * Don't touch these at all when BCO_NOHELP is used and going from * or to a help buffer. */ if (dont_do_help) buf->b_p_isk = save_p_isk; else { buf->b_p_isk = vim_strsave(p_isk); did_isk = TRUE; buf->b_p_ts = p_ts; buf->b_help = FALSE; #ifdef FEAT_QUICKFIX if (buf->b_p_bt[0] == 'h') clear_string_option(&buf->b_p_bt); #endif buf->b_p_ma = p_ma; } } /* * When the options should be copied (ignoring BCO_ALWAYS), set the * flag that indicates that the options have been initialized. */ if (should_copy) buf->b_p_initialized = TRUE; } check_buf_options(buf); /* make sure we don't have NULLs */ if (did_isk) (void)buf_init_chartab(buf, FALSE); } /* * Reset the 'modifiable' option and its default value. */ void reset_modifiable() { int opt_idx; curbuf->b_p_ma = FALSE; p_ma = FALSE; opt_idx = findoption((char_u *)"ma"); if (opt_idx >= 0) options[opt_idx].def_val[VI_DEFAULT] = FALSE; } /* * Set the global value for 'iminsert' to the local value. */ void set_iminsert_global() { p_iminsert = curbuf->b_p_iminsert; } /* * Set the global value for 'imsearch' to the local value. */ void set_imsearch_global() { p_imsearch = curbuf->b_p_imsearch; } #if defined(FEAT_CMDL_COMPL) || defined(PROTO) static int expand_option_idx = -1; static char_u expand_option_name[5] = {'t', '_', NUL, NUL, NUL}; static int expand_option_flags = 0; void set_context_in_set_cmd(xp, arg, opt_flags) expand_T *xp; char_u *arg; int opt_flags; /* OPT_GLOBAL and/or OPT_LOCAL */ { int nextchar; long_u flags = 0; /* init for GCC */ int opt_idx = 0; /* init for GCC */ char_u *p; char_u *s; int is_term_option = FALSE; int key; expand_option_flags = opt_flags; xp->xp_context = EXPAND_SETTINGS; if (*arg == NUL) { xp->xp_pattern = arg; return; } p = arg + STRLEN(arg) - 1; if (*p == ' ' && *(p - 1) != '\\') { xp->xp_pattern = p + 1; return; } while (p > arg) { s = p; /* count number of backslashes before ' ' or ',' */ if (*p == ' ' || *p == ',') { while (s > arg && *(s - 1) == '\\') --s; } /* break at a space with an even number of backslashes */ if (*p == ' ' && ((p - s) & 1) == 0) { ++p; break; } --p; } if (STRNCMP(p, "no", 2) == 0 && STRNCMP(p, "novice", 6) != 0) { xp->xp_context = EXPAND_BOOL_SETTINGS; p += 2; } if (STRNCMP(p, "inv", 3) == 0) { xp->xp_context = EXPAND_BOOL_SETTINGS; p += 3; } xp->xp_pattern = arg = p; if (*arg == '<') { while (*p != '>') if (*p++ == NUL) /* expand terminal option name */ return; key = get_special_key_code(arg + 1); if (key == 0) /* unknown name */ { xp->xp_context = EXPAND_NOTHING; return; } nextchar = *++p; is_term_option = TRUE; expand_option_name[2] = KEY2TERMCAP0(key); expand_option_name[3] = KEY2TERMCAP1(key); } else { if (p[0] == 't' && p[1] == '_') { p += 2; if (*p != NUL) ++p; if (*p == NUL) return; /* expand option name */ nextchar = *++p; is_term_option = TRUE; expand_option_name[2] = p[-2]; expand_option_name[3] = p[-1]; } else { /* Allow * wildcard */ while (ASCII_ISALNUM(*p) || *p == '_' || *p == '*') p++; if (*p == NUL) return; nextchar = *p; *p = NUL; opt_idx = findoption(arg); *p = nextchar; if (opt_idx == -1 || options[opt_idx].var == NULL) { xp->xp_context = EXPAND_NOTHING; return; } flags = options[opt_idx].flags; if (flags & P_BOOL) { xp->xp_context = EXPAND_NOTHING; return; } } } /* handle "-=" and "+=" */ if ((nextchar == '-' || nextchar == '+' || nextchar == '^') && p[1] == '=') { ++p; nextchar = '='; } if ((nextchar != '=' && nextchar != ':') || xp->xp_context == EXPAND_BOOL_SETTINGS) { xp->xp_context = EXPAND_UNSUCCESSFUL; return; } if (xp->xp_context != EXPAND_BOOL_SETTINGS && p[1] == NUL) { xp->xp_context = EXPAND_OLD_SETTING; if (is_term_option) expand_option_idx = -1; else expand_option_idx = opt_idx; xp->xp_pattern = p + 1; return; } xp->xp_context = EXPAND_NOTHING; if (is_term_option || (flags & P_NUM)) return; xp->xp_pattern = p + 1; if (flags & P_EXPAND) { p = options[opt_idx].var; if (p == (char_u *)&p_bdir || p == (char_u *)&p_dir || p == (char_u *)&p_path || p == (char_u *)&p_rtp #ifdef FEAT_SEARCHPATH || p == (char_u *)&p_cdpath #endif #ifdef FEAT_SESSION || p == (char_u *)&p_vdir #endif ) { xp->xp_context = EXPAND_DIRECTORIES; if (p == (char_u *)&p_path #ifdef FEAT_SEARCHPATH || p == (char_u *)&p_cdpath #endif ) xp->xp_backslash = XP_BS_THREE; else xp->xp_backslash = XP_BS_ONE; } else { xp->xp_context = EXPAND_FILES; /* for 'tags' need three backslashes for a space */ if (p == (char_u *)&p_tags) xp->xp_backslash = XP_BS_THREE; else xp->xp_backslash = XP_BS_ONE; } } /* For an option that is a list of file names, find the start of the * last file name. */ for (p = arg + STRLEN(arg) - 1; p > xp->xp_pattern; --p) { /* count number of backslashes before ' ' or ',' */ if (*p == ' ' || *p == ',') { s = p; while (s > xp->xp_pattern && *(s - 1) == '\\') --s; if ((*p == ' ' && (xp->xp_backslash == XP_BS_THREE && (p - s) < 3)) || (*p == ',' && (flags & P_COMMA) && ((p - s) & 1) == 0)) { xp->xp_pattern = p + 1; break; } } #ifdef FEAT_SPELL /* for 'spellsuggest' start at "file:" */ if (options[opt_idx].var == (char_u *)&p_sps && STRNCMP(p, "file:", 5) == 0) { xp->xp_pattern = p + 5; break; } #endif } return; } int ExpandSettings(xp, regmatch, num_file, file) expand_T *xp; regmatch_T *regmatch; int *num_file; char_u ***file; { int num_normal = 0; /* Nr of matching non-term-code settings */ int num_term = 0; /* Nr of matching terminal code settings */ int opt_idx; int match; int count = 0; char_u *str; int loop; int is_term_opt; char_u name_buf[MAX_KEY_NAME_LEN]; static char *(names[]) = {"all", "termcap"}; int ic = regmatch->rm_ic; /* remember the ignore-case flag */ /* do this loop twice: * loop == 0: count the number of matching options * loop == 1: copy the matching options into allocated memory */ for (loop = 0; loop <= 1; ++loop) { regmatch->rm_ic = ic; if (xp->xp_context != EXPAND_BOOL_SETTINGS) { for (match = 0; match < (int)(sizeof(names) / sizeof(char *)); ++match) if (vim_regexec(regmatch, (char_u *)names[match], (colnr_T)0)) { if (loop == 0) num_normal++; else (*file)[count++] = vim_strsave((char_u *)names[match]); } } for (opt_idx = 0; (str = (char_u *)options[opt_idx].fullname) != NULL; opt_idx++) { if (options[opt_idx].var == NULL) continue; if (xp->xp_context == EXPAND_BOOL_SETTINGS && !(options[opt_idx].flags & P_BOOL)) continue; is_term_opt = istermoption(&options[opt_idx]); if (is_term_opt && num_normal > 0) continue; match = FALSE; if (vim_regexec(regmatch, str, (colnr_T)0) || (options[opt_idx].shortname != NULL && vim_regexec(regmatch, (char_u *)options[opt_idx].shortname, (colnr_T)0))) match = TRUE; else if (is_term_opt) { name_buf[0] = '<'; name_buf[1] = 't'; name_buf[2] = '_'; name_buf[3] = str[2]; name_buf[4] = str[3]; name_buf[5] = '>'; name_buf[6] = NUL; if (vim_regexec(regmatch, name_buf, (colnr_T)0)) { match = TRUE; str = name_buf; } } if (match) { if (loop == 0) { if (is_term_opt) num_term++; else num_normal++; } else (*file)[count++] = vim_strsave(str); } } /* * Check terminal key codes, these are not in the option table */ if (xp->xp_context != EXPAND_BOOL_SETTINGS && num_normal == 0) { for (opt_idx = 0; (str = get_termcode(opt_idx)) != NULL; opt_idx++) { if (!isprint(str[0]) || !isprint(str[1])) continue; name_buf[0] = 't'; name_buf[1] = '_'; name_buf[2] = str[0]; name_buf[3] = str[1]; name_buf[4] = NUL; match = FALSE; if (vim_regexec(regmatch, name_buf, (colnr_T)0)) match = TRUE; else { name_buf[0] = '<'; name_buf[1] = 't'; name_buf[2] = '_'; name_buf[3] = str[0]; name_buf[4] = str[1]; name_buf[5] = '>'; name_buf[6] = NUL; if (vim_regexec(regmatch, name_buf, (colnr_T)0)) match = TRUE; } if (match) { if (loop == 0) num_term++; else (*file)[count++] = vim_strsave(name_buf); } } /* * Check special key names. */ regmatch->rm_ic = TRUE; /* ignore case here */ for (opt_idx = 0; (str = get_key_name(opt_idx)) != NULL; opt_idx++) { name_buf[0] = '<'; STRCPY(name_buf + 1, str); STRCAT(name_buf, ">"); if (vim_regexec(regmatch, name_buf, (colnr_T)0)) { if (loop == 0) num_term++; else (*file)[count++] = vim_strsave(name_buf); } } } if (loop == 0) { if (num_normal > 0) *num_file = num_normal; else if (num_term > 0) *num_file = num_term; else return OK; *file = (char_u **)alloc((unsigned)(*num_file * sizeof(char_u *))); if (*file == NULL) { *file = (char_u **)""; return FAIL; } } } return OK; } int ExpandOldSetting(num_file, file) int *num_file; char_u ***file; { char_u *var = NULL; /* init for GCC */ char_u *buf; *num_file = 0; *file = (char_u **)alloc((unsigned)sizeof(char_u *)); if (*file == NULL) return FAIL; /* * For a terminal key code expand_option_idx is < 0. */ if (expand_option_idx < 0) { var = find_termcode(expand_option_name + 2); if (var == NULL) expand_option_idx = findoption(expand_option_name); } if (expand_option_idx >= 0) { /* put string of option value in NameBuff */ option_value2string(&options[expand_option_idx], expand_option_flags); var = NameBuff; } else if (var == NULL) var = (char_u *)""; /* A backslash is required before some characters. This is the reverse of * what happens in do_set(). */ buf = vim_strsave_escaped(var, escape_chars); if (buf == NULL) { vim_free(*file); *file = NULL; return FAIL; } #ifdef BACKSLASH_IN_FILENAME /* For MS-Windows et al. we don't double backslashes at the start and * before a file name character. */ for (var = buf; *var != NUL; mb_ptr_adv(var)) if (var[0] == '\\' && var[1] == '\\' && expand_option_idx >= 0 && (options[expand_option_idx].flags & P_EXPAND) && vim_isfilec(var[2]) && (var[2] != '\\' || (var == buf && var[4] != '\\'))) STRMOVE(var, var + 1); #endif *file[0] = buf; *num_file = 1; return OK; } #endif /* * Get the value for the numeric or string option *opp in a nice format into * NameBuff[]. Must not be called with a hidden option! */ static void option_value2string(opp, opt_flags) struct vimoption *opp; int opt_flags; /* OPT_GLOBAL and/or OPT_LOCAL */ { char_u *varp; varp = get_varp_scope(opp, opt_flags); if (opp->flags & P_NUM) { long wc = 0; if (wc_use_keyname(varp, &wc)) STRCPY(NameBuff, get_special_key_name((int)wc, 0)); else if (wc != 0) STRCPY(NameBuff, transchar((int)wc)); else sprintf((char *)NameBuff, "%ld", *(long *)varp); } else /* P_STRING */ { varp = *(char_u **)(varp); if (varp == NULL) /* just in case */ NameBuff[0] = NUL; #ifdef FEAT_CRYPT /* don't show the actual value of 'key', only that it's set */ else if (opp->var == (char_u *)&p_key && *varp) STRCPY(NameBuff, "*****"); #endif else if (opp->flags & P_EXPAND) home_replace(NULL, varp, NameBuff, MAXPATHL, FALSE); /* Translate 'pastetoggle' into special key names */ else if ((char_u **)opp->var == &p_pt) str2specialbuf(p_pt, NameBuff, MAXPATHL); else vim_strncpy(NameBuff, varp, MAXPATHL - 1); } } /* * Return TRUE if "varp" points to 'wildchar' or 'wildcharm' and it can be * printed as a keyname. * "*wcp" is set to the value of the option if it's 'wildchar' or 'wildcharm'. */ static int wc_use_keyname(varp, wcp) char_u *varp; long *wcp; { if (((long *)varp == &p_wc) || ((long *)varp == &p_wcm)) { *wcp = *(long *)varp; if (IS_SPECIAL(*wcp) || find_special_key_in_table((int)*wcp) >= 0) return TRUE; } return FALSE; } #ifdef FEAT_LANGMAP /* * Any character has an equivalent 'langmap' character. This is used for * keyboards that have a special language mode that sends characters above * 128 (although other characters can be translated too). The "to" field is a * Vim command character. This avoids having to switch the keyboard back to * ASCII mode when leaving Insert mode. * * langmap_mapchar[] maps any of 256 chars to an ASCII char used for Vim * commands. * When FEAT_MBYTE is defined langmap_mapga.ga_data is a sorted table of * langmap_entry_T. This does the same as langmap_mapchar[] for characters >= * 256. */ # ifdef FEAT_MBYTE /* * With multi-byte support use growarray for 'langmap' chars >= 256 */ typedef struct { int from; int to; } langmap_entry_T; static garray_T langmap_mapga; static void langmap_set_entry __ARGS((int from, int to)); /* * Search for an entry in "langmap_mapga" for "from". If found set the "to" * field. If not found insert a new entry at the appropriate location. */ static void langmap_set_entry(from, to) int from; int to; { langmap_entry_T *entries = (langmap_entry_T *)(langmap_mapga.ga_data); int a = 0; int b = langmap_mapga.ga_len; /* Do a binary search for an existing entry. */ while (a != b) { int i = (a + b) / 2; int d = entries[i].from - from; if (d == 0) { entries[i].to = to; return; } if (d < 0) a = i + 1; else b = i; } if (ga_grow(&langmap_mapga, 1) != OK) return; /* out of memory */ /* insert new entry at position "a" */ entries = (langmap_entry_T *)(langmap_mapga.ga_data) + a; mch_memmove(entries + 1, entries, (langmap_mapga.ga_len - a) * sizeof(langmap_entry_T)); ++langmap_mapga.ga_len; entries[0].from = from; entries[0].to = to; } /* * Apply 'langmap' to multi-byte character "c" and return the result. */ int langmap_adjust_mb(c) int c; { langmap_entry_T *entries = (langmap_entry_T *)(langmap_mapga.ga_data); int a = 0; int b = langmap_mapga.ga_len; while (a != b) { int i = (a + b) / 2; int d = entries[i].from - c; if (d == 0) return entries[i].to; /* found matching entry */ if (d < 0) a = i + 1; else b = i; } return c; /* no entry found, return "c" unmodified */ } # endif static void langmap_init() { int i; for (i = 0; i < 256; i++) langmap_mapchar[i] = i; /* we init with a one-to-one map */ # ifdef FEAT_MBYTE ga_init2(&langmap_mapga, sizeof(langmap_entry_T), 8); # endif } /* * Called when langmap option is set; the language map can be * changed at any time! */ static void langmap_set() { char_u *p; char_u *p2; int from, to; #ifdef FEAT_MBYTE ga_clear(&langmap_mapga); /* clear the previous map first */ #endif langmap_init(); /* back to one-to-one map */ for (p = p_langmap; p[0] != NUL; ) { for (p2 = p; p2[0] != NUL && p2[0] != ',' && p2[0] != ';'; mb_ptr_adv(p2)) { if (p2[0] == '\\' && p2[1] != NUL) ++p2; } if (p2[0] == ';') ++p2; /* abcd;ABCD form, p2 points to A */ else p2 = NULL; /* aAbBcCdD form, p2 is NULL */ while (p[0]) { if (p[0] == ',') { ++p; break; } if (p[0] == '\\' && p[1] != NUL) ++p; #ifdef FEAT_MBYTE from = (*mb_ptr2char)(p); #else from = p[0]; #endif to = NUL; if (p2 == NULL) { mb_ptr_adv(p); if (p[0] != ',') { if (p[0] == '\\') ++p; #ifdef FEAT_MBYTE to = (*mb_ptr2char)(p); #else to = p[0]; #endif } } else { if (p2[0] != ',') { if (p2[0] == '\\') ++p2; #ifdef FEAT_MBYTE to = (*mb_ptr2char)(p2); #else to = p2[0]; #endif } } if (to == NUL) { EMSG2(_("E357: 'langmap': Matching character missing for %s"), transchar(from)); return; } #ifdef FEAT_MBYTE if (from >= 256) langmap_set_entry(from, to); else #endif langmap_mapchar[from & 255] = to; /* Advance to next pair */ mb_ptr_adv(p); if (p2 != NULL) { mb_ptr_adv(p2); if (*p == ';') { p = p2; if (p[0] != NUL) { if (p[0] != ',') { EMSG2(_("E358: 'langmap': Extra characters after semicolon: %s"), p); return; } ++p; } break; } } } } } #endif /* * Return TRUE if format option 'x' is in effect. * Take care of no formatting when 'paste' is set. */ int has_format_option(x) int x; { if (p_paste) return FALSE; return (vim_strchr(curbuf->b_p_fo, x) != NULL); } /* * Return TRUE if "x" is present in 'shortmess' option, or * 'shortmess' contains 'a' and "x" is present in SHM_A. */ int shortmess(x) int x; { return p_shm != NULL && ( vim_strchr(p_shm, x) != NULL || (vim_strchr(p_shm, 'a') != NULL && vim_strchr((char_u *)SHM_A, x) != NULL)); } /* * paste_option_changed() - Called after p_paste was set or reset. */ static void paste_option_changed() { static int old_p_paste = FALSE; static int save_sm = 0; #ifdef FEAT_CMDL_INFO static int save_ru = 0; #endif #ifdef FEAT_RIGHTLEFT static int save_ri = 0; static int save_hkmap = 0; #endif buf_T *buf; if (p_paste) { /* * Paste switched from off to on. * Save the current values, so they can be restored later. */ if (!old_p_paste) { /* save options for each buffer */ for (buf = firstbuf; buf != NULL; buf = buf->b_next) { buf->b_p_tw_nopaste = buf->b_p_tw; buf->b_p_wm_nopaste = buf->b_p_wm; buf->b_p_sts_nopaste = buf->b_p_sts; buf->b_p_ai_nopaste = buf->b_p_ai; } /* save global options */ save_sm = p_sm; #ifdef FEAT_CMDL_INFO save_ru = p_ru; #endif #ifdef FEAT_RIGHTLEFT save_ri = p_ri; save_hkmap = p_hkmap; #endif /* save global values for local buffer options */ p_tw_nopaste = p_tw; p_wm_nopaste = p_wm; p_sts_nopaste = p_sts; p_ai_nopaste = p_ai; } /* * Always set the option values, also when 'paste' is set when it is * already on. */ /* set options for each buffer */ for (buf = firstbuf; buf != NULL; buf = buf->b_next) { buf->b_p_tw = 0; /* textwidth is 0 */ buf->b_p_wm = 0; /* wrapmargin is 0 */ buf->b_p_sts = 0; /* softtabstop is 0 */ buf->b_p_ai = 0; /* no auto-indent */ } /* set global options */ p_sm = 0; /* no showmatch */ #ifdef FEAT_CMDL_INFO # ifdef FEAT_WINDOWS if (p_ru) status_redraw_all(); /* redraw to remove the ruler */ # endif p_ru = 0; /* no ruler */ #endif #ifdef FEAT_RIGHTLEFT p_ri = 0; /* no reverse insert */ p_hkmap = 0; /* no Hebrew keyboard */ #endif /* set global values for local buffer options */ p_tw = 0; p_wm = 0; p_sts = 0; p_ai = 0; } /* * Paste switched from on to off: Restore saved values. */ else if (old_p_paste) { /* restore options for each buffer */ for (buf = firstbuf; buf != NULL; buf = buf->b_next) { buf->b_p_tw = buf->b_p_tw_nopaste; buf->b_p_wm = buf->b_p_wm_nopaste; buf->b_p_sts = buf->b_p_sts_nopaste; buf->b_p_ai = buf->b_p_ai_nopaste; } /* restore global options */ p_sm = save_sm; #ifdef FEAT_CMDL_INFO # ifdef FEAT_WINDOWS if (p_ru != save_ru) status_redraw_all(); /* redraw to draw the ruler */ # endif p_ru = save_ru; #endif #ifdef FEAT_RIGHTLEFT p_ri = save_ri; p_hkmap = save_hkmap; #endif /* set global values for local buffer options */ p_tw = p_tw_nopaste; p_wm = p_wm_nopaste; p_sts = p_sts_nopaste; p_ai = p_ai_nopaste; } old_p_paste = p_paste; } /* * vimrc_found() - Called when a ".vimrc" or "VIMINIT" has been found. * * Reset 'compatible' and set the values for options that didn't get set yet * to the Vim defaults. * Don't do this if the 'compatible' option has been set or reset before. * When "fname" is not NULL, use it to set $"envname" when it wasn't set yet. */ void vimrc_found(fname, envname) char_u *fname; char_u *envname; { int opt_idx; int dofree = FALSE; char_u *p; if (!option_was_set((char_u *)"cp")) { p_cp = FALSE; for (opt_idx = 0; !istermoption(&options[opt_idx]); opt_idx++) if (!(options[opt_idx].flags & (P_WAS_SET|P_VI_DEF))) set_option_default(opt_idx, OPT_FREE, FALSE); didset_options(); } if (fname != NULL) { p = vim_getenv(envname, &dofree); if (p == NULL) { /* Set $MYVIMRC to the first vimrc file found. */ p = FullName_save(fname, FALSE); if (p != NULL) { vim_setenv(envname, p); vim_free(p); } } else if (dofree) vim_free(p); } } /* * Set 'compatible' on or off. Called for "-C" and "-N" command line arg. */ void change_compatible(on) int on; { int opt_idx; if (p_cp != on) { p_cp = on; compatible_set(); } opt_idx = findoption((char_u *)"cp"); if (opt_idx >= 0) options[opt_idx].flags |= P_WAS_SET; } /* * Return TRUE when option "name" has been set. */ int option_was_set(name) char_u *name; { int idx; idx = findoption(name); if (idx < 0) /* unknown option */ return FALSE; if (options[idx].flags & P_WAS_SET) return TRUE; return FALSE; } /* * compatible_set() - Called when 'compatible' has been set or unset. * * When 'compatible' set: Set all relevant options (those that have the P_VIM) * flag) to a Vi compatible value. * When 'compatible' is unset: Set all options that have a different default * for Vim (without the P_VI_DEF flag) to that default. */ static void compatible_set() { int opt_idx; for (opt_idx = 0; !istermoption(&options[opt_idx]); opt_idx++) if ( ((options[opt_idx].flags & P_VIM) && p_cp) || (!(options[opt_idx].flags & P_VI_DEF) && !p_cp)) set_option_default(opt_idx, OPT_FREE, p_cp); didset_options(); } #ifdef FEAT_LINEBREAK # if defined(__BORLANDC__) && (__BORLANDC__ < 0x500) /* Borland C++ screws up loop optimisation here (negri) */ #pragma option -O-l # endif /* * fill_breakat_flags() -- called when 'breakat' changes value. */ static void fill_breakat_flags() { char_u *p; int i; for (i = 0; i < 256; i++) breakat_flags[i] = FALSE; if (p_breakat != NULL) for (p = p_breakat; *p; p++) breakat_flags[*p] = TRUE; } # if defined(__BORLANDC__) && (__BORLANDC__ < 0x500) #pragma option -O.l # endif #endif /* * Check an option that can be a range of string values. * * Return OK for correct value, FAIL otherwise. * Empty is always OK. */ static int check_opt_strings(val, values, list) char_u *val; char **values; int list; /* when TRUE: accept a list of values */ { return opt_strings_flags(val, values, NULL, list); } /* * Handle an option that can be a range of string values. * Set a flag in "*flagp" for each string present. * * Return OK for correct value, FAIL otherwise. * Empty is always OK. */ static int opt_strings_flags(val, values, flagp, list) char_u *val; /* new value */ char **values; /* array of valid string values */ unsigned *flagp; int list; /* when TRUE: accept a list of values */ { int i; int len; unsigned new_flags = 0; while (*val) { for (i = 0; ; ++i) { if (values[i] == NULL) /* val not found in values[] */ return FAIL; len = (int)STRLEN(values[i]); if (STRNCMP(values[i], val, len) == 0 && ((list && val[len] == ',') || val[len] == NUL)) { val += len + (val[len] == ','); new_flags |= (1 << i); break; /* check next item in val list */ } } } if (flagp != NULL) *flagp = new_flags; return OK; } /* * Read the 'wildmode' option, fill wim_flags[]. */ static int check_opt_wim() { char_u new_wim_flags[4]; char_u *p; int i; int idx = 0; for (i = 0; i < 4; ++i) new_wim_flags[i] = 0; for (p = p_wim; *p; ++p) { for (i = 0; ASCII_ISALPHA(p[i]); ++i) ; if (p[i] != NUL && p[i] != ',' && p[i] != ':') return FAIL; if (i == 7 && STRNCMP(p, "longest", 7) == 0) new_wim_flags[idx] |= WIM_LONGEST; else if (i == 4 && STRNCMP(p, "full", 4) == 0) new_wim_flags[idx] |= WIM_FULL; else if (i == 4 && STRNCMP(p, "list", 4) == 0) new_wim_flags[idx] |= WIM_LIST; else return FAIL; p += i; if (*p == NUL) break; if (*p == ',') { if (idx == 3) return FAIL; ++idx; } } /* fill remaining entries with last flag */ while (idx < 3) { new_wim_flags[idx + 1] = new_wim_flags[idx]; ++idx; } /* only when there are no errors, wim_flags[] is changed */ for (i = 0; i < 4; ++i) wim_flags[i] = new_wim_flags[i]; return OK; } /* * Check if backspacing over something is allowed. */ int can_bs(what) int what; /* BS_INDENT, BS_EOL or BS_START */ { switch (*p_bs) { case '2': return TRUE; case '1': return (what != BS_START); case '0': return FALSE; } return vim_strchr(p_bs, what) != NULL; } /* * Save the current values of 'fileformat' and 'fileencoding', so that we know * the file must be considered changed when the value is different. */ void save_file_ff(buf) buf_T *buf; { buf->b_start_ffc = *buf->b_p_ff; buf->b_start_eol = buf->b_p_eol; #ifdef FEAT_MBYTE buf->b_start_bomb = buf->b_p_bomb; /* Only use free/alloc when necessary, they take time. */ if (buf->b_start_fenc == NULL || STRCMP(buf->b_start_fenc, buf->b_p_fenc) != 0) { vim_free(buf->b_start_fenc); buf->b_start_fenc = vim_strsave(buf->b_p_fenc); } #endif } /* * Return TRUE if 'fileformat' and/or 'fileencoding' has a different value * from when editing started (save_file_ff() called). * Also when 'endofline' was changed and 'binary' is set, or when 'bomb' was * changed and 'binary' is not set. * When "ignore_empty" is true don't consider a new, empty buffer to be * changed. */ int file_ff_differs(buf, ignore_empty) buf_T *buf; int ignore_empty; { /* In a buffer that was never loaded the options are not valid. */ if (buf->b_flags & BF_NEVERLOADED) return FALSE; if (ignore_empty && (buf->b_flags & BF_NEW) && buf->b_ml.ml_line_count == 1 && *ml_get_buf(buf, (linenr_T)1, FALSE) == NUL) return FALSE; if (buf->b_start_ffc != *buf->b_p_ff) return TRUE; if (buf->b_p_bin && buf->b_start_eol != buf->b_p_eol) return TRUE; #ifdef FEAT_MBYTE if (!buf->b_p_bin && buf->b_start_bomb != buf->b_p_bomb) return TRUE; if (buf->b_start_fenc == NULL) return (*buf->b_p_fenc != NUL); return (STRCMP(buf->b_start_fenc, buf->b_p_fenc) != 0); #else return FALSE; #endif } /* * return OK if "p" is a valid fileformat name, FAIL otherwise. */ int check_ff_value(p) char_u *p; { return check_opt_strings(p, p_ff_values, FALSE); }
zyz2011-vim
src/option.c
C
gpl2
299,448
/* vi:set ts=8 sts=4 sw=4: * * CSCOPE support for Vim added by Andy Kahn <kahn@zk3.dec.com> * Ported to Win32 by Sergey Khorev <sergey.khorev@gmail.com> * * The basic idea/structure of cscope for Vim was borrowed from Nvi. There * might be a few lines of code that look similar to what Nvi has. * * See README.txt for an overview of the Vim source code. */ #include "vim.h" #if defined(FEAT_CSCOPE) || defined(PROTO) #include <sys/types.h> #include <sys/stat.h> #if defined(UNIX) # include <sys/wait.h> #endif #include "if_cscope.h" static void cs_usage_msg __ARGS((csid_e x)); static int cs_add __ARGS((exarg_T *eap)); static void cs_stat_emsg __ARGS((char *fname)); static int cs_add_common __ARGS((char *, char *, char *)); static int cs_check_for_connections __ARGS((void)); static int cs_check_for_tags __ARGS((void)); static int cs_cnt_connections __ARGS((void)); static void cs_reading_emsg __ARGS((int idx)); static int cs_cnt_matches __ARGS((int idx)); static char * cs_create_cmd __ARGS((char *csoption, char *pattern)); static int cs_create_connection __ARGS((int i)); static void do_cscope_general __ARGS((exarg_T *eap, int make_split)); #ifdef FEAT_QUICKFIX static void cs_file_results __ARGS((FILE *, int *)); #endif static void cs_fill_results __ARGS((char *, int , int *, char ***, char ***, int *)); static int cs_find __ARGS((exarg_T *eap)); static int cs_find_common __ARGS((char *opt, char *pat, int, int, int, char_u *cmdline)); static int cs_help __ARGS((exarg_T *eap)); static void clear_csinfo __ARGS((int i)); static int cs_insert_filelist __ARGS((char *, char *, char *, struct stat *)); static int cs_kill __ARGS((exarg_T *eap)); static void cs_kill_execute __ARGS((int, char *)); static cscmd_T * cs_lookup_cmd __ARGS((exarg_T *eap)); static char * cs_make_vim_style_matches __ARGS((char *, char *, char *, char *)); static char * cs_manage_matches __ARGS((char **, char **, int, mcmd_e)); static char * cs_parse_results __ARGS((int cnumber, char *buf, int bufsize, char **context, char **linenumber, char **search)); static char * cs_pathcomponents __ARGS((char *path)); static void cs_print_tags_priv __ARGS((char **, char **, int)); static int cs_read_prompt __ARGS((int)); static void cs_release_csp __ARGS((int, int freefnpp)); static int cs_reset __ARGS((exarg_T *eap)); static char * cs_resolve_file __ARGS((int, char *)); static int cs_show __ARGS((exarg_T *eap)); static csinfo_T * csinfo = NULL; static int csinfo_size = 0; /* number of items allocated in csinfo[] */ static int eap_arg_len; /* length of eap->arg, set in cs_lookup_cmd() */ static cscmd_T cs_cmds[] = { { "add", cs_add, N_("Add a new database"), "add file|dir [pre-path] [flags]", 0 }, { "find", cs_find, N_("Query for a pattern"), "find c|d|e|f|g|i|s|t name", 1 }, { "help", cs_help, N_("Show this message"), "help", 0 }, { "kill", cs_kill, N_("Kill a connection"), "kill #", 0 }, { "reset", cs_reset, N_("Reinit all connections"), "reset", 0 }, { "show", cs_show, N_("Show connections"), "show", 0 }, { NULL, NULL, NULL, NULL, 0 } }; static void cs_usage_msg(x) csid_e x; { (void)EMSG2(_("E560: Usage: cs[cope] %s"), cs_cmds[(int)x].usage); } #if defined(FEAT_CMDL_COMPL) || defined(PROTO) static enum { EXP_CSCOPE_SUBCMD, /* expand ":cscope" sub-commands */ EXP_SCSCOPE_SUBCMD, /* expand ":scscope" sub-commands */ EXP_CSCOPE_FIND, /* expand ":cscope find" arguments */ EXP_CSCOPE_KILL /* expand ":cscope kill" arguments */ } expand_what; /* * Function given to ExpandGeneric() to obtain the cscope command * expansion. */ char_u * get_cscope_name(xp, idx) expand_T *xp UNUSED; int idx; { int current_idx; int i; switch (expand_what) { case EXP_CSCOPE_SUBCMD: /* Complete with sub-commands of ":cscope": * add, find, help, kill, reset, show */ return (char_u *)cs_cmds[idx].name; case EXP_SCSCOPE_SUBCMD: /* Complete with sub-commands of ":scscope": same sub-commands as * ":cscope" but skip commands which don't support split windows */ for (i = 0, current_idx = 0; cs_cmds[i].name != NULL; i++) if (cs_cmds[i].cansplit) if (current_idx++ == idx) break; return (char_u *)cs_cmds[i].name; case EXP_CSCOPE_FIND: { const char *query_type[] = { "c", "d", "e", "f", "g", "i", "s", "t", NULL }; /* Complete with query type of ":cscope find {query_type}". * {query_type} can be letters (c, d, ... t) or numbers (0, 1, * ..., 8) but only complete with letters, since numbers are * redundant. */ return (char_u *)query_type[idx]; } case EXP_CSCOPE_KILL: { static char connection[5]; /* ":cscope kill" accepts connection numbers or partial names of * the pathname of the cscope database as argument. Only complete * with connection numbers. -1 can also be used to kill all * connections. */ for (i = 0, current_idx = 0; i < csinfo_size; i++) { if (csinfo[i].fname == NULL) continue; if (current_idx++ == idx) { vim_snprintf(connection, sizeof(connection), "%d", i); return (char_u *)connection; } } return (current_idx == idx && idx > 0) ? (char_u *)"-1" : NULL; } default: return NULL; } } /* * Handle command line completion for :cscope command. */ void set_context_in_cscope_cmd(xp, arg, cmdidx) expand_T *xp; char_u *arg; cmdidx_T cmdidx; { char_u *p; /* Default: expand subcommands */ xp->xp_context = EXPAND_CSCOPE; xp->xp_pattern = arg; expand_what = (cmdidx == CMD_scscope) ? EXP_SCSCOPE_SUBCMD : EXP_CSCOPE_SUBCMD; /* (part of) subcommand already typed */ if (*arg != NUL) { p = skiptowhite(arg); if (*p != NUL) /* past first word */ { xp->xp_pattern = skipwhite(p); if (*skiptowhite(xp->xp_pattern) != NUL) xp->xp_context = EXPAND_NOTHING; else if (STRNICMP(arg, "add", p - arg) == 0) xp->xp_context = EXPAND_FILES; else if (STRNICMP(arg, "kill", p - arg) == 0) expand_what = EXP_CSCOPE_KILL; else if (STRNICMP(arg, "find", p - arg) == 0) expand_what = EXP_CSCOPE_FIND; else xp->xp_context = EXPAND_NOTHING; } } } #endif /* FEAT_CMDL_COMPL */ /* * PRIVATE: do_cscope_general * * Find the command, print help if invalid, and then call the corresponding * command function. */ static void do_cscope_general(eap, make_split) exarg_T *eap; int make_split; /* whether to split window */ { cscmd_T *cmdp; if ((cmdp = cs_lookup_cmd(eap)) == NULL) { cs_help(eap); return; } #ifdef FEAT_WINDOWS if (make_split) { if (!cmdp->cansplit) { (void)MSG_PUTS(_("This cscope command does not support splitting the window.\n")); return; } postponed_split = -1; postponed_split_flags = cmdmod.split; postponed_split_tab = cmdmod.tab; } #endif cmdp->func(eap); #ifdef FEAT_WINDOWS postponed_split_flags = 0; postponed_split_tab = 0; #endif } /* * PUBLIC: do_cscope */ void do_cscope(eap) exarg_T *eap; { do_cscope_general(eap, FALSE); } /* * PUBLIC: do_scscope * * same as do_cscope, but splits window, too. */ void do_scscope(eap) exarg_T *eap; { do_cscope_general(eap, TRUE); } /* * PUBLIC: do_cstag * */ void do_cstag(eap) exarg_T *eap; { int ret = FALSE; if (*eap->arg == NUL) { (void)EMSG(_("E562: Usage: cstag <ident>")); return; } switch (p_csto) { case 0 : if (cs_check_for_connections()) { ret = cs_find_common("g", (char *)(eap->arg), eap->forceit, FALSE, FALSE, *eap->cmdlinep); if (ret == FALSE) { cs_free_tags(); if (msg_col) msg_putchar('\n'); if (cs_check_for_tags()) ret = do_tag(eap->arg, DT_JUMP, 0, eap->forceit, FALSE); } } else if (cs_check_for_tags()) { ret = do_tag(eap->arg, DT_JUMP, 0, eap->forceit, FALSE); } break; case 1 : if (cs_check_for_tags()) { ret = do_tag(eap->arg, DT_JUMP, 0, eap->forceit, FALSE); if (ret == FALSE) { if (msg_col) msg_putchar('\n'); if (cs_check_for_connections()) { ret = cs_find_common("g", (char *)(eap->arg), eap->forceit, FALSE, FALSE, *eap->cmdlinep); if (ret == FALSE) cs_free_tags(); } } } else if (cs_check_for_connections()) { ret = cs_find_common("g", (char *)(eap->arg), eap->forceit, FALSE, FALSE, *eap->cmdlinep); if (ret == FALSE) cs_free_tags(); } break; default : break; } if (!ret) { (void)EMSG(_("E257: cstag: tag not found")); #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX) g_do_tagpreview = 0; #endif } } /* do_cscope */ /* * PUBLIC: cs_find * * this simulates a vim_fgets(), but for cscope, returns the next line * from the cscope output. should only be called from find_tags() * * returns TRUE if eof, FALSE otherwise */ int cs_fgets(buf, size) char_u *buf; int size; { char *p; if ((p = cs_manage_matches(NULL, NULL, -1, Get)) == NULL) return TRUE; vim_strncpy(buf, (char_u *)p, size - 1); return FALSE; } /* cs_fgets */ /* * PUBLIC: cs_free_tags * * called only from do_tag(), when popping the tag stack */ void cs_free_tags() { cs_manage_matches(NULL, NULL, -1, Free); } /* * PUBLIC: cs_print_tags * * called from do_tag() */ void cs_print_tags() { cs_manage_matches(NULL, NULL, -1, Print); } /* * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function * * Checks for the existence of a |cscope| connection. If no * parameters are specified, then the function returns: * * 0, if cscope was not available (not compiled in), or if there * are no cscope connections; or * 1, if there is at least one cscope connection. * * If parameters are specified, then the value of {num} * determines how existence of a cscope connection is checked: * * {num} Description of existence check * ----- ------------------------------ * 0 Same as no parameters (e.g., "cscope_connection()"). * 1 Ignore {prepend}, and use partial string matches for * {dbpath}. * 2 Ignore {prepend}, and use exact string matches for * {dbpath}. * 3 Use {prepend}, use partial string matches for both * {dbpath} and {prepend}. * 4 Use {prepend}, use exact string matches for both * {dbpath} and {prepend}. * * Note: All string comparisons are case sensitive! */ #if defined(FEAT_EVAL) || defined(PROTO) int cs_connection(num, dbpath, ppath) int num; char_u *dbpath; char_u *ppath; { int i; if (num < 0 || num > 4 || (num > 0 && !dbpath)) return FALSE; for (i = 0; i < csinfo_size; i++) { if (!csinfo[i].fname) continue; if (num == 0) return TRUE; switch (num) { case 1: if (strstr(csinfo[i].fname, (char *)dbpath)) return TRUE; break; case 2: if (strcmp(csinfo[i].fname, (char *)dbpath) == 0) return TRUE; break; case 3: if (strstr(csinfo[i].fname, (char *)dbpath) && ((!ppath && !csinfo[i].ppath) || (ppath && csinfo[i].ppath && strstr(csinfo[i].ppath, (char *)ppath)))) return TRUE; break; case 4: if ((strcmp(csinfo[i].fname, (char *)dbpath) == 0) && ((!ppath && !csinfo[i].ppath) || (ppath && csinfo[i].ppath && (strcmp(csinfo[i].ppath, (char *)ppath) == 0)))) return TRUE; break; } } return FALSE; } /* cs_connection */ #endif /* * PRIVATE functions ****************************************************************************/ /* * PRIVATE: cs_add * * add cscope database or a directory name (to look for cscope.out) * to the cscope connection list * * MAXPATHL 256 */ static int cs_add(eap) exarg_T *eap UNUSED; { char *fname, *ppath, *flags = NULL; if ((fname = strtok((char *)NULL, (const char *)" ")) == NULL) { cs_usage_msg(Add); return CSCOPE_FAILURE; } if ((ppath = strtok((char *)NULL, (const char *)" ")) != NULL) flags = strtok((char *)NULL, (const char *)" "); return cs_add_common(fname, ppath, flags); } static void cs_stat_emsg(fname) char *fname; { char *stat_emsg = _("E563: stat(%s) error: %d"); char *buf = (char *)alloc((unsigned)strlen(stat_emsg) + MAXPATHL + 10); if (buf != NULL) { (void)sprintf(buf, stat_emsg, fname, errno); (void)EMSG(buf); vim_free(buf); } else (void)EMSG(_("E563: stat error")); } /* * PRIVATE: cs_add_common * * the common routine to add a new cscope connection. called by * cs_add() and cs_reset(). i really don't like to do this, but this * routine uses a number of goto statements. */ static int cs_add_common(arg1, arg2, flags) char *arg1; /* filename - may contain environment variables */ char *arg2; /* prepend path - may contain environment variables */ char *flags; { struct stat statbuf; int ret; char *fname = NULL; char *fname2 = NULL; char *ppath = NULL; int i; /* get the filename (arg1), expand it, and try to stat it */ if ((fname = (char *)alloc(MAXPATHL + 1)) == NULL) goto add_err; expand_env((char_u *)arg1, (char_u *)fname, MAXPATHL); ret = stat(fname, &statbuf); if (ret < 0) { staterr: if (p_csverbose) cs_stat_emsg(fname); goto add_err; } /* get the prepend path (arg2), expand it, and try to stat it */ if (arg2 != NULL) { struct stat statbuf2; if ((ppath = (char *)alloc(MAXPATHL + 1)) == NULL) goto add_err; expand_env((char_u *)arg2, (char_u *)ppath, MAXPATHL); ret = stat(ppath, &statbuf2); if (ret < 0) goto staterr; } /* if filename is a directory, append the cscope database name to it */ if ((statbuf.st_mode & S_IFMT) == S_IFDIR) { fname2 = (char *)alloc((unsigned)(strlen(CSCOPE_DBFILE) + strlen(fname) + 2)); if (fname2 == NULL) goto add_err; while (fname[strlen(fname)-1] == '/' #ifdef WIN32 || fname[strlen(fname)-1] == '\\' #endif ) { fname[strlen(fname)-1] = '\0'; if (fname[0] == '\0') break; } if (fname[0] == '\0') (void)sprintf(fname2, "/%s", CSCOPE_DBFILE); else (void)sprintf(fname2, "%s/%s", fname, CSCOPE_DBFILE); ret = stat(fname2, &statbuf); if (ret < 0) { if (p_csverbose) cs_stat_emsg(fname2); goto add_err; } i = cs_insert_filelist(fname2, ppath, flags, &statbuf); } #if defined(UNIX) else if (S_ISREG(statbuf.st_mode) || S_ISLNK(statbuf.st_mode)) #else /* WIN32 - substitute define S_ISREG from os_unix.h */ else if (((statbuf.st_mode) & S_IFMT) == S_IFREG) #endif { i = cs_insert_filelist(fname, ppath, flags, &statbuf); } else { if (p_csverbose) (void)EMSG2( _("E564: %s is not a directory or a valid cscope database"), fname); goto add_err; } if (i != -1) { if (cs_create_connection(i) == CSCOPE_FAILURE || cs_read_prompt(i) == CSCOPE_FAILURE) { cs_release_csp(i, TRUE); goto add_err; } if (p_csverbose) { msg_clr_eos(); (void)smsg_attr(hl_attr(HLF_R), (char_u *)_("Added cscope database %s"), csinfo[i].fname); } } vim_free(fname); vim_free(fname2); vim_free(ppath); return CSCOPE_SUCCESS; add_err: vim_free(fname2); vim_free(fname); vim_free(ppath); return CSCOPE_FAILURE; } /* cs_add_common */ static int cs_check_for_connections() { return (cs_cnt_connections() > 0); } /* cs_check_for_connections */ static int cs_check_for_tags() { return (p_tags[0] != NUL && curbuf->b_p_tags != NULL); } /* cs_check_for_tags */ /* * PRIVATE: cs_cnt_connections * * count the number of cscope connections */ static int cs_cnt_connections() { short i; short cnt = 0; for (i = 0; i < csinfo_size; i++) { if (csinfo[i].fname != NULL) cnt++; } return cnt; } /* cs_cnt_connections */ static void cs_reading_emsg(idx) int idx; /* connection index */ { EMSGN(_("E262: error reading cscope connection %ld"), idx); } #define CSREAD_BUFSIZE 2048 /* * PRIVATE: cs_cnt_matches * * count the number of matches for a given cscope connection. */ static int cs_cnt_matches(idx) int idx; { char *stok; char *buf; int nlines; buf = (char *)alloc(CSREAD_BUFSIZE); if (buf == NULL) return 0; for (;;) { if (!fgets(buf, CSREAD_BUFSIZE, csinfo[idx].fr_fp)) { if (feof(csinfo[idx].fr_fp)) errno = EIO; cs_reading_emsg(idx); vim_free(buf); return -1; } /* * If the database is out of date, or there's some other problem, * cscope will output error messages before the number-of-lines output. * Display/discard any output that doesn't match what we want. * Accept "\S*cscope: X lines", also matches "mlcscope". */ if ((stok = strtok(buf, (const char *)" ")) == NULL) continue; if (strstr((const char *)stok, "cscope:") == NULL) continue; if ((stok = strtok(NULL, (const char *)" ")) == NULL) continue; nlines = atoi(stok); if (nlines < 0) { nlines = 0; break; } if ((stok = strtok(NULL, (const char *)" ")) == NULL) continue; if (strncmp((const char *)stok, "lines", 5)) continue; break; } vim_free(buf); return nlines; } /* cs_cnt_matches */ /* * PRIVATE: cs_create_cmd * * Creates the actual cscope command query from what the user entered. */ static char * cs_create_cmd(csoption, pattern) char *csoption; char *pattern; { char *cmd; short search; char *pat; switch (csoption[0]) { case '0' : case 's' : search = 0; break; case '1' : case 'g' : search = 1; break; case '2' : case 'd' : search = 2; break; case '3' : case 'c' : search = 3; break; case '4' : case 't' : search = 4; break; case '6' : case 'e' : search = 6; break; case '7' : case 'f' : search = 7; break; case '8' : case 'i' : search = 8; break; default : (void)EMSG(_("E561: unknown cscope search type")); cs_usage_msg(Find); return NULL; } /* Skip white space before the patter, except for text and pattern search, * they may want to use the leading white space. */ pat = pattern; if (search != 4 && search != 6) while vim_iswhite(*pat) ++pat; if ((cmd = (char *)alloc((unsigned)(strlen(pat) + 2))) == NULL) return NULL; (void)sprintf(cmd, "%d%s", search, pat); return cmd; } /* cs_create_cmd */ /* * PRIVATE: cs_create_connection * * This piece of code was taken/adapted from nvi. do we need to add * the BSD license notice? */ static int cs_create_connection(i) int i; { #ifdef UNIX int to_cs[2], from_cs[2]; #endif int len; char *prog, *cmd, *ppath = NULL; #ifdef WIN32 int fd; SECURITY_ATTRIBUTES sa; PROCESS_INFORMATION pi; STARTUPINFO si; BOOL pipe_stdin = FALSE, pipe_stdout = FALSE; HANDLE stdin_rd, stdout_rd; HANDLE stdout_wr, stdin_wr; BOOL created; # ifdef __BORLANDC__ # define OPEN_OH_ARGTYPE long # else # if (_MSC_VER >= 1300) # define OPEN_OH_ARGTYPE intptr_t # else # define OPEN_OH_ARGTYPE long # endif # endif #endif #if defined(UNIX) /* * Cscope reads from to_cs[0] and writes to from_cs[1]; vi reads from * from_cs[0] and writes to to_cs[1]. */ to_cs[0] = to_cs[1] = from_cs[0] = from_cs[1] = -1; if (pipe(to_cs) < 0 || pipe(from_cs) < 0) { (void)EMSG(_("E566: Could not create cscope pipes")); err_closing: if (to_cs[0] != -1) (void)close(to_cs[0]); if (to_cs[1] != -1) (void)close(to_cs[1]); if (from_cs[0] != -1) (void)close(from_cs[0]); if (from_cs[1] != -1) (void)close(from_cs[1]); return CSCOPE_FAILURE; } switch (csinfo[i].pid = fork()) { case -1: (void)EMSG(_("E622: Could not fork for cscope")); goto err_closing; case 0: /* child: run cscope. */ if (dup2(to_cs[0], STDIN_FILENO) == -1) PERROR("cs_create_connection 1"); if (dup2(from_cs[1], STDOUT_FILENO) == -1) PERROR("cs_create_connection 2"); if (dup2(from_cs[1], STDERR_FILENO) == -1) PERROR("cs_create_connection 3"); /* close unused */ (void)close(to_cs[1]); (void)close(from_cs[0]); #else /* WIN32 */ /* Create pipes to communicate with cscope */ sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = NULL; if (!(pipe_stdin = CreatePipe(&stdin_rd, &stdin_wr, &sa, 0)) || !(pipe_stdout = CreatePipe(&stdout_rd, &stdout_wr, &sa, 0))) { (void)EMSG(_("E566: Could not create cscope pipes")); err_closing: if (pipe_stdin) { CloseHandle(stdin_rd); CloseHandle(stdin_wr); } if (pipe_stdout) { CloseHandle(stdout_rd); CloseHandle(stdout_wr); } return CSCOPE_FAILURE; } #endif /* expand the cscope exec for env var's */ if ((prog = (char *)alloc(MAXPATHL + 1)) == NULL) { #ifdef UNIX return CSCOPE_FAILURE; #else /* WIN32 */ goto err_closing; #endif } expand_env((char_u *)p_csprg, (char_u *)prog, MAXPATHL); /* alloc space to hold the cscope command */ len = (int)(strlen(prog) + strlen(csinfo[i].fname) + 32); if (csinfo[i].ppath) { /* expand the prepend path for env var's */ if ((ppath = (char *)alloc(MAXPATHL + 1)) == NULL) { vim_free(prog); #ifdef UNIX return CSCOPE_FAILURE; #else /* WIN32 */ goto err_closing; #endif } expand_env((char_u *)csinfo[i].ppath, (char_u *)ppath, MAXPATHL); len += (int)strlen(ppath); } if (csinfo[i].flags) len += (int)strlen(csinfo[i].flags); if ((cmd = (char *)alloc(len)) == NULL) { vim_free(prog); vim_free(ppath); #ifdef UNIX return CSCOPE_FAILURE; #else /* WIN32 */ goto err_closing; #endif } /* run the cscope command; is there execl for non-unix systems? */ #if defined(UNIX) (void)sprintf(cmd, "exec %s -dl -f %s", prog, csinfo[i].fname); #else /* WIN32 */ (void)sprintf(cmd, "%s -dl -f %s", prog, csinfo[i].fname); #endif if (csinfo[i].ppath != NULL) { (void)strcat(cmd, " -P"); (void)strcat(cmd, csinfo[i].ppath); } if (csinfo[i].flags != NULL) { (void)strcat(cmd, " "); (void)strcat(cmd, csinfo[i].flags); } # ifdef UNIX /* on Win32 we still need prog */ vim_free(prog); # endif vim_free(ppath); #if defined(UNIX) if (execl("/bin/sh", "sh", "-c", cmd, (char *)NULL) == -1) PERROR(_("cs_create_connection exec failed")); exit(127); /* NOTREACHED */ default: /* parent. */ /* * Save the file descriptors for later duplication, and * reopen as streams. */ if ((csinfo[i].to_fp = fdopen(to_cs[1], "w")) == NULL) PERROR(_("cs_create_connection: fdopen for to_fp failed")); if ((csinfo[i].fr_fp = fdopen(from_cs[0], "r")) == NULL) PERROR(_("cs_create_connection: fdopen for fr_fp failed")); /* close unused */ (void)close(to_cs[0]); (void)close(from_cs[1]); break; } #else /* WIN32 */ /* Create a new process to run cscope and use pipes to talk with it */ GetStartupInfo(&si); si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; /* Hide child application window */ si.hStdOutput = stdout_wr; si.hStdError = stdout_wr; si.hStdInput = stdin_rd; created = CreateProcess(NULL, cmd, NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi); vim_free(prog); vim_free(cmd); if (!created) { PERROR(_("cs_create_connection exec failed")); (void)EMSG(_("E623: Could not spawn cscope process")); goto err_closing; } /* else */ csinfo[i].pid = pi.dwProcessId; csinfo[i].hProc = pi.hProcess; CloseHandle(pi.hThread); /* TODO - tidy up after failure to create files on pipe handles. */ if (((fd = _open_osfhandle((OPEN_OH_ARGTYPE)stdin_wr, _O_TEXT|_O_APPEND)) < 0) || ((csinfo[i].to_fp = _fdopen(fd, "w")) == NULL)) PERROR(_("cs_create_connection: fdopen for to_fp failed")); if (((fd = _open_osfhandle((OPEN_OH_ARGTYPE)stdout_rd, _O_TEXT|_O_RDONLY)) < 0) || ((csinfo[i].fr_fp = _fdopen(fd, "r")) == NULL)) PERROR(_("cs_create_connection: fdopen for fr_fp failed")); /* Close handles for file descriptors inherited by the cscope process */ CloseHandle(stdin_rd); CloseHandle(stdout_wr); #endif /* !UNIX */ return CSCOPE_SUCCESS; } /* cs_create_connection */ /* * PRIVATE: cs_find * * query cscope using command line interface. parse the output and use tselect * to allow choices. like Nvi, creates a pipe to send to/from query/cscope. * * returns TRUE if we jump to a tag or abort, FALSE if not. */ static int cs_find(eap) exarg_T *eap; { char *opt, *pat; int i; if (cs_check_for_connections() == FALSE) { (void)EMSG(_("E567: no cscope connections")); return FALSE; } if ((opt = strtok((char *)NULL, (const char *)" ")) == NULL) { cs_usage_msg(Find); return FALSE; } pat = opt + strlen(opt) + 1; if (pat >= (char *)eap->arg + eap_arg_len) { cs_usage_msg(Find); return FALSE; } /* * Let's replace the NULs written by strtok() with spaces - we need the * spaces to correctly display the quickfix/location list window's title. */ for (i = 0; i < eap_arg_len; ++i) if (NUL == eap->arg[i]) eap->arg[i] = ' '; return cs_find_common(opt, pat, eap->forceit, TRUE, eap->cmdidx == CMD_lcscope, *eap->cmdlinep); } /* cs_find */ /* * PRIVATE: cs_find_common * * common code for cscope find, shared by cs_find() and do_cstag() */ static int cs_find_common(opt, pat, forceit, verbose, use_ll, cmdline) char *opt; char *pat; int forceit; int verbose; int use_ll; char_u *cmdline; { int i; char *cmd; int *nummatches; int totmatches; #ifdef FEAT_QUICKFIX char cmdletter; char *qfpos; /* get cmd letter */ switch (opt[0]) { case '0' : cmdletter = 's'; break; case '1' : cmdletter = 'g'; break; case '2' : cmdletter = 'd'; break; case '3' : cmdletter = 'c'; break; case '4' : cmdletter = 't'; break; case '6' : cmdletter = 'e'; break; case '7' : cmdletter = 'f'; break; case '8' : cmdletter = 'i'; break; default : cmdletter = opt[0]; } qfpos = (char *)vim_strchr(p_csqf, cmdletter); if (qfpos != NULL) { qfpos++; /* next symbol must be + or - */ if (strchr(CSQF_FLAGS, *qfpos) == NULL) { char *nf = _("E469: invalid cscopequickfix flag %c for %c"); char *buf = (char *)alloc((unsigned)strlen(nf)); /* strlen will be enough because we use chars */ if (buf != NULL) { sprintf(buf, nf, *qfpos, *(qfpos-1)); (void)EMSG(buf); vim_free(buf); } return FALSE; } # ifdef FEAT_AUTOCMD if (*qfpos != '0') { apply_autocmds(EVENT_QUICKFIXCMDPRE, (char_u *)"cscope", curbuf->b_fname, TRUE, curbuf); # ifdef FEAT_EVAL if (did_throw || force_abort) return FALSE; # endif } # endif } #endif /* create the actual command to send to cscope */ cmd = cs_create_cmd(opt, pat); if (cmd == NULL) return FALSE; nummatches = (int *)alloc(sizeof(int)*csinfo_size); if (nummatches == NULL) return FALSE; /* send query to all open connections, then count the total number * of matches so we can alloc matchesp all in one swell foop */ for (i = 0; i < csinfo_size; i++) nummatches[i] = 0; totmatches = 0; for (i = 0; i < csinfo_size; i++) { if (csinfo[i].fname == NULL || csinfo[i].to_fp == NULL) continue; /* send cmd to cscope */ (void)fprintf(csinfo[i].to_fp, "%s\n", cmd); (void)fflush(csinfo[i].to_fp); nummatches[i] = cs_cnt_matches(i); if (nummatches[i] > -1) totmatches += nummatches[i]; if (nummatches[i] == 0) (void)cs_read_prompt(i); } vim_free(cmd); if (totmatches == 0) { char *nf = _("E259: no matches found for cscope query %s of %s"); char *buf; if (!verbose) { vim_free(nummatches); return FALSE; } buf = (char *)alloc((unsigned)(strlen(opt) + strlen(pat) + strlen(nf))); if (buf == NULL) (void)EMSG(nf); else { sprintf(buf, nf, opt, pat); (void)EMSG(buf); vim_free(buf); } vim_free(nummatches); return FALSE; } #ifdef FEAT_QUICKFIX if (qfpos != NULL && *qfpos != '0' && totmatches > 0) { /* fill error list */ FILE *f; char_u *tmp = vim_tempname('c'); qf_info_T *qi = NULL; win_T *wp = NULL; f = mch_fopen((char *)tmp, "w"); if (f == NULL) EMSG2(_(e_notopen), tmp); else { cs_file_results(f, nummatches); fclose(f); if (use_ll) /* Use location list */ wp = curwin; /* '-' starts a new error list */ if (qf_init(wp, tmp, (char_u *)"%f%*\\t%l%*\\t%m", *qfpos == '-', cmdline) > 0) { # ifdef FEAT_WINDOWS if (postponed_split != 0) { win_split(postponed_split > 0 ? postponed_split : 0, postponed_split_flags); RESET_BINDING(curwin); postponed_split = 0; } # endif # ifdef FEAT_AUTOCMD apply_autocmds(EVENT_QUICKFIXCMDPOST, (char_u *)"cscope", curbuf->b_fname, TRUE, curbuf); # endif if (use_ll) /* * In the location list window, use the displayed location * list. Otherwise, use the location list for the window. */ qi = (bt_quickfix(wp->w_buffer) && wp->w_llist_ref != NULL) ? wp->w_llist_ref : wp->w_llist; qf_jump(qi, 0, 0, forceit); } } mch_remove(tmp); vim_free(tmp); vim_free(nummatches); return TRUE; } else #endif /* FEAT_QUICKFIX */ { char **matches = NULL, **contexts = NULL; int matched = 0; /* read output */ cs_fill_results((char *)pat, totmatches, nummatches, &matches, &contexts, &matched); vim_free(nummatches); if (matches == NULL) return FALSE; (void)cs_manage_matches(matches, contexts, matched, Store); return do_tag((char_u *)pat, DT_CSCOPE, 0, forceit, verbose); } } /* cs_find_common */ /* * PRIVATE: cs_help * * print help */ static int cs_help(eap) exarg_T *eap UNUSED; { cscmd_T *cmdp = cs_cmds; (void)MSG_PUTS(_("cscope commands:\n")); while (cmdp->name != NULL) { char *help = _(cmdp->help); int space_cnt = 30 - vim_strsize((char_u *)help); /* Use %*s rather than %30s to ensure proper alignment in utf-8 */ if (space_cnt < 0) space_cnt = 0; (void)smsg((char_u *)_("%-5s: %s%*s (Usage: %s)"), cmdp->name, help, space_cnt, " ", cmdp->usage); if (strcmp(cmdp->name, "find") == 0) MSG_PUTS(_("\n" " c: Find functions calling this function\n" " d: Find functions called by this function\n" " e: Find this egrep pattern\n" " f: Find this file\n" " g: Find this definition\n" " i: Find files #including this file\n" " s: Find this C symbol\n" " t: Find this text string\n")); cmdp++; } wait_return(TRUE); return 0; } /* cs_help */ static void clear_csinfo(i) int i; { csinfo[i].fname = NULL; csinfo[i].ppath = NULL; csinfo[i].flags = NULL; #if defined(UNIX) csinfo[i].st_dev = (dev_t)0; csinfo[i].st_ino = (ino_t)0; #else csinfo[i].nVolume = 0; csinfo[i].nIndexHigh = 0; csinfo[i].nIndexLow = 0; #endif csinfo[i].pid = 0; csinfo[i].fr_fp = NULL; csinfo[i].to_fp = NULL; #if defined(WIN32) csinfo[i].hProc = NULL; #endif } #ifndef UNIX static char *GetWin32Error __ARGS((void)); static char * GetWin32Error() { char *msg = NULL; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL); if (msg != NULL) { /* remove trailing \r\n */ char *pcrlf = strstr(msg, "\r\n"); if (pcrlf != NULL) *pcrlf = '\0'; } return msg; } #endif /* * PRIVATE: cs_insert_filelist * * insert a new cscope database filename into the filelist */ static int cs_insert_filelist(fname, ppath, flags, sb) char *fname; char *ppath; char *flags; struct stat *sb UNUSED; { short i, j; #ifndef UNIX BY_HANDLE_FILE_INFORMATION bhfi; /* On windows 9x GetFileInformationByHandle doesn't work, so skip it */ if (!mch_windows95()) { switch (win32_fileinfo(fname, &bhfi)) { case FILEINFO_ENC_FAIL: /* enc_to_utf16() failed */ case FILEINFO_READ_FAIL: /* CreateFile() failed */ if (p_csverbose) { char *cant_msg = _("E625: cannot open cscope database: %s"); char *winmsg = GetWin32Error(); if (winmsg != NULL) { (void)EMSG2(cant_msg, winmsg); LocalFree(winmsg); } else /* subst filename if can't get error text */ (void)EMSG2(cant_msg, fname); } return -1; case FILEINFO_INFO_FAIL: /* GetFileInformationByHandle() failed */ if (p_csverbose) (void)EMSG(_("E626: cannot get cscope database information")); return -1; } } #endif i = -1; /* can be set to the index of an empty item in csinfo */ for (j = 0; j < csinfo_size; j++) { if (csinfo[j].fname != NULL #if defined(UNIX) && csinfo[j].st_dev == sb->st_dev && csinfo[j].st_ino == sb->st_ino #else /* compare pathnames first */ && ((fullpathcmp(csinfo[j].fname, fname, FALSE) & FPC_SAME) /* if not Windows 9x, test index file attributes too */ || (!mch_windows95() && csinfo[j].nVolume == bhfi.dwVolumeSerialNumber && csinfo[j].nIndexHigh == bhfi.nFileIndexHigh && csinfo[j].nIndexLow == bhfi.nFileIndexLow)) #endif ) { if (p_csverbose) (void)EMSG(_("E568: duplicate cscope database not added")); return -1; } if (csinfo[j].fname == NULL && i == -1) i = j; /* remember first empty entry */ } if (i == -1) { i = csinfo_size; if (csinfo_size == 0) { /* First time allocation: allocate only 1 connection. It should * be enough for most users. If more is needed, csinfo will be * reallocated. */ csinfo_size = 1; csinfo = (csinfo_T *)alloc_clear(sizeof(csinfo_T)); } else { /* Reallocate space for more connections. */ csinfo_size *= 2; csinfo = vim_realloc(csinfo, sizeof(csinfo_T)*csinfo_size); } if (csinfo == NULL) return -1; for (j = csinfo_size/2; j < csinfo_size; j++) clear_csinfo(j); } if ((csinfo[i].fname = (char *)alloc((unsigned)strlen(fname)+1)) == NULL) return -1; (void)strcpy(csinfo[i].fname, (const char *)fname); if (ppath != NULL) { if ((csinfo[i].ppath = (char *)alloc((unsigned)strlen(ppath) + 1)) == NULL) { vim_free(csinfo[i].fname); csinfo[i].fname = NULL; return -1; } (void)strcpy(csinfo[i].ppath, (const char *)ppath); } else csinfo[i].ppath = NULL; if (flags != NULL) { if ((csinfo[i].flags = (char *)alloc((unsigned)strlen(flags) + 1)) == NULL) { vim_free(csinfo[i].fname); vim_free(csinfo[i].ppath); csinfo[i].fname = NULL; csinfo[i].ppath = NULL; return -1; } (void)strcpy(csinfo[i].flags, (const char *)flags); } else csinfo[i].flags = NULL; #if defined(UNIX) csinfo[i].st_dev = sb->st_dev; csinfo[i].st_ino = sb->st_ino; #else csinfo[i].nVolume = bhfi.dwVolumeSerialNumber; csinfo[i].nIndexLow = bhfi.nFileIndexLow; csinfo[i].nIndexHigh = bhfi.nFileIndexHigh; #endif return i; } /* cs_insert_filelist */ /* * PRIVATE: cs_lookup_cmd * * find cscope command in command table */ static cscmd_T * cs_lookup_cmd(eap) exarg_T *eap; { cscmd_T *cmdp; char *stok; size_t len; if (eap->arg == NULL) return NULL; /* Store length of eap->arg before it gets modified by strtok(). */ eap_arg_len = (int)STRLEN(eap->arg); if ((stok = strtok((char *)(eap->arg), (const char *)" ")) == NULL) return NULL; len = strlen(stok); for (cmdp = cs_cmds; cmdp->name != NULL; ++cmdp) { if (strncmp((const char *)(stok), cmdp->name, len) == 0) return (cmdp); } return NULL; } /* cs_lookup_cmd */ /* * PRIVATE: cs_kill * * nuke em */ static int cs_kill(eap) exarg_T *eap UNUSED; { char *stok; short i; if ((stok = strtok((char *)NULL, (const char *)" ")) == NULL) { cs_usage_msg(Kill); return CSCOPE_FAILURE; } /* only single digit positive and negative integers are allowed */ if ((strlen(stok) < 2 && VIM_ISDIGIT((int)(stok[0]))) || (strlen(stok) < 3 && stok[0] == '-' && VIM_ISDIGIT((int)(stok[1])))) i = atoi(stok); else { /* It must be part of a name. We will try to find a match * within all the names in the csinfo data structure */ for (i = 0; i < csinfo_size; i++) { if (csinfo[i].fname != NULL && strstr(csinfo[i].fname, stok)) break; } } if ((i != -1) && (i >= csinfo_size || i < -1 || csinfo[i].fname == NULL)) { if (p_csverbose) (void)EMSG2(_("E261: cscope connection %s not found"), stok); } else { if (i == -1) { for (i = 0; i < csinfo_size; i++) { if (csinfo[i].fname) cs_kill_execute(i, csinfo[i].fname); } } else cs_kill_execute(i, stok); } return 0; } /* cs_kill */ /* * PRIVATE: cs_kill_execute * * Actually kills a specific cscope connection. */ static void cs_kill_execute(i, cname) int i; /* cscope table index */ char *cname; /* cscope database name */ { if (p_csverbose) { msg_clr_eos(); (void)smsg_attr(hl_attr(HLF_R) | MSG_HIST, (char_u *)_("cscope connection %s closed"), cname); } cs_release_csp(i, TRUE); } /* * PRIVATE: cs_make_vim_style_matches * * convert the cscope output into a ctags style entry (as might be found * in a ctags tags file). there's one catch though: cscope doesn't tell you * the type of the tag you are looking for. for example, in Darren Hiebert's * ctags (the one that comes with vim), #define's use a line number to find the * tag in a file while function definitions use a regexp search pattern. * * i'm going to always use the line number because cscope does something * quirky (and probably other things i don't know about): * * if you have "# define" in your source file, which is * perfectly legal, cscope thinks you have "#define". this * will result in a failed regexp search. :( * * besides, even if this particular case didn't happen, the search pattern * would still have to be modified to escape all the special regular expression * characters to comply with ctags formatting. */ static char * cs_make_vim_style_matches(fname, slno, search, tagstr) char *fname; char *slno; char *search; char *tagstr; { /* vim style is ctags: * * <tagstr>\t<filename>\t<linenum_or_search>"\t<extra> * * but as mentioned above, we'll always use the line number and * put the search pattern (if one exists) as "extra" * * buf is used as part of vim's method of handling tags, and * (i think) vim frees it when you pop your tags and get replaced * by new ones on the tag stack. */ char *buf; int amt; if (search != NULL) { amt = (int)(strlen(fname) + strlen(slno) + strlen(tagstr) + strlen(search)+6); if ((buf = (char *)alloc(amt)) == NULL) return NULL; (void)sprintf(buf, "%s\t%s\t%s;\"\t%s", tagstr, fname, slno, search); } else { amt = (int)(strlen(fname) + strlen(slno) + strlen(tagstr) + 5); if ((buf = (char *)alloc(amt)) == NULL) return NULL; (void)sprintf(buf, "%s\t%s\t%s;\"", tagstr, fname, slno); } return buf; } /* cs_make_vim_style_matches */ /* * PRIVATE: cs_manage_matches * * this is kind of hokey, but i don't see an easy way round this.. * * Store: keep a ptr to the (malloc'd) memory of matches originally * generated from cs_find(). the matches are originally lines directly * from cscope output, but transformed to look like something out of a * ctags. see cs_make_vim_style_matches for more details. * * Get: used only from cs_fgets(), this simulates a vim_fgets() to return * the next line from the cscope output. it basically keeps track of which * lines have been "used" and returns the next one. * * Free: frees up everything and resets * * Print: prints the tags */ static char * cs_manage_matches(matches, contexts, totmatches, cmd) char **matches; char **contexts; int totmatches; mcmd_e cmd; { static char **mp = NULL; static char **cp = NULL; static int cnt = -1; static int next = -1; char *p = NULL; switch (cmd) { case Store: assert(matches != NULL); assert(totmatches > 0); if (mp != NULL || cp != NULL) (void)cs_manage_matches(NULL, NULL, -1, Free); mp = matches; cp = contexts; cnt = totmatches; next = 0; break; case Get: if (next >= cnt) return NULL; p = mp[next]; next++; break; case Free: if (mp != NULL) { if (cnt > 0) while (cnt--) { vim_free(mp[cnt]); if (cp != NULL) vim_free(cp[cnt]); } vim_free(mp); vim_free(cp); } mp = NULL; cp = NULL; cnt = 0; next = 0; break; case Print: cs_print_tags_priv(mp, cp, cnt); break; default: /* should not reach here */ (void)EMSG(_("E570: fatal error in cs_manage_matches")); return NULL; } return p; } /* cs_manage_matches */ /* * PRIVATE: cs_parse_results * * parse cscope output */ static char * cs_parse_results(cnumber, buf, bufsize, context, linenumber, search) int cnumber; char *buf; int bufsize; char **context; char **linenumber; char **search; { int ch; char *p; char *name; if (fgets(buf, bufsize, csinfo[cnumber].fr_fp) == NULL) { if (feof(csinfo[cnumber].fr_fp)) errno = EIO; cs_reading_emsg(cnumber); return NULL; } /* If the line's too long for the buffer, discard it. */ if ((p = strchr(buf, '\n')) == NULL) { while ((ch = getc(csinfo[cnumber].fr_fp)) != EOF && ch != '\n') ; return NULL; } *p = '\0'; /* * cscope output is in the following format: * * <filename> <context> <line number> <pattern> */ if ((name = strtok((char *)buf, (const char *)" ")) == NULL) return NULL; if ((*context = strtok(NULL, (const char *)" ")) == NULL) return NULL; if ((*linenumber = strtok(NULL, (const char *)" ")) == NULL) return NULL; *search = *linenumber + strlen(*linenumber) + 1; /* +1 to skip \0 */ /* --- nvi --- * If the file is older than the cscope database, that is, * the database was built since the file was last modified, * or there wasn't a search string, use the line number. */ if (strcmp(*search, "<unknown>") == 0) *search = NULL; name = cs_resolve_file(cnumber, name); return name; } #ifdef FEAT_QUICKFIX /* * PRIVATE: cs_file_results * * write cscope find results to file */ static void cs_file_results(f, nummatches_a) FILE *f; int *nummatches_a; { int i, j; char *buf; char *search, *slno; char *fullname; char *cntx; char *context; buf = (char *)alloc(CSREAD_BUFSIZE); if (buf == NULL) return; for (i = 0; i < csinfo_size; i++) { if (nummatches_a[i] < 1) continue; for (j = 0; j < nummatches_a[i]; j++) { if ((fullname = cs_parse_results(i, buf, CSREAD_BUFSIZE, &cntx, &slno, &search)) == NULL) continue; context = (char *)alloc((unsigned)strlen(cntx)+5); if (context == NULL) continue; if (strcmp(cntx, "<global>")==0) strcpy(context, "<<global>>"); else sprintf(context, "<<%s>>", cntx); if (search == NULL) fprintf(f, "%s\t%s\t%s\n", fullname, slno, context); else fprintf(f, "%s\t%s\t%s %s\n", fullname, slno, context, search); vim_free(context); vim_free(fullname); } /* for all matches */ (void)cs_read_prompt(i); } /* for all cscope connections */ vim_free(buf); } #endif /* * PRIVATE: cs_fill_results * * get parsed cscope output and calls cs_make_vim_style_matches to convert * into ctags format * When there are no matches sets "*matches_p" to NULL. */ static void cs_fill_results(tagstr, totmatches, nummatches_a, matches_p, cntxts_p, matched) char *tagstr; int totmatches; int *nummatches_a; char ***matches_p; char ***cntxts_p; int *matched; { int i, j; char *buf; char *search, *slno; int totsofar = 0; char **matches = NULL; char **cntxts = NULL; char *fullname; char *cntx; assert(totmatches > 0); buf = (char *)alloc(CSREAD_BUFSIZE); if (buf == NULL) return; if ((matches = (char **)alloc(sizeof(char *) * totmatches)) == NULL) goto parse_out; if ((cntxts = (char **)alloc(sizeof(char *) * totmatches)) == NULL) goto parse_out; for (i = 0; i < csinfo_size; i++) { if (nummatches_a[i] < 1) continue; for (j = 0; j < nummatches_a[i]; j++) { if ((fullname = cs_parse_results(i, buf, CSREAD_BUFSIZE, &cntx, &slno, &search)) == NULL) continue; matches[totsofar] = cs_make_vim_style_matches(fullname, slno, search, tagstr); vim_free(fullname); if (strcmp(cntx, "<global>") == 0) cntxts[totsofar] = NULL; else /* note: if vim_strsave returns NULL, then the context * will be "<global>", which is misleading. */ cntxts[totsofar] = (char *)vim_strsave((char_u *)cntx); if (matches[totsofar] != NULL) totsofar++; } /* for all matches */ (void)cs_read_prompt(i); } /* for all cscope connections */ parse_out: if (totsofar == 0) { /* No matches, free the arrays and return NULL in "*matches_p". */ vim_free(matches); matches = NULL; vim_free(cntxts); cntxts = NULL; } *matched = totsofar; *matches_p = matches; *cntxts_p = cntxts; vim_free(buf); } /* cs_fill_results */ /* get the requested path components */ static char * cs_pathcomponents(path) char *path; { int i; char *s; if (p_cspc == 0) return path; s = path + strlen(path) - 1; for (i = 0; i < p_cspc; ++i) while (s > path && *--s != '/' #ifdef WIN32 && *--s != '\\' #endif ) ; if ((s > path && *s == '/') #ifdef WIN32 || (s > path && *s == '\\') #endif ) ++s; return s; } /* * PRIVATE: cs_print_tags_priv * * called from cs_manage_matches() */ static void cs_print_tags_priv(matches, cntxts, num_matches) char **matches; char **cntxts; int num_matches; { char *buf = NULL; int bufsize = 0; /* Track available bufsize */ int newsize = 0; char *ptag; char *fname, *lno, *extra, *tbuf; int i, idx, num; char *globalcntx = "GLOBAL"; char *cntxformat = " <<%s>>"; char *context; char *cstag_msg = _("Cscope tag: %s"); char *csfmt_str = "%4d %6s "; assert (num_matches > 0); if ((tbuf = (char *)alloc((unsigned)strlen(matches[0]) + 1)) == NULL) return; strcpy(tbuf, matches[0]); ptag = strtok(tbuf, "\t"); newsize = (int)(strlen(cstag_msg) + strlen(ptag)); buf = (char *)alloc(newsize); if (buf != NULL) { bufsize = newsize; (void)sprintf(buf, cstag_msg, ptag); MSG_PUTS_ATTR(buf, hl_attr(HLF_T)); } vim_free(tbuf); MSG_PUTS_ATTR(_("\n # line"), hl_attr(HLF_T)); /* strlen is 7 */ msg_advance(msg_col + 2); MSG_PUTS_ATTR(_("filename / context / line\n"), hl_attr(HLF_T)); num = 1; for (i = 0; i < num_matches; i++) { idx = i; /* if we really wanted to, we could avoid this malloc and strcpy * by parsing matches[i] on the fly and placing stuff into buf * directly, but that's too much of a hassle */ if ((tbuf = (char *)alloc((unsigned)strlen(matches[idx]) + 1)) == NULL) continue; (void)strcpy(tbuf, matches[idx]); if (strtok(tbuf, (const char *)"\t") == NULL) continue; if ((fname = strtok(NULL, (const char *)"\t")) == NULL) continue; if ((lno = strtok(NULL, (const char *)"\t")) == NULL) continue; extra = strtok(NULL, (const char *)"\t"); lno[strlen(lno)-2] = '\0'; /* ignore ;" at the end */ /* hopefully 'num' (num of matches) will be less than 10^16 */ newsize = (int)(strlen(csfmt_str) + 16 + strlen(lno)); if (bufsize < newsize) { buf = (char *)vim_realloc(buf, newsize); if (buf == NULL) bufsize = 0; else bufsize = newsize; } if (buf != NULL) { /* csfmt_str = "%4d %6s "; */ (void)sprintf(buf, csfmt_str, num, lno); MSG_PUTS_ATTR(buf, hl_attr(HLF_CM)); } MSG_PUTS_LONG_ATTR(cs_pathcomponents(fname), hl_attr(HLF_CM)); /* compute the required space for the context */ if (cntxts[idx] != NULL) context = cntxts[idx]; else context = globalcntx; newsize = (int)(strlen(context) + strlen(cntxformat)); if (bufsize < newsize) { buf = (char *)vim_realloc(buf, newsize); if (buf == NULL) bufsize = 0; else bufsize = newsize; } if (buf != NULL) { (void)sprintf(buf, cntxformat, context); /* print the context only if it fits on the same line */ if (msg_col + (int)strlen(buf) >= (int)Columns) msg_putchar('\n'); msg_advance(12); MSG_PUTS_LONG(buf); msg_putchar('\n'); } if (extra != NULL) { msg_advance(13); MSG_PUTS_LONG(extra); } vim_free(tbuf); /* only after printing extra due to strtok use */ if (msg_col) msg_putchar('\n'); ui_breakcheck(); if (got_int) { got_int = FALSE; /* don't print any more matches */ break; } num++; } /* for all matches */ vim_free(buf); } /* cs_print_tags_priv */ /* * PRIVATE: cs_read_prompt * * read a cscope prompt (basically, skip over the ">> ") */ static int cs_read_prompt(i) int i; { int ch; char *buf = NULL; /* buffer for possible error message from cscope */ int bufpos = 0; char *cs_emsg; int maxlen; static char *eprompt = "Press the RETURN key to continue:"; int epromptlen = (int)strlen(eprompt); int n; cs_emsg = _("E609: Cscope error: %s"); /* compute maximum allowed len for Cscope error message */ maxlen = (int)(IOSIZE - strlen(cs_emsg)); for (;;) { while ((ch = getc(csinfo[i].fr_fp)) != EOF && ch != CSCOPE_PROMPT[0]) /* if there is room and char is printable */ if (bufpos < maxlen - 1 && vim_isprintc(ch)) { if (buf == NULL) /* lazy buffer allocation */ buf = (char *)alloc(maxlen); if (buf != NULL) { /* append character to the message */ buf[bufpos++] = ch; buf[bufpos] = NUL; if (bufpos >= epromptlen && strcmp(&buf[bufpos - epromptlen], eprompt) == 0) { /* remove eprompt from buf */ buf[bufpos - epromptlen] = NUL; /* print message to user */ (void)EMSG2(cs_emsg, buf); /* send RETURN to cscope */ (void)putc('\n', csinfo[i].to_fp); (void)fflush(csinfo[i].to_fp); /* clear buf */ bufpos = 0; buf[bufpos] = NUL; } } } for (n = 0; n < (int)strlen(CSCOPE_PROMPT); ++n) { if (n > 0) ch = getc(csinfo[i].fr_fp); if (ch == EOF) { PERROR("cs_read_prompt EOF"); if (buf != NULL && buf[0] != NUL) (void)EMSG2(cs_emsg, buf); else if (p_csverbose) cs_reading_emsg(i); /* don't have additional information */ cs_release_csp(i, TRUE); vim_free(buf); return CSCOPE_FAILURE; } if (ch != CSCOPE_PROMPT[n]) { ch = EOF; break; } } if (ch == EOF) continue; /* didn't find the prompt */ break; /* did find the prompt */ } vim_free(buf); return CSCOPE_SUCCESS; } #if defined(UNIX) && defined(SIGALRM) /* * Used to catch and ignore SIGALRM below. */ static RETSIGTYPE sig_handler SIGDEFARG(sigarg) { /* do nothing */ SIGRETURN; } #endif /* * PRIVATE: cs_release_csp * * Does the actual free'ing for the cs ptr with an optional flag of whether * or not to free the filename. Called by cs_kill and cs_reset. */ static void cs_release_csp(i, freefnpp) int i; int freefnpp; { /* * Trying to exit normally (not sure whether it is fit to UNIX cscope */ if (csinfo[i].to_fp != NULL) { (void)fputs("q\n", csinfo[i].to_fp); (void)fflush(csinfo[i].to_fp); } #if defined(UNIX) { int waitpid_errno; int pstat; pid_t pid; # if defined(HAVE_SIGACTION) struct sigaction sa, old; /* Use sigaction() to limit the waiting time to two seconds. */ sigemptyset(&sa.sa_mask); sa.sa_handler = sig_handler; # ifdef SA_NODEFER sa.sa_flags = SA_NODEFER; # else sa.sa_flags = 0; # endif sigaction(SIGALRM, &sa, &old); alarm(2); /* 2 sec timeout */ /* Block until cscope exits or until timer expires */ pid = waitpid(csinfo[i].pid, &pstat, 0); waitpid_errno = errno; /* cancel pending alarm if still there and restore signal */ alarm(0); sigaction(SIGALRM, &old, NULL); # else int waited; /* Can't use sigaction(), loop for two seconds. First yield the CPU * to give cscope a chance to exit quickly. */ sleep(0); for (waited = 0; waited < 40; ++waited) { pid = waitpid(csinfo[i].pid, &pstat, WNOHANG); waitpid_errno = errno; if (pid != 0) break; /* break unless the process is still running */ mch_delay(50L, FALSE); /* sleep 50 ms */ } # endif /* * If the cscope process is still running: kill it. * Safety check: If the PID would be zero here, the entire X session * would be killed. -1 and 1 are dangerous as well. */ if (pid < 0 && csinfo[i].pid > 1) { # ifdef ECHILD int alive = TRUE; if (waitpid_errno == ECHILD) { /* * When using 'vim -g', vim is forked and cscope process is * no longer a child process but a sibling. So waitpid() * fails with errno being ECHILD (No child processes). * Don't send SIGKILL to cscope immediately but wait * (polling) for it to exit normally as result of sending * the "q" command, hence giving it a chance to clean up * its temporary files. */ int waited; sleep(0); for (waited = 0; waited < 40; ++waited) { /* Check whether cscope process is still alive */ if (kill(csinfo[i].pid, 0) != 0) { alive = FALSE; /* cscope process no longer exists */ break; } mch_delay(50L, FALSE); /* sleep 50ms */ } } if (alive) # endif { kill(csinfo[i].pid, SIGKILL); (void)waitpid(csinfo[i].pid, &pstat, 0); } } } #else /* !UNIX */ if (csinfo[i].hProc != NULL) { /* Give cscope a chance to exit normally */ if (WaitForSingleObject(csinfo[i].hProc, 1000) == WAIT_TIMEOUT) TerminateProcess(csinfo[i].hProc, 0); CloseHandle(csinfo[i].hProc); } #endif if (csinfo[i].fr_fp != NULL) (void)fclose(csinfo[i].fr_fp); if (csinfo[i].to_fp != NULL) (void)fclose(csinfo[i].to_fp); if (freefnpp) { vim_free(csinfo[i].fname); vim_free(csinfo[i].ppath); vim_free(csinfo[i].flags); } clear_csinfo(i); } /* cs_release_csp */ /* * PRIVATE: cs_reset * * calls cs_kill on all cscope connections then reinits */ static int cs_reset(eap) exarg_T *eap UNUSED; { char **dblist = NULL, **pplist = NULL, **fllist = NULL; int i; char buf[20]; /* for sprintf " (#%d)" */ if (csinfo_size == 0) return CSCOPE_SUCCESS; /* malloc our db and ppath list */ dblist = (char **)alloc(csinfo_size * sizeof(char *)); pplist = (char **)alloc(csinfo_size * sizeof(char *)); fllist = (char **)alloc(csinfo_size * sizeof(char *)); if (dblist == NULL || pplist == NULL || fllist == NULL) { vim_free(dblist); vim_free(pplist); vim_free(fllist); return CSCOPE_FAILURE; } for (i = 0; i < csinfo_size; i++) { dblist[i] = csinfo[i].fname; pplist[i] = csinfo[i].ppath; fllist[i] = csinfo[i].flags; if (csinfo[i].fname != NULL) cs_release_csp(i, FALSE); } /* rebuild the cscope connection list */ for (i = 0; i < csinfo_size; i++) { if (dblist[i] != NULL) { cs_add_common(dblist[i], pplist[i], fllist[i]); if (p_csverbose) { /* don't use smsg_attr() because we want to display the * connection number in the same line as * "Added cscope database..." */ sprintf(buf, " (#%d)", i); MSG_PUTS_ATTR(buf, hl_attr(HLF_R)); } } vim_free(dblist[i]); vim_free(pplist[i]); vim_free(fllist[i]); } vim_free(dblist); vim_free(pplist); vim_free(fllist); if (p_csverbose) MSG_ATTR(_("All cscope databases reset"), hl_attr(HLF_R) | MSG_HIST); return CSCOPE_SUCCESS; } /* cs_reset */ /* * PRIVATE: cs_resolve_file * * construct the full pathname to a file found in the cscope database. * (Prepends ppath, if there is one and if it's not already prepended, * otherwise just uses the name found.) * * we need to prepend the prefix because on some cscope's (e.g., the one that * ships with Solaris 2.6), the output never has the prefix prepended. * contrast this with my development system (Digital Unix), which does. */ static char * cs_resolve_file(i, name) int i; char *name; { char *fullname; int len; char_u *csdir = NULL; /* * Ppath is freed when we destroy the cscope connection. * Fullname is freed after cs_make_vim_style_matches, after it's been * copied into the tag buffer used by Vim. */ len = (int)(strlen(name) + 2); if (csinfo[i].ppath != NULL) len += (int)strlen(csinfo[i].ppath); else if (p_csre && csinfo[i].fname != NULL) { /* If 'cscoperelative' is set and ppath is not set, use cscope.out * path in path resolution. */ csdir = alloc(MAXPATHL); if (csdir != NULL) { vim_strncpy(csdir, (char_u *)csinfo[i].fname, gettail((char_u *)csinfo[i].fname) - 1 - (char_u *)csinfo[i].fname); len += (int)STRLEN(csdir); } } if ((fullname = (char *)alloc(len)) == NULL) return NULL; /* Note/example: this won't work if the cscope output already starts * "../.." and the prefix path is also "../..". if something like this * happens, you are screwed up and need to fix how you're using cscope. */ if (csinfo[i].ppath != NULL && (strncmp(name, csinfo[i].ppath, strlen(csinfo[i].ppath)) != 0) && (name[0] != '/') #ifdef WIN32 && name[0] != '\\' && name[1] != ':' #endif ) (void)sprintf(fullname, "%s/%s", csinfo[i].ppath, name); else if (csdir != NULL && csinfo[i].fname != NULL && STRLEN(csdir) > 0) { /* Check for csdir to be non empty to avoid empty path concatenated to * cscope output. TODO: avoid the unnecessary alloc/free of fullname. */ vim_free(fullname); fullname = (char *)concat_fnames(csdir, (char_u *)name, TRUE); } else (void)sprintf(fullname, "%s", name); vim_free(csdir); return fullname; } /* * PRIVATE: cs_show * * show all cscope connections */ static int cs_show(eap) exarg_T *eap UNUSED; { short i; if (cs_cnt_connections() == 0) MSG_PUTS(_("no cscope connections\n")); else { MSG_PUTS_ATTR( _(" # pid database name prepend path\n"), hl_attr(HLF_T)); for (i = 0; i < csinfo_size; i++) { if (csinfo[i].fname == NULL) continue; if (csinfo[i].ppath != NULL) (void)smsg((char_u *)"%2d %-5ld %-34s %-32s", i, (long)csinfo[i].pid, csinfo[i].fname, csinfo[i].ppath); else (void)smsg((char_u *)"%2d %-5ld %-34s <none>", i, (long)csinfo[i].pid, csinfo[i].fname); } } wait_return(TRUE); return CSCOPE_SUCCESS; } /* cs_show */ /* * PUBLIC: cs_end * * Only called when VIM exits to quit any cscope sessions. */ void cs_end() { int i; for (i = 0; i < csinfo_size; i++) cs_release_csp(i, TRUE); vim_free(csinfo); csinfo_size = 0; } #endif /* FEAT_CSCOPE */ /* the end */
zyz2011-vim
src/if_cscope.c
C
gpl2
60,013
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. */ /* * Win16 (Windows 3.1x) machine-dependent things. */ #include "os_dos.h" /* common MS-DOS and Windows stuff */ #define BINARY_FILE_IO #define USE_EXE_NAME /* use argv[0] for $VIM */ #define SYNC_DUP_CLOSE /* sync() a file with dup() and close() */ #define USE_TERM_CONSOLE #define HAVE_STRING_H #define HAVE_STRCSPN #define HAVE_STRICMP #define HAVE_STRNICMP #define HAVE_STRFTIME /* guessed */ #define HAVE_MEMSET #define USE_TMPNAM /* use tmpnam() instead of mktemp() */ #define HAVE_LOCALE_H #define HAVE_FCNTL_H #define HAVE_QSORT #define HAVE_ST_MODE /* have stat.st_mode */ #define HAVE_MATH_H //#define USE_FNAME_CASE /* adjust case of file names */ #ifndef FEAT_CLIPBOARD # define FEAT_CLIPBOARD /* include clipboard support */ #endif #if defined(__DATE__) && defined(__TIME__) # define HAVE_DATE_TIME #endif #define HAVE_AVAIL_MEM #define SHORT_FNAME /* always 8.3 file name */ #define SMALL_MALLOC /* 16 bit storage allocation */ #ifdef __BORLANDC__ # define HAVE_PUTENV /* at least Bcc 5.2 has it */ #endif #ifdef FEAT_GUI_W16 # define NO_CONSOLE /* don't included console-only code */ #endif /* toupper() is not really broken, but it's very slow. Probably because of * using unicde characters on Windows NT */ #define BROKEN_TOUPPER #define FNAME_ILLEGAL "\"*?><|" /* illegal characters in a file name */ #ifndef SIZEOF_INT # define SIZEOF_INT 2 #endif typedef long off_t; #include <stdlib.h> #include <time.h> #include <dos.h> #include <dir.h> #ifndef STRICT # define STRICT #endif #ifndef COBJMACROS # define COBJMACROS /* For OLE: Enable "friendlier" access to objects */ #endif #include <windows.h> /* * plenty of memory, use large buffers */ #define CMDBUFFSIZE 1024 /* size of the command processing buffer */ #define BASENAMELEN (MAXPATHL-5) /* length of base of file name */ #ifndef DFLT_MAXMEM # define DFLT_MAXMEM (256) /* use up to 256K for a buffer*/ #endif #ifndef DFLT_MAXMEMTOT # define DFLT_MAXMEMTOT (5*1024) /* use up to 5 Mbyte for Vim */ #endif /* * Some simple debugging macros that look and behave a lot like their * namesakes in MFC. */ #ifdef _DEBUG # if defined(_MSC_VER) && (_MSC_VER >= 1000) /* Use the new debugging tools in Visual C++ 4.x */ # include <crtdbg.h> # define ASSERT(f) _ASSERT(f) # else # include <assert.h> # define ASSERT(f) assert(f) # endif # define TRACE Trace # define TRACE0(sz) Trace(_T("%s"), _T(sz)) # define TRACE1(sz, p1) Trace(_T(sz), p1) # define TRACE2(sz, p1, p2) Trace(_T(sz), p1, p2) # define TRACE3(sz, p1, p2, p3) Trace(_T(sz), p1, p2, p3) /* In debug version, writes trace messages to debug stream */ void __cdecl Trace(char *pszFormat, ...); #else /* !_DEBUG */ /* These macros should all compile away to nothing */ # define ASSERT(f) ((void)0) # define TRACE 1 ? (void)0 : printf # define TRACE0(sz) # define TRACE1(sz, p1) # define TRACE2(sz, p1, p2) # define TRACE3(sz, p1, p2, p3) #endif /* !_DEBUG */ #define ASSERT_POINTER(p, type) \ ASSERT(((p) != NULL) && IsValidAddress((p), sizeof(type), FALSE)) #define ASSERT_NULL_OR_POINTER(p, type) \ ASSERT(((p) == NULL) || IsValidAddress((p), sizeof(type), FALSE)) #define mch_setenv(name, val, x) setenv(name, val, x)
zyz2011-vim
src/os_win16.h
C
gpl2
3,444
# # Makefile for Vim on MiNT vim:ts=8:sw=8:tw=78 # # This is a wrapper around the Unix Makefile. It is configured to accompany # the MiNT distribution of Vim. # # See "Makefile" for instructions how to run "make". # # BUT: Always run: "make -f Make_mint.mak config", # and then: "make -f Make_mint.mak"! # Otherwise the postprocessing won't get done. # ### This Makefile has been successfully tested on these systems. ### Check the (*) column for remarks, listed below. ### Later code changes may cause small problems, otherwise Vim is supposed to ### compile and run without problems. #system: configurations: version (*) tested by: #------------- ------------------------ ------- - ---------- #MiNT 1.12.5 gcc gcc-2.6.1 3.29 Jens Felderhoff #MiNT 1.12.6 gcc gcc-2.6.1 -GUI 4.6b Jens Felderhoff #MiNT 1.12.6 gcc gcc-2.6.1 -GUI 4.6 Jens Felderhoff # set this to the pathname prefix of your symbol link editor, i.e. if it is # /usr/local/bin/sym-ld set: # SYMLDPREFIX = /usr/local/bin/sym- #SYMLDPREFIX = /gnu/bin/sym- POSTPROCESS = fixstk 20k $(VIMTARGET) DBGPOSTPROCESS = fixstk 20k $(DBGTARGET) DBGLDFLAGS = -B$(SYMLDPREFIX) DBGTARGET = $(VIMTARGET).sym # Default target is making the executable and then do the post processing all: $(VIMTARGET) $(TOOLS) $(POSTPROCESS) debug: $(DBGTARGET) $(DBGPOSTPROCESS) #################### include the Unix Makefile ############### include Makefile ### (M) MiNT with gcc 2.6.1 and gdb 3.5 CC = gcc -mint CFLAGS = -g -O -Iproto $(DBGTARGET): $(OBJ) version.c version.h $(CC) -c $(ALL_CFLAGS) version.c $(CC) $(LDFLAGS) $(DBGLDFLAGS) -o $(DBGTARGET) -g $(OBJ) \ version.o $(ALL_LIBS)
zyz2011-vim
src/Make_mint.mak
Makefile
gpl2
1,701
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * arabic.c: functions for Arabic language * * Included by main.c, when FEAT_ARABIC & FEAT_GUI is defined. * * -- * * Author: Nadim Shaikli & Isam Bayazidi * */ static int A_is_a __ARGS((int cur_c)); static int A_is_s __ARGS((int cur_c)); static int A_is_f __ARGS((int cur_c)); static int chg_c_a2s __ARGS((int cur_c)); static int chg_c_a2i __ARGS((int cur_c)); static int chg_c_a2m __ARGS((int cur_c)); static int chg_c_a2f __ARGS((int cur_c)); static int chg_c_i2m __ARGS((int cur_c)); static int chg_c_f2m __ARGS((int cur_c)); static int chg_c_laa2i __ARGS((int hid_c)); static int chg_c_laa2f __ARGS((int hid_c)); static int half_shape __ARGS((int c)); static int A_firstc_laa __ARGS((int c1, int c)); static int A_is_harakat __ARGS((int c)); static int A_is_iso __ARGS((int c)); static int A_is_formb __ARGS((int c)); static int A_is_ok __ARGS((int c)); static int A_is_valid __ARGS((int c)); static int A_is_special __ARGS((int c)); /* * Returns True if c is an ISO-8859-6 shaped ARABIC letter (user entered) */ static int A_is_a(cur_c) int cur_c; { switch (cur_c) { case a_HAMZA: case a_ALEF_MADDA: case a_ALEF_HAMZA_ABOVE: case a_WAW_HAMZA: case a_ALEF_HAMZA_BELOW: case a_YEH_HAMZA: case a_ALEF: case a_BEH: case a_TEH_MARBUTA: case a_TEH: case a_THEH: case a_JEEM: case a_HAH: case a_KHAH: case a_DAL: case a_THAL: case a_REH: case a_ZAIN: case a_SEEN: case a_SHEEN: case a_SAD: case a_DAD: case a_TAH: case a_ZAH: case a_AIN: case a_GHAIN: case a_TATWEEL: case a_FEH: case a_QAF: case a_KAF: case a_LAM: case a_MEEM: case a_NOON: case a_HEH: case a_WAW: case a_ALEF_MAKSURA: case a_YEH: return TRUE; } return FALSE; } /* * Returns True if c is an Isolated Form-B ARABIC letter */ static int A_is_s(cur_c) int cur_c; { switch (cur_c) { case a_s_HAMZA: case a_s_ALEF_MADDA: case a_s_ALEF_HAMZA_ABOVE: case a_s_WAW_HAMZA: case a_s_ALEF_HAMZA_BELOW: case a_s_YEH_HAMZA: case a_s_ALEF: case a_s_BEH: case a_s_TEH_MARBUTA: case a_s_TEH: case a_s_THEH: case a_s_JEEM: case a_s_HAH: case a_s_KHAH: case a_s_DAL: case a_s_THAL: case a_s_REH: case a_s_ZAIN: case a_s_SEEN: case a_s_SHEEN: case a_s_SAD: case a_s_DAD: case a_s_TAH: case a_s_ZAH: case a_s_AIN: case a_s_GHAIN: case a_s_FEH: case a_s_QAF: case a_s_KAF: case a_s_LAM: case a_s_MEEM: case a_s_NOON: case a_s_HEH: case a_s_WAW: case a_s_ALEF_MAKSURA: case a_s_YEH: return TRUE; } return FALSE; } /* * Returns True if c is a Final shape of an ARABIC letter */ static int A_is_f(cur_c) int cur_c; { switch (cur_c) { case a_f_ALEF_MADDA: case a_f_ALEF_HAMZA_ABOVE: case a_f_WAW_HAMZA: case a_f_ALEF_HAMZA_BELOW: case a_f_YEH_HAMZA: case a_f_ALEF: case a_f_BEH: case a_f_TEH_MARBUTA: case a_f_TEH: case a_f_THEH: case a_f_JEEM: case a_f_HAH: case a_f_KHAH: case a_f_DAL: case a_f_THAL: case a_f_REH: case a_f_ZAIN: case a_f_SEEN: case a_f_SHEEN: case a_f_SAD: case a_f_DAD: case a_f_TAH: case a_f_ZAH: case a_f_AIN: case a_f_GHAIN: case a_f_FEH: case a_f_QAF: case a_f_KAF: case a_f_LAM: case a_f_MEEM: case a_f_NOON: case a_f_HEH: case a_f_WAW: case a_f_ALEF_MAKSURA: case a_f_YEH: case a_f_LAM_ALEF_MADDA_ABOVE: case a_f_LAM_ALEF_HAMZA_ABOVE: case a_f_LAM_ALEF_HAMZA_BELOW: case a_f_LAM_ALEF: return TRUE; } return FALSE; } /* * Change shape - from ISO-8859-6/Isolated to Form-B Isolated */ static int chg_c_a2s(cur_c) int cur_c; { int tempc; switch (cur_c) { case a_HAMZA: tempc = a_s_HAMZA; break; case a_ALEF_MADDA: tempc = a_s_ALEF_MADDA; break; case a_ALEF_HAMZA_ABOVE: tempc = a_s_ALEF_HAMZA_ABOVE; break; case a_WAW_HAMZA: tempc = a_s_WAW_HAMZA; break; case a_ALEF_HAMZA_BELOW: tempc = a_s_ALEF_HAMZA_BELOW; break; case a_YEH_HAMZA: tempc = a_s_YEH_HAMZA; break; case a_ALEF: tempc = a_s_ALEF; break; case a_TEH_MARBUTA: tempc = a_s_TEH_MARBUTA; break; case a_DAL: tempc = a_s_DAL; break; case a_THAL: tempc = a_s_THAL; break; case a_REH: tempc = a_s_REH; break; case a_ZAIN: tempc = a_s_ZAIN; break; case a_TATWEEL: /* exceptions */ tempc = cur_c; break; case a_WAW: tempc = a_s_WAW; break; case a_ALEF_MAKSURA: tempc = a_s_ALEF_MAKSURA; break; case a_BEH: tempc = a_s_BEH; break; case a_TEH: tempc = a_s_TEH; break; case a_THEH: tempc = a_s_THEH; break; case a_JEEM: tempc = a_s_JEEM; break; case a_HAH: tempc = a_s_HAH; break; case a_KHAH: tempc = a_s_KHAH; break; case a_SEEN: tempc = a_s_SEEN; break; case a_SHEEN: tempc = a_s_SHEEN; break; case a_SAD: tempc = a_s_SAD; break; case a_DAD: tempc = a_s_DAD; break; case a_TAH: tempc = a_s_TAH; break; case a_ZAH: tempc = a_s_ZAH; break; case a_AIN: tempc = a_s_AIN; break; case a_GHAIN: tempc = a_s_GHAIN; break; case a_FEH: tempc = a_s_FEH; break; case a_QAF: tempc = a_s_QAF; break; case a_KAF: tempc = a_s_KAF; break; case a_LAM: tempc = a_s_LAM; break; case a_MEEM: tempc = a_s_MEEM; break; case a_NOON: tempc = a_s_NOON; break; case a_HEH: tempc = a_s_HEH; break; case a_YEH: tempc = a_s_YEH; break; default: tempc = 0; } return tempc; } /* * Change shape - from ISO-8859-6/Isolated to Initial */ static int chg_c_a2i(cur_c) int cur_c; { int tempc; switch (cur_c) { case a_YEH_HAMZA: tempc = a_i_YEH_HAMZA; break; case a_HAMZA: /* exceptions */ tempc = a_s_HAMZA; break; case a_ALEF_MADDA: /* exceptions */ tempc = a_s_ALEF_MADDA; break; case a_ALEF_HAMZA_ABOVE: /* exceptions */ tempc = a_s_ALEF_HAMZA_ABOVE; break; case a_WAW_HAMZA: /* exceptions */ tempc = a_s_WAW_HAMZA; break; case a_ALEF_HAMZA_BELOW: /* exceptions */ tempc = a_s_ALEF_HAMZA_BELOW; break; case a_ALEF: /* exceptions */ tempc = a_s_ALEF; break; case a_TEH_MARBUTA: /* exceptions */ tempc = a_s_TEH_MARBUTA; break; case a_DAL: /* exceptions */ tempc = a_s_DAL; break; case a_THAL: /* exceptions */ tempc = a_s_THAL; break; case a_REH: /* exceptions */ tempc = a_s_REH; break; case a_ZAIN: /* exceptions */ tempc = a_s_ZAIN; break; case a_TATWEEL: /* exceptions */ tempc = cur_c; break; case a_WAW: /* exceptions */ tempc = a_s_WAW; break; case a_ALEF_MAKSURA: /* exceptions */ tempc = a_s_ALEF_MAKSURA; break; case a_BEH: tempc = a_i_BEH; break; case a_TEH: tempc = a_i_TEH; break; case a_THEH: tempc = a_i_THEH; break; case a_JEEM: tempc = a_i_JEEM; break; case a_HAH: tempc = a_i_HAH; break; case a_KHAH: tempc = a_i_KHAH; break; case a_SEEN: tempc = a_i_SEEN; break; case a_SHEEN: tempc = a_i_SHEEN; break; case a_SAD: tempc = a_i_SAD; break; case a_DAD: tempc = a_i_DAD; break; case a_TAH: tempc = a_i_TAH; break; case a_ZAH: tempc = a_i_ZAH; break; case a_AIN: tempc = a_i_AIN; break; case a_GHAIN: tempc = a_i_GHAIN; break; case a_FEH: tempc = a_i_FEH; break; case a_QAF: tempc = a_i_QAF; break; case a_KAF: tempc = a_i_KAF; break; case a_LAM: tempc = a_i_LAM; break; case a_MEEM: tempc = a_i_MEEM; break; case a_NOON: tempc = a_i_NOON; break; case a_HEH: tempc = a_i_HEH; break; case a_YEH: tempc = a_i_YEH; break; default: tempc = 0; } return tempc; } /* * Change shape - from ISO-8859-6/Isolated to Medial */ static int chg_c_a2m(cur_c) int cur_c; { int tempc; switch (cur_c) { case a_HAMZA: /* exception */ tempc = a_s_HAMZA; break; case a_ALEF_MADDA: /* exception */ tempc = a_f_ALEF_MADDA; break; case a_ALEF_HAMZA_ABOVE: /* exception */ tempc = a_f_ALEF_HAMZA_ABOVE; break; case a_WAW_HAMZA: /* exception */ tempc = a_f_WAW_HAMZA; break; case a_ALEF_HAMZA_BELOW: /* exception */ tempc = a_f_ALEF_HAMZA_BELOW; break; case a_YEH_HAMZA: tempc = a_m_YEH_HAMZA; break; case a_ALEF: /* exception */ tempc = a_f_ALEF; break; case a_BEH: tempc = a_m_BEH; break; case a_TEH_MARBUTA: /* exception */ tempc = a_f_TEH_MARBUTA; break; case a_TEH: tempc = a_m_TEH; break; case a_THEH: tempc = a_m_THEH; break; case a_JEEM: tempc = a_m_JEEM; break; case a_HAH: tempc = a_m_HAH; break; case a_KHAH: tempc = a_m_KHAH; break; case a_DAL: /* exception */ tempc = a_f_DAL; break; case a_THAL: /* exception */ tempc = a_f_THAL; break; case a_REH: /* exception */ tempc = a_f_REH; break; case a_ZAIN: /* exception */ tempc = a_f_ZAIN; break; case a_SEEN: tempc = a_m_SEEN; break; case a_SHEEN: tempc = a_m_SHEEN; break; case a_SAD: tempc = a_m_SAD; break; case a_DAD: tempc = a_m_DAD; break; case a_TAH: tempc = a_m_TAH; break; case a_ZAH: tempc = a_m_ZAH; break; case a_AIN: tempc = a_m_AIN; break; case a_GHAIN: tempc = a_m_GHAIN; break; case a_TATWEEL: /* exception */ tempc = cur_c; break; case a_FEH: tempc = a_m_FEH; break; case a_QAF: tempc = a_m_QAF; break; case a_KAF: tempc = a_m_KAF; break; case a_LAM: tempc = a_m_LAM; break; case a_MEEM: tempc = a_m_MEEM; break; case a_NOON: tempc = a_m_NOON; break; case a_HEH: tempc = a_m_HEH; break; case a_WAW: /* exception */ tempc = a_f_WAW; break; case a_ALEF_MAKSURA: /* exception */ tempc = a_f_ALEF_MAKSURA; break; case a_YEH: tempc = a_m_YEH; break; default: tempc = 0; } return tempc; } /* * Change shape - from ISO-8859-6/Isolated to final */ static int chg_c_a2f(cur_c) int cur_c; { int tempc; /* NOTE: these encodings need to be accounted for a_f_ALEF_MADDA; a_f_ALEF_HAMZA_ABOVE; a_f_ALEF_HAMZA_BELOW; a_f_LAM_ALEF_MADDA_ABOVE; a_f_LAM_ALEF_HAMZA_ABOVE; a_f_LAM_ALEF_HAMZA_BELOW; */ switch (cur_c) { case a_HAMZA: /* exception */ tempc = a_s_HAMZA; break; case a_ALEF_MADDA: tempc = a_f_ALEF_MADDA; break; case a_ALEF_HAMZA_ABOVE: tempc = a_f_ALEF_HAMZA_ABOVE; break; case a_WAW_HAMZA: tempc = a_f_WAW_HAMZA; break; case a_ALEF_HAMZA_BELOW: tempc = a_f_ALEF_HAMZA_BELOW; break; case a_YEH_HAMZA: tempc = a_f_YEH_HAMZA; break; case a_ALEF: tempc = a_f_ALEF; break; case a_BEH: tempc = a_f_BEH; break; case a_TEH_MARBUTA: tempc = a_f_TEH_MARBUTA; break; case a_TEH: tempc = a_f_TEH; break; case a_THEH: tempc = a_f_THEH; break; case a_JEEM: tempc = a_f_JEEM; break; case a_HAH: tempc = a_f_HAH; break; case a_KHAH: tempc = a_f_KHAH; break; case a_DAL: tempc = a_f_DAL; break; case a_THAL: tempc = a_f_THAL; break; case a_REH: tempc = a_f_REH; break; case a_ZAIN: tempc = a_f_ZAIN; break; case a_SEEN: tempc = a_f_SEEN; break; case a_SHEEN: tempc = a_f_SHEEN; break; case a_SAD: tempc = a_f_SAD; break; case a_DAD: tempc = a_f_DAD; break; case a_TAH: tempc = a_f_TAH; break; case a_ZAH: tempc = a_f_ZAH; break; case a_AIN: tempc = a_f_AIN; break; case a_GHAIN: tempc = a_f_GHAIN; break; case a_TATWEEL: /* exception */ tempc = cur_c; break; case a_FEH: tempc = a_f_FEH; break; case a_QAF: tempc = a_f_QAF; break; case a_KAF: tempc = a_f_KAF; break; case a_LAM: tempc = a_f_LAM; break; case a_MEEM: tempc = a_f_MEEM; break; case a_NOON: tempc = a_f_NOON; break; case a_HEH: tempc = a_f_HEH; break; case a_WAW: tempc = a_f_WAW; break; case a_ALEF_MAKSURA: tempc = a_f_ALEF_MAKSURA; break; case a_YEH: tempc = a_f_YEH; break; default: tempc = 0; } return tempc; } /* * Change shape - from Initial to Medial */ static int chg_c_i2m(cur_c) int cur_c; { int tempc; switch (cur_c) { case a_i_YEH_HAMZA: tempc = a_m_YEH_HAMZA; break; case a_i_BEH: tempc = a_m_BEH; break; case a_i_TEH: tempc = a_m_TEH; break; case a_i_THEH: tempc = a_m_THEH; break; case a_i_JEEM: tempc = a_m_JEEM; break; case a_i_HAH: tempc = a_m_HAH; break; case a_i_KHAH: tempc = a_m_KHAH; break; case a_i_SEEN: tempc = a_m_SEEN; break; case a_i_SHEEN: tempc = a_m_SHEEN; break; case a_i_SAD: tempc = a_m_SAD; break; case a_i_DAD: tempc = a_m_DAD; break; case a_i_TAH: tempc = a_m_TAH; break; case a_i_ZAH: tempc = a_m_ZAH; break; case a_i_AIN: tempc = a_m_AIN; break; case a_i_GHAIN: tempc = a_m_GHAIN; break; case a_i_FEH: tempc = a_m_FEH; break; case a_i_QAF: tempc = a_m_QAF; break; case a_i_KAF: tempc = a_m_KAF; break; case a_i_LAM: tempc = a_m_LAM; break; case a_i_MEEM: tempc = a_m_MEEM; break; case a_i_NOON: tempc = a_m_NOON; break; case a_i_HEH: tempc = a_m_HEH; break; case a_i_YEH: tempc = a_m_YEH; break; default: tempc = 0; } return tempc; } /* * Change shape - from Final to Medial */ static int chg_c_f2m(cur_c) int cur_c; { int tempc; switch (cur_c) { /* NOTE: these encodings are multi-positional, no ? case a_f_ALEF_MADDA: case a_f_ALEF_HAMZA_ABOVE: case a_f_ALEF_HAMZA_BELOW: */ case a_f_YEH_HAMZA: tempc = a_m_YEH_HAMZA; break; case a_f_WAW_HAMZA: /* exceptions */ case a_f_ALEF: case a_f_TEH_MARBUTA: case a_f_DAL: case a_f_THAL: case a_f_REH: case a_f_ZAIN: case a_f_WAW: case a_f_ALEF_MAKSURA: tempc = cur_c; break; case a_f_BEH: tempc = a_m_BEH; break; case a_f_TEH: tempc = a_m_TEH; break; case a_f_THEH: tempc = a_m_THEH; break; case a_f_JEEM: tempc = a_m_JEEM; break; case a_f_HAH: tempc = a_m_HAH; break; case a_f_KHAH: tempc = a_m_KHAH; break; case a_f_SEEN: tempc = a_m_SEEN; break; case a_f_SHEEN: tempc = a_m_SHEEN; break; case a_f_SAD: tempc = a_m_SAD; break; case a_f_DAD: tempc = a_m_DAD; break; case a_f_TAH: tempc = a_m_TAH; break; case a_f_ZAH: tempc = a_m_ZAH; break; case a_f_AIN: tempc = a_m_AIN; break; case a_f_GHAIN: tempc = a_m_GHAIN; break; case a_f_FEH: tempc = a_m_FEH; break; case a_f_QAF: tempc = a_m_QAF; break; case a_f_KAF: tempc = a_m_KAF; break; case a_f_LAM: tempc = a_m_LAM; break; case a_f_MEEM: tempc = a_m_MEEM; break; case a_f_NOON: tempc = a_m_NOON; break; case a_f_HEH: tempc = a_m_HEH; break; case a_f_YEH: tempc = a_m_YEH; break; /* NOTE: these encodings are multi-positional, no ? case a_f_LAM_ALEF_MADDA_ABOVE: case a_f_LAM_ALEF_HAMZA_ABOVE: case a_f_LAM_ALEF_HAMZA_BELOW: case a_f_LAM_ALEF: */ default: tempc = 0; } return tempc; } /* * Change shape - from Combination (2 char) to an Isolated */ static int chg_c_laa2i(hid_c) int hid_c; { int tempc; switch (hid_c) { case a_ALEF_MADDA: tempc = a_s_LAM_ALEF_MADDA_ABOVE; break; case a_ALEF_HAMZA_ABOVE: tempc = a_s_LAM_ALEF_HAMZA_ABOVE; break; case a_ALEF_HAMZA_BELOW: tempc = a_s_LAM_ALEF_HAMZA_BELOW; break; case a_ALEF: tempc = a_s_LAM_ALEF; break; default: tempc = 0; } return tempc; } /* * Change shape - from Combination-Isolated to Final */ static int chg_c_laa2f(hid_c) int hid_c; { int tempc; switch (hid_c) { case a_ALEF_MADDA: tempc = a_f_LAM_ALEF_MADDA_ABOVE; break; case a_ALEF_HAMZA_ABOVE: tempc = a_f_LAM_ALEF_HAMZA_ABOVE; break; case a_ALEF_HAMZA_BELOW: tempc = a_f_LAM_ALEF_HAMZA_BELOW; break; case a_ALEF: tempc = a_f_LAM_ALEF; break; default: tempc = 0; } return tempc; } /* * Do "half-shaping" on character "c". Return zero if no shaping. */ static int half_shape(c) int c; { if (A_is_a(c)) return chg_c_a2i(c); if (A_is_valid(c) && A_is_f(c)) return chg_c_f2m(c); return 0; } /* * Do Arabic shaping on character "c". Returns the shaped character. * out: "ccp" points to the first byte of the character to be shaped. * in/out: "c1p" points to the first composing char for "c". * in: "prev_c" is the previous character (not shaped) * in: "prev_c1" is the first composing char for the previous char * (not shaped) * in: "next_c" is the next character (not shaped). */ int arabic_shape(c, ccp, c1p, prev_c, prev_c1, next_c) int c; int *ccp; int *c1p; int prev_c; int prev_c1; int next_c; { int curr_c; int shape_c; int curr_laa; int prev_laa; /* Deal only with Arabic character, pass back all others */ if (!A_is_ok(c)) return c; /* half-shape current and previous character */ shape_c = half_shape(prev_c); /* Save away current character */ curr_c = c; curr_laa = A_firstc_laa(c, *c1p); prev_laa = A_firstc_laa(prev_c, prev_c1); if (curr_laa) { if (A_is_valid(prev_c) && !A_is_f(shape_c) && !A_is_s(shape_c) && !prev_laa) curr_c = chg_c_laa2f(curr_laa); else curr_c = chg_c_laa2i(curr_laa); /* Remove the composing character */ *c1p = 0; } else if (!A_is_valid(prev_c) && A_is_valid(next_c)) curr_c = chg_c_a2i(c); else if (!shape_c || A_is_f(shape_c) || A_is_s(shape_c) || prev_laa) curr_c = A_is_valid(next_c) ? chg_c_a2i(c) : chg_c_a2s(c); else if (A_is_valid(next_c)) curr_c = A_is_iso(c) ? chg_c_a2m(c) : chg_c_i2m(c); else if (A_is_valid(prev_c)) curr_c = chg_c_a2f(c); else curr_c = chg_c_a2s(c); /* Sanity check -- curr_c should, in the future, never be 0. * We should, in the future, insert a fatal error here. */ if (curr_c == NUL) curr_c = c; if (curr_c != c && ccp != NULL) { char_u buf[MB_MAXBYTES + 1]; /* Update the first byte of the character. */ (*mb_char2bytes)(curr_c, buf); *ccp = buf[0]; } /* Return the shaped character */ return curr_c; } /* * A_firstc_laa returns first character of LAA combination if it exists */ static int A_firstc_laa(c, c1) int c; /* base character */ int c1; /* first composing character */ { if (c1 != NUL && c == a_LAM && !A_is_harakat(c1)) return c1; return 0; } /* * A_is_harakat returns TRUE if 'c' is an Arabic Harakat character * (harakat/tanween) */ static int A_is_harakat(c) int c; { return (c >= a_FATHATAN && c <= a_SUKUN); } /* * A_is_iso returns TRUE if 'c' is an Arabic ISO-8859-6 character * (alphabet/number/punctuation) */ static int A_is_iso(c) int c; { return ((c >= a_HAMZA && c <= a_GHAIN) || (c >= a_TATWEEL && c <= a_HAMZA_BELOW) || c == a_MINI_ALEF); } /* * A_is_formb returns TRUE if 'c' is an Arabic 10646-1 FormB character * (alphabet/number/punctuation) */ static int A_is_formb(c) int c; { return ((c >= a_s_FATHATAN && c <= a_s_DAMMATAN) || c == a_s_KASRATAN || (c >= a_s_FATHA && c <= a_f_LAM_ALEF) || c == a_BYTE_ORDER_MARK); } /* * A_is_ok returns TRUE if 'c' is an Arabic 10646 (8859-6 or Form-B) */ static int A_is_ok(c) int c; { return (A_is_iso(c) || A_is_formb(c)); } /* * A_is_valid returns TRUE if 'c' is an Arabic 10646 (8859-6 or Form-B) * with some exceptions/exclusions */ static int A_is_valid(c) int c; { return (A_is_ok(c) && !A_is_special(c)); } /* * A_is_special returns TRUE if 'c' is not a special Arabic character. * Specials don't adhere to most of the rules. */ static int A_is_special(c) int c; { return (c == a_HAMZA || c == a_s_HAMZA); }
zyz2011-vim
src/arabic.c
C
gpl2
20,969
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * Python extensions by Paul Moore, David Leonard, Roland Puntaier. * * Common code for if_python.c and if_python3.c. */ #ifdef FEAT_MBYTE # define ENC_OPT p_enc #else # define ENC_OPT "latin1" #endif /* * obtain a lock on the Vim data structures */ static void Python_Lock_Vim(void) { } /* * release a lock on the Vim data structures */ static void Python_Release_Vim(void) { } /* Output object definition */ static PyObject *OutputWrite(PyObject *, PyObject *); static PyObject *OutputWritelines(PyObject *, PyObject *); static PyObject *OutputFlush(PyObject *, PyObject *); /* Function to write a line, points to either msg() or emsg(). */ typedef void (*writefn)(char_u *); static void writer(writefn fn, char_u *str, PyInt n); typedef struct { PyObject_HEAD long softspace; long error; } OutputObject; static struct PyMethodDef OutputMethods[] = { /* name, function, calling, documentation */ {"write", OutputWrite, 1, ""}, {"writelines", OutputWritelines, 1, ""}, {"flush", OutputFlush, 1, ""}, { NULL, NULL, 0, NULL} }; #define PyErr_SetVim(str) PyErr_SetString(VimError, str) /*************/ /* Output buffer management */ static PyObject * OutputWrite(PyObject *self, PyObject *args) { int len; char *str = NULL; int error = ((OutputObject *)(self))->error; if (!PyArg_ParseTuple(args, "et#", ENC_OPT, &str, &len)) return NULL; /* TODO: This works around a gcc optimizer problem and avoids Vim * from crashing. Should find a real solution. */ if (str == NULL) return NULL; Py_BEGIN_ALLOW_THREADS Python_Lock_Vim(); writer((writefn)(error ? emsg : msg), (char_u *)str, len); Python_Release_Vim(); Py_END_ALLOW_THREADS PyMem_Free(str); Py_INCREF(Py_None); return Py_None; } static PyObject * OutputWritelines(PyObject *self, PyObject *args) { PyInt n; PyInt i; PyObject *list; int error = ((OutputObject *)(self))->error; if (!PyArg_ParseTuple(args, "O", &list)) return NULL; Py_INCREF(list); if (!PyList_Check(list)) { PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings")); Py_DECREF(list); return NULL; } n = PyList_Size(list); for (i = 0; i < n; ++i) { PyObject *line = PyList_GetItem(list, i); char *str = NULL; PyInt len; if (!PyArg_Parse(line, "et#", ENC_OPT, &str, &len)) { PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings")); Py_DECREF(list); return NULL; } Py_BEGIN_ALLOW_THREADS Python_Lock_Vim(); writer((writefn)(error ? emsg : msg), (char_u *)str, len); Python_Release_Vim(); Py_END_ALLOW_THREADS PyMem_Free(str); } Py_DECREF(list); Py_INCREF(Py_None); return Py_None; } static PyObject * OutputFlush(PyObject *self UNUSED, PyObject *args UNUSED) { /* do nothing */ Py_INCREF(Py_None); return Py_None; } /* Buffer IO, we write one whole line at a time. */ static garray_T io_ga = {0, 0, 1, 80, NULL}; static writefn old_fn = NULL; static void PythonIO_Flush(void) { if (old_fn != NULL && io_ga.ga_len > 0) { ((char_u *)io_ga.ga_data)[io_ga.ga_len] = NUL; old_fn((char_u *)io_ga.ga_data); } io_ga.ga_len = 0; } static void writer(writefn fn, char_u *str, PyInt n) { char_u *ptr; /* Flush when switching output function. */ if (fn != old_fn) PythonIO_Flush(); old_fn = fn; /* Write each NL separated line. Text after the last NL is kept for * writing later. */ while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL) { PyInt len = ptr - str; if (ga_grow(&io_ga, (int)(len + 1)) == FAIL) break; mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)len); ((char *)io_ga.ga_data)[io_ga.ga_len + len] = NUL; fn((char_u *)io_ga.ga_data); str = ptr + 1; n -= len + 1; io_ga.ga_len = 0; } /* Put the remaining text into io_ga for later printing. */ if (n > 0 && ga_grow(&io_ga, (int)(n + 1)) == OK) { mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)n); io_ga.ga_len += (int)n; } } /***************/ static PyTypeObject OutputType; static OutputObject Output = { PyObject_HEAD_INIT(&OutputType) 0, 0 }; static OutputObject Error = { PyObject_HEAD_INIT(&OutputType) 0, 1 }; static int PythonIO_Init_io(void) { PySys_SetObject("stdout", (PyObject *)(void *)&Output); PySys_SetObject("stderr", (PyObject *)(void *)&Error); if (PyErr_Occurred()) { EMSG(_("E264: Python: Error initialising I/O objects")); return -1; } return 0; } static PyObject *VimError; /* Check to see whether a Vim error has been reported, or a keyboard * interrupt has been detected. */ static int VimErrorCheck(void) { if (got_int) { PyErr_SetNone(PyExc_KeyboardInterrupt); return 1; } else if (did_emsg && !PyErr_Occurred()) { PyErr_SetNone(VimError); return 1; } return 0; } /* Vim module - Implementation */ static PyObject * VimCommand(PyObject *self UNUSED, PyObject *args) { char *cmd; PyObject *result; if (!PyArg_ParseTuple(args, "s", &cmd)) return NULL; PyErr_Clear(); Py_BEGIN_ALLOW_THREADS Python_Lock_Vim(); do_cmdline_cmd((char_u *)cmd); update_screen(VALID); Python_Release_Vim(); Py_END_ALLOW_THREADS if (VimErrorCheck()) result = NULL; else result = Py_None; Py_XINCREF(result); return result; } #ifdef FEAT_EVAL /* * Function to translate a typval_T into a PyObject; this will recursively * translate lists/dictionaries into their Python equivalents. * * The depth parameter is to avoid infinite recursion, set it to 1 when * you call VimToPython. */ static PyObject * VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict) { PyObject *result; PyObject *newObj; char ptrBuf[NUMBUFLEN]; /* Avoid infinite recursion */ if (depth > 100) { Py_INCREF(Py_None); result = Py_None; return result; } /* Check if we run into a recursive loop. The item must be in lookupDict * then and we can use it again. */ if ((our_tv->v_type == VAR_LIST && our_tv->vval.v_list != NULL) || (our_tv->v_type == VAR_DICT && our_tv->vval.v_dict != NULL)) { sprintf(ptrBuf, PRINTF_DECIMAL_LONG_U, our_tv->v_type == VAR_LIST ? (long_u)our_tv->vval.v_list : (long_u)our_tv->vval.v_dict); result = PyDict_GetItemString(lookupDict, ptrBuf); if (result != NULL) { Py_INCREF(result); return result; } } if (our_tv->v_type == VAR_STRING) { result = Py_BuildValue("s", our_tv->vval.v_string); } else if (our_tv->v_type == VAR_NUMBER) { char buf[NUMBUFLEN]; /* For backwards compatibility numbers are stored as strings. */ sprintf(buf, "%ld", (long)our_tv->vval.v_number); result = Py_BuildValue("s", buf); } # ifdef FEAT_FLOAT else if (our_tv->v_type == VAR_FLOAT) { char buf[NUMBUFLEN]; sprintf(buf, "%f", our_tv->vval.v_float); result = Py_BuildValue("s", buf); } # endif else if (our_tv->v_type == VAR_LIST) { list_T *list = our_tv->vval.v_list; listitem_T *curr; result = PyList_New(0); if (list != NULL) { PyDict_SetItemString(lookupDict, ptrBuf, result); for (curr = list->lv_first; curr != NULL; curr = curr->li_next) { newObj = VimToPython(&curr->li_tv, depth + 1, lookupDict); PyList_Append(result, newObj); Py_DECREF(newObj); } } } else if (our_tv->v_type == VAR_DICT) { result = PyDict_New(); if (our_tv->vval.v_dict != NULL) { hashtab_T *ht = &our_tv->vval.v_dict->dv_hashtab; long_u todo = ht->ht_used; hashitem_T *hi; dictitem_T *di; PyDict_SetItemString(lookupDict, ptrBuf, result); for (hi = ht->ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; di = dict_lookup(hi); newObj = VimToPython(&di->di_tv, depth + 1, lookupDict); PyDict_SetItemString(result, (char *)hi->hi_key, newObj); Py_DECREF(newObj); } } } } else { Py_INCREF(Py_None); result = Py_None; } return result; } #endif static PyObject * VimEval(PyObject *self UNUSED, PyObject *args UNUSED) { #ifdef FEAT_EVAL char *expr; typval_T *our_tv; PyObject *result; PyObject *lookup_dict; if (!PyArg_ParseTuple(args, "s", &expr)) return NULL; Py_BEGIN_ALLOW_THREADS Python_Lock_Vim(); our_tv = eval_expr((char_u *)expr, NULL); Python_Release_Vim(); Py_END_ALLOW_THREADS if (our_tv == NULL) { PyErr_SetVim(_("invalid expression")); return NULL; } /* Convert the Vim type into a Python type. Create a dictionary that's * used to check for recursive loops. */ lookup_dict = PyDict_New(); result = VimToPython(our_tv, 1, lookup_dict); Py_DECREF(lookup_dict); Py_BEGIN_ALLOW_THREADS Python_Lock_Vim(); free_tv(our_tv); Python_Release_Vim(); Py_END_ALLOW_THREADS return result; #else PyErr_SetVim(_("expressions disabled at compile time")); return NULL; #endif } /* * Vim module - Definitions */ static struct PyMethodDef VimMethods[] = { /* name, function, calling, documentation */ {"command", VimCommand, 1, "Execute a Vim ex-mode command" }, {"eval", VimEval, 1, "Evaluate an expression using Vim evaluator" }, { NULL, NULL, 0, NULL } }; typedef struct { PyObject_HEAD buf_T *buf; } BufferObject; #define INVALID_BUFFER_VALUE ((buf_T *)(-1)) /* * Buffer list object - Implementation */ static PyInt BufListLength(PyObject *self UNUSED) { buf_T *b = firstbuf; PyInt n = 0; while (b) { ++n; b = b->b_next; } return n; } static PyObject * BufListItem(PyObject *self UNUSED, PyInt n) { buf_T *b; for (b = firstbuf; b; b = b->b_next, --n) { if (n == 0) return BufferNew(b); } PyErr_SetString(PyExc_IndexError, _("no such buffer")); return NULL; } typedef struct { PyObject_HEAD win_T *win; } WindowObject; #define INVALID_WINDOW_VALUE ((win_T *)(-1)) static int CheckWindow(WindowObject *this) { if (this->win == INVALID_WINDOW_VALUE) { PyErr_SetVim(_("attempt to refer to deleted window")); return -1; } return 0; } static int WindowSetattr(PyObject *, char *, PyObject *); static PyObject *WindowRepr(PyObject *); static int WindowSetattr(PyObject *self, char *name, PyObject *val) { WindowObject *this = (WindowObject *)(self); if (CheckWindow(this)) return -1; if (strcmp(name, "buffer") == 0) { PyErr_SetString(PyExc_TypeError, _("readonly attribute")); return -1; } else if (strcmp(name, "cursor") == 0) { long lnum; long col; if (!PyArg_Parse(val, "(ll)", &lnum, &col)) return -1; if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count) { PyErr_SetVim(_("cursor position outside buffer")); return -1; } /* Check for keyboard interrupts */ if (VimErrorCheck()) return -1; this->win->w_cursor.lnum = lnum; this->win->w_cursor.col = col; #ifdef FEAT_VIRTUALEDIT this->win->w_cursor.coladd = 0; #endif /* When column is out of range silently correct it. */ check_cursor_col_win(this->win); update_screen(VALID); return 0; } else if (strcmp(name, "height") == 0) { int height; win_T *savewin; if (!PyArg_Parse(val, "i", &height)) return -1; #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif savewin = curwin; curwin = this->win; win_setheight(height); curwin = savewin; /* Check for keyboard interrupts */ if (VimErrorCheck()) return -1; return 0; } #ifdef FEAT_VERTSPLIT else if (strcmp(name, "width") == 0) { int width; win_T *savewin; if (!PyArg_Parse(val, "i", &width)) return -1; #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif savewin = curwin; curwin = this->win; win_setwidth(width); curwin = savewin; /* Check for keyboard interrupts */ if (VimErrorCheck()) return -1; return 0; } #endif else { PyErr_SetString(PyExc_AttributeError, name); return -1; } } static PyObject * WindowRepr(PyObject *self) { static char repr[100]; WindowObject *this = (WindowObject *)(self); if (this->win == INVALID_WINDOW_VALUE) { vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self)); return PyString_FromString(repr); } else { int i = 0; win_T *w; for (w = firstwin; w != NULL && w != this->win; w = W_NEXT(w)) ++i; if (w == NULL) vim_snprintf(repr, 100, _("<window object (unknown) at %p>"), (self)); else vim_snprintf(repr, 100, _("<window %d>"), i); return PyString_FromString(repr); } } /* * Window list object - Implementation */ static PyInt WinListLength(PyObject *self UNUSED) { win_T *w = firstwin; PyInt n = 0; while (w != NULL) { ++n; w = W_NEXT(w); } return n; } static PyObject * WinListItem(PyObject *self UNUSED, PyInt n) { win_T *w; for (w = firstwin; w != NULL; w = W_NEXT(w), --n) if (n == 0) return WindowNew(w); PyErr_SetString(PyExc_IndexError, _("no such window")); return NULL; } /* Convert a Python string into a Vim line. * * The result is in allocated memory. All internal nulls are replaced by * newline characters. It is an error for the string to contain newline * characters. * * On errors, the Python exception data is set, and NULL is returned. */ static char * StringToLine(PyObject *obj) { const char *str; char *save; PyObject *bytes; PyInt len; PyInt i; char *p; if (obj == NULL || !PyString_Check(obj)) { PyErr_BadArgument(); return NULL; } bytes = PyString_AsBytes(obj); /* for Python 2 this does nothing */ str = PyString_AsString(bytes); len = PyString_Size(bytes); /* * Error checking: String must not contain newlines, as we * are replacing a single line, and we must replace it with * a single line. * A trailing newline is removed, so that append(f.readlines()) works. */ p = memchr(str, '\n', len); if (p != NULL) { if (p == str + len - 1) --len; else { PyErr_SetVim(_("string cannot contain newlines")); return NULL; } } /* Create a copy of the string, with internal nulls replaced by * newline characters, as is the vim convention. */ save = (char *)alloc((unsigned)(len+1)); if (save == NULL) { PyErr_NoMemory(); return NULL; } for (i = 0; i < len; ++i) { if (str[i] == '\0') save[i] = '\n'; else save[i] = str[i]; } save[i] = '\0'; PyString_FreeBytes(bytes); /* Python 2 does nothing here */ return save; } /* Get a line from the specified buffer. The line number is * in Vim format (1-based). The line is returned as a Python * string object. */ static PyObject * GetBufferLine(buf_T *buf, PyInt n) { return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE)); } /* Get a list of lines from the specified buffer. The line numbers * are in Vim format (1-based). The range is from lo up to, but not * including, hi. The list is returned as a Python list of string objects. */ static PyObject * GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi) { PyInt i; PyInt n = hi - lo; PyObject *list = PyList_New(n); if (list == NULL) return NULL; for (i = 0; i < n; ++i) { PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE)); /* Error check - was the Python string creation OK? */ if (str == NULL) { Py_DECREF(list); return NULL; } /* Set the list item */ if (PyList_SetItem(list, i, str)) { Py_DECREF(str); Py_DECREF(list); return NULL; } } /* The ownership of the Python list is passed to the caller (ie, * the caller should Py_DECREF() the object when it is finished * with it). */ return list; } /* * Check if deleting lines made the cursor position invalid. * Changed the lines from "lo" to "hi" and added "extra" lines (negative if * deleted). */ static void py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra) { if (curwin->w_cursor.lnum >= lo) { /* Adjust the cursor position if it's in/after the changed * lines. */ if (curwin->w_cursor.lnum >= hi) { curwin->w_cursor.lnum += extra; check_cursor_col(); } else if (extra < 0) { curwin->w_cursor.lnum = lo; check_cursor(); } else check_cursor_col(); changed_cline_bef_curs(); } invalidate_botline(); } /* * Replace a line in the specified buffer. The line number is * in Vim format (1-based). The replacement line is given as * a Python string object. The object is checked for validity * and correct format. Errors are returned as a value of FAIL. * The return value is OK on success. * If OK is returned and len_change is not NULL, *len_change * is set to the change in the buffer length. */ static int SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change) { /* First of all, we check the thpe of the supplied Python object. * There are three cases: * 1. NULL, or None - this is a deletion. * 2. A string - this is a replacement. * 3. Anything else - this is an error. */ if (line == Py_None || line == NULL) { buf_T *savebuf = curbuf; PyErr_Clear(); curbuf = buf; if (u_savedel((linenr_T)n, 1L) == FAIL) PyErr_SetVim(_("cannot save undo information")); else if (ml_delete((linenr_T)n, FALSE) == FAIL) PyErr_SetVim(_("cannot delete line")); else { if (buf == curwin->w_buffer) py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1); deleted_lines_mark((linenr_T)n, 1L); } curbuf = savebuf; if (PyErr_Occurred() || VimErrorCheck()) return FAIL; if (len_change) *len_change = -1; return OK; } else if (PyString_Check(line)) { char *save = StringToLine(line); buf_T *savebuf = curbuf; if (save == NULL) return FAIL; /* We do not need to free "save" if ml_replace() consumes it. */ PyErr_Clear(); curbuf = buf; if (u_savesub((linenr_T)n) == FAIL) { PyErr_SetVim(_("cannot save undo information")); vim_free(save); } else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL) { PyErr_SetVim(_("cannot replace line")); vim_free(save); } else changed_bytes((linenr_T)n, 0); curbuf = savebuf; /* Check that the cursor is not beyond the end of the line now. */ if (buf == curwin->w_buffer) check_cursor_col(); if (PyErr_Occurred() || VimErrorCheck()) return FAIL; if (len_change) *len_change = 0; return OK; } else { PyErr_BadArgument(); return FAIL; } } /* Replace a range of lines in the specified buffer. The line numbers are in * Vim format (1-based). The range is from lo up to, but not including, hi. * The replacement lines are given as a Python list of string objects. The * list is checked for validity and correct format. Errors are returned as a * value of FAIL. The return value is OK on success. * If OK is returned and len_change is not NULL, *len_change * is set to the change in the buffer length. */ static int SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change) { /* First of all, we check the thpe of the supplied Python object. * There are three cases: * 1. NULL, or None - this is a deletion. * 2. A list - this is a replacement. * 3. Anything else - this is an error. */ if (list == Py_None || list == NULL) { PyInt i; PyInt n = (int)(hi - lo); buf_T *savebuf = curbuf; PyErr_Clear(); curbuf = buf; if (u_savedel((linenr_T)lo, (long)n) == FAIL) PyErr_SetVim(_("cannot save undo information")); else { for (i = 0; i < n; ++i) { if (ml_delete((linenr_T)lo, FALSE) == FAIL) { PyErr_SetVim(_("cannot delete line")); break; } } if (buf == curwin->w_buffer) py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n); deleted_lines_mark((linenr_T)lo, (long)i); } curbuf = savebuf; if (PyErr_Occurred() || VimErrorCheck()) return FAIL; if (len_change) *len_change = -n; return OK; } else if (PyList_Check(list)) { PyInt i; PyInt new_len = PyList_Size(list); PyInt old_len = hi - lo; PyInt extra = 0; /* lines added to text, can be negative */ char **array; buf_T *savebuf; if (new_len == 0) /* avoid allocating zero bytes */ array = NULL; else { array = (char **)alloc((unsigned)(new_len * sizeof(char *))); if (array == NULL) { PyErr_NoMemory(); return FAIL; } } for (i = 0; i < new_len; ++i) { PyObject *line = PyList_GetItem(list, i); array[i] = StringToLine(line); if (array[i] == NULL) { while (i) vim_free(array[--i]); vim_free(array); return FAIL; } } savebuf = curbuf; PyErr_Clear(); curbuf = buf; if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL) PyErr_SetVim(_("cannot save undo information")); /* If the size of the range is reducing (ie, new_len < old_len) we * need to delete some old_len. We do this at the start, by * repeatedly deleting line "lo". */ if (!PyErr_Occurred()) { for (i = 0; i < old_len - new_len; ++i) if (ml_delete((linenr_T)lo, FALSE) == FAIL) { PyErr_SetVim(_("cannot delete line")); break; } extra -= i; } /* For as long as possible, replace the existing old_len with the * new old_len. This is a more efficient operation, as it requires * less memory allocation and freeing. */ if (!PyErr_Occurred()) { for (i = 0; i < old_len && i < new_len; ++i) if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE) == FAIL) { PyErr_SetVim(_("cannot replace line")); break; } } else i = 0; /* Now we may need to insert the remaining new old_len. If we do, we * must free the strings as we finish with them (we can't pass the * responsibility to vim in this case). */ if (!PyErr_Occurred()) { while (i < new_len) { if (ml_append((linenr_T)(lo + i - 1), (char_u *)array[i], 0, FALSE) == FAIL) { PyErr_SetVim(_("cannot insert line")); break; } vim_free(array[i]); ++i; ++extra; } } /* Free any left-over old_len, as a result of an error */ while (i < new_len) { vim_free(array[i]); ++i; } /* Free the array of old_len. All of its contents have now * been dealt with (either freed, or the responsibility passed * to vim. */ vim_free(array); /* Adjust marks. Invalidate any which lie in the * changed range, and move any in the remainder of the buffer. */ mark_adjust((linenr_T)lo, (linenr_T)(hi - 1), (long)MAXLNUM, (long)extra); changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra); if (buf == curwin->w_buffer) py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra); curbuf = savebuf; if (PyErr_Occurred() || VimErrorCheck()) return FAIL; if (len_change) *len_change = new_len - old_len; return OK; } else { PyErr_BadArgument(); return FAIL; } } /* Insert a number of lines into the specified buffer after the specifed line. * The line number is in Vim format (1-based). The lines to be inserted are * given as a Python list of string objects or as a single string. The lines * to be added are checked for validity and correct format. Errors are * returned as a value of FAIL. The return value is OK on success. * If OK is returned and len_change is not NULL, *len_change * is set to the change in the buffer length. */ static int InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change) { /* First of all, we check the type of the supplied Python object. * It must be a string or a list, or the call is in error. */ if (PyString_Check(lines)) { char *str = StringToLine(lines); buf_T *savebuf; if (str == NULL) return FAIL; savebuf = curbuf; PyErr_Clear(); curbuf = buf; if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL) PyErr_SetVim(_("cannot save undo information")); else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL) PyErr_SetVim(_("cannot insert line")); else appended_lines_mark((linenr_T)n, 1L); vim_free(str); curbuf = savebuf; update_screen(VALID); if (PyErr_Occurred() || VimErrorCheck()) return FAIL; if (len_change) *len_change = 1; return OK; } else if (PyList_Check(lines)) { PyInt i; PyInt size = PyList_Size(lines); char **array; buf_T *savebuf; array = (char **)alloc((unsigned)(size * sizeof(char *))); if (array == NULL) { PyErr_NoMemory(); return FAIL; } for (i = 0; i < size; ++i) { PyObject *line = PyList_GetItem(lines, i); array[i] = StringToLine(line); if (array[i] == NULL) { while (i) vim_free(array[--i]); vim_free(array); return FAIL; } } savebuf = curbuf; PyErr_Clear(); curbuf = buf; if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL) PyErr_SetVim(_("cannot save undo information")); else { for (i = 0; i < size; ++i) { if (ml_append((linenr_T)(n + i), (char_u *)array[i], 0, FALSE) == FAIL) { PyErr_SetVim(_("cannot insert line")); /* Free the rest of the lines */ while (i < size) vim_free(array[i++]); break; } vim_free(array[i]); } if (i > 0) appended_lines_mark((linenr_T)n, (long)i); } /* Free the array of lines. All of its contents have now * been freed. */ vim_free(array); curbuf = savebuf; update_screen(VALID); if (PyErr_Occurred() || VimErrorCheck()) return FAIL; if (len_change) *len_change = size; return OK; } else { PyErr_BadArgument(); return FAIL; } } /* * Common routines for buffers and line ranges * ------------------------------------------- */ static int CheckBuffer(BufferObject *this) { if (this->buf == INVALID_BUFFER_VALUE) { PyErr_SetVim(_("attempt to refer to deleted buffer")); return -1; } return 0; } static PyObject * RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end) { if (CheckBuffer(self)) return NULL; if (n < 0 || n > end - start) { PyErr_SetString(PyExc_IndexError, _("line number out of range")); return NULL; } return GetBufferLine(self->buf, n+start); } static PyObject * RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end) { PyInt size; if (CheckBuffer(self)) return NULL; size = end - start + 1; if (lo < 0) lo = 0; else if (lo > size) lo = size; if (hi < 0) hi = 0; if (hi < lo) hi = lo; else if (hi > size) hi = size; return GetBufferLineList(self->buf, lo+start, hi+start); } static PyInt RBAsItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end) { PyInt len_change; if (CheckBuffer(self)) return -1; if (n < 0 || n > end - start) { PyErr_SetString(PyExc_IndexError, _("line number out of range")); return -1; } if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL) return -1; if (new_end) *new_end = end + len_change; return 0; } static PyInt RBAsSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end) { PyInt size; PyInt len_change; /* Self must be a valid buffer */ if (CheckBuffer(self)) return -1; /* Sort out the slice range */ size = end - start + 1; if (lo < 0) lo = 0; else if (lo > size) lo = size; if (hi < 0) hi = 0; if (hi < lo) hi = lo; else if (hi > size) hi = size; if (SetBufferLineList(self->buf, lo + start, hi + start, val, &len_change) == FAIL) return -1; if (new_end) *new_end = end + len_change; return 0; } static PyObject * RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end) { PyObject *lines; PyInt len_change; PyInt max; PyInt n; if (CheckBuffer(self)) return NULL; max = n = end - start + 1; if (!PyArg_ParseTuple(args, "O|n", &lines, &n)) return NULL; if (n < 0 || n > max) { PyErr_SetString(PyExc_ValueError, _("line number out of range")); return NULL; } if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL) return NULL; if (new_end) *new_end = end + len_change; Py_INCREF(Py_None); return Py_None; } /* Buffer object - Definitions */ typedef struct { PyObject_HEAD BufferObject *buf; PyInt start; PyInt end; } RangeObject; static PyObject * RangeNew(buf_T *buf, PyInt start, PyInt end) { BufferObject *bufr; RangeObject *self; self = PyObject_NEW(RangeObject, &RangeType); if (self == NULL) return NULL; bufr = (BufferObject *)BufferNew(buf); if (bufr == NULL) { Py_DECREF(self); return NULL; } Py_INCREF(bufr); self->buf = bufr; self->start = start; self->end = end; return (PyObject *)(self); } static PyObject * BufferAppend(PyObject *self, PyObject *args) { return RBAppend((BufferObject *)(self), args, 1, (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count, NULL); } static PyObject * BufferMark(PyObject *self, PyObject *args) { pos_T *posp; char *pmark; char mark; buf_T *curbuf_save; if (CheckBuffer((BufferObject *)(self))) return NULL; if (!PyArg_ParseTuple(args, "s", &pmark)) return NULL; mark = *pmark; curbuf_save = curbuf; curbuf = ((BufferObject *)(self))->buf; posp = getmark(mark, FALSE); curbuf = curbuf_save; if (posp == NULL) { PyErr_SetVim(_("invalid mark name")); return NULL; } /* Ckeck for keyboard interrupt */ if (VimErrorCheck()) return NULL; if (posp->lnum <= 0) { /* Or raise an error? */ Py_INCREF(Py_None); return Py_None; } return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col)); } static PyObject * BufferRange(PyObject *self, PyObject *args) { PyInt start; PyInt end; if (CheckBuffer((BufferObject *)(self))) return NULL; if (!PyArg_ParseTuple(args, "nn", &start, &end)) return NULL; return RangeNew(((BufferObject *)(self))->buf, start, end); } static struct PyMethodDef BufferMethods[] = { /* name, function, calling, documentation */ {"append", BufferAppend, 1, "Append data to Vim buffer" }, {"mark", BufferMark, 1, "Return (row,col) representing position of named mark" }, {"range", BufferRange, 1, "Return a range object which represents the part of the given buffer between line numbers s and e" }, #if PY_VERSION_HEX >= 0x03000000 {"__dir__", BufferDir, 4, "List its attributes" }, #endif { NULL, NULL, 0, NULL } }; static PyObject * RangeAppend(PyObject *self, PyObject *args) { return RBAppend(((RangeObject *)(self))->buf, args, ((RangeObject *)(self))->start, ((RangeObject *)(self))->end, &((RangeObject *)(self))->end); } static PyInt RangeLength(PyObject *self) { /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */ if (CheckBuffer(((RangeObject *)(self))->buf)) return -1; /* ??? */ return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1); } static PyObject * RangeItem(PyObject *self, PyInt n) { return RBItem(((RangeObject *)(self))->buf, n, ((RangeObject *)(self))->start, ((RangeObject *)(self))->end); } static PyObject * RangeRepr(PyObject *self) { static char repr[100]; RangeObject *this = (RangeObject *)(self); if (this->buf->buf == INVALID_BUFFER_VALUE) { vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>", (self)); return PyString_FromString(repr); } else { char *name = (char *)this->buf->buf->b_fname; int len; if (name == NULL) name = ""; len = (int)strlen(name); if (len > 45) name = name + (45 - len); vim_snprintf(repr, 100, "<range %s%s (%d:%d)>", len > 45 ? "..." : "", name, this->start, this->end); return PyString_FromString(repr); } } static PyObject * RangeSlice(PyObject *self, PyInt lo, PyInt hi) { return RBSlice(((RangeObject *)(self))->buf, lo, hi, ((RangeObject *)(self))->start, ((RangeObject *)(self))->end); } /* * Line range object - Definitions */ static struct PyMethodDef RangeMethods[] = { /* name, function, calling, documentation */ {"append", RangeAppend, 1, "Append data to the Vim range" }, { NULL, NULL, 0, NULL } };
zyz2011-vim
src/if_py_both.h
C
gpl2
33,219
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * X command server by Flemming Madsen * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. * * if_xcmdsrv.c: Functions for passing commands through an X11 display. * */ #include "vim.h" #include "version.h" #if defined(FEAT_CLIENTSERVER) || defined(PROTO) # ifdef FEAT_X11 # include <X11/Intrinsic.h> # include <X11/Xatom.h> # endif /* * This file provides procedures that implement the command server * functionality of Vim when in contact with an X11 server. * * Adapted from TCL/TK's send command in tkSend.c of the tk 3.6 distribution. * Adapted for use in Vim by Flemming Madsen. Protocol changed to that of tk 4 */ /* * Copyright (c) 1989-1993 The Regents of the University of California. * All rights reserved. * * Permission is hereby granted, without written agreement and without * license or royalty fees, to use, copy, modify, and distribute this * software and its documentation for any purpose, provided that the * above copyright notice and the following two paragraphs appear in * all copies of this software. * * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ /* * When a result is being awaited from a sent command, one of * the following structures is present on a list of all outstanding * sent commands. The information in the structure is used to * process the result when it arrives. You're probably wondering * how there could ever be multiple outstanding sent commands. * This could happen if Vim instances invoke each other recursively. * It's unlikely, but possible. */ typedef struct PendingCommand { int serial; /* Serial number expected in result. */ int code; /* Result Code. 0 is OK */ char_u *result; /* String result for command (malloc'ed). * NULL means command still pending. */ struct PendingCommand *nextPtr; /* Next in list of all outstanding commands. * NULL means end of list. */ } PendingCommand; static PendingCommand *pendingCommands = NULL; /* List of all commands currently * being waited for. */ /* * The information below is used for communication between processes * during "send" commands. Each process keeps a private window, never * even mapped, with one property, "Comm". When a command is sent to * an interpreter, the command is appended to the comm property of the * communication window associated with the interp's process. Similarly, * when a result is returned from a sent command, it is also appended * to the comm property. * * Each command and each result takes the form of ASCII text. For a * command, the text consists of a nul character followed by several * nul-terminated ASCII strings. The first string consists of a * single letter: * "c" for an expression * "k" for keystrokes * "r" for reply * "n" for notification. * Subsequent strings have the form "option value" where the following options * are supported: * * -r commWindow serial * * This option means that a response should be sent to the window * whose X identifier is "commWindow" (in hex), and the response should * be identified with the serial number given by "serial" (in decimal). * If this option isn't specified then the send is asynchronous and * no response is sent. * * -n name * "Name" gives the name of the application for which the command is * intended. This option must be present. * * -E encoding * Encoding name used for the text. This is the 'encoding' of the * sender. The receiver may want to do conversion to his 'encoding'. * * -s script * "Script" is the script to be executed. This option must be * present. Taken as a series of keystrokes in a "k" command where * <Key>'s are expanded * * The options may appear in any order. The -n and -s options must be * present, but -r may be omitted for asynchronous RPCs. For compatibility * with future releases that may add new features, there may be additional * options present; as long as they start with a "-" character, they will * be ignored. * * A result also consists of a zero character followed by several null- * terminated ASCII strings. The first string consists of the single * letter "r". Subsequent strings have the form "option value" where * the following options are supported: * * -s serial * Identifies the command for which this is the result. It is the * same as the "serial" field from the -s option in the command. This * option must be present. * * -r result * "Result" is the result string for the script, which may be either * a result or an error message. If this field is omitted then it * defaults to an empty string. * * -c code * 0: for OK. This is the default. * 1: for error: Result is the last error * * -i errorInfo * -e errorCode * Not applicable for Vim * * Options may appear in any order, and only the -s option must be * present. As with commands, there may be additional options besides * these; unknown options are ignored. */ /* * Maximum size property that can be read at one time by * this module: */ #define MAX_PROP_WORDS 100000 struct ServerReply { Window id; garray_T strings; }; static garray_T serverReply = { 0, 0, 0, 0, 0 }; enum ServerReplyOp { SROP_Find, SROP_Add, SROP_Delete }; typedef int (*EndCond) __ARGS((void *)); /* * Forward declarations for procedures defined later in this file: */ static Window LookupName __ARGS((Display *dpy, char_u *name, int delete, char_u **loose)); static int SendInit __ARGS((Display *dpy)); static int DoRegisterName __ARGS((Display *dpy, char_u *name)); static void DeleteAnyLingerer __ARGS((Display *dpy, Window w)); static int GetRegProp __ARGS((Display *dpy, char_u **regPropp, long_u *numItemsp, int domsg)); static int WaitForPend __ARGS((void *p)); static int WaitForReply __ARGS((void *p)); static int WindowValid __ARGS((Display *dpy, Window w)); static void ServerWait __ARGS((Display *dpy, Window w, EndCond endCond, void *endData, int localLoop, int seconds)); static struct ServerReply *ServerReplyFind __ARGS((Window w, enum ServerReplyOp op)); static int AppendPropCarefully __ARGS((Display *display, Window window, Atom property, char_u *value, int length)); static int x_error_check __ARGS((Display *dpy, XErrorEvent *error_event)); static int IsSerialName __ARGS((char_u *name)); /* Private variables for the "server" functionality */ static Atom registryProperty = None; static Atom vimProperty = None; static int got_x_error = FALSE; static char_u *empty_prop = (char_u *)""; /* empty GetRegProp() result */ /* * Associate an ASCII name with Vim. Try real hard to get a unique one. * Returns FAIL or OK. */ int serverRegisterName(dpy, name) Display *dpy; /* display to register with */ char_u *name; /* the name that will be used as a base */ { int i; int res; char_u *p = NULL; res = DoRegisterName(dpy, name); if (res < 0) { i = 1; do { if (res < -1 || i >= 1000) { MSG_ATTR(_("Unable to register a command server name"), hl_attr(HLF_W)); return FAIL; } if (p == NULL) p = alloc(STRLEN(name) + 10); if (p == NULL) { res = -10; continue; } sprintf((char *)p, "%s%d", name, i++); res = DoRegisterName(dpy, p); } while (res < 0) ; vim_free(p); } return OK; } static int DoRegisterName(dpy, name) Display *dpy; char_u *name; { Window w; XErrorHandler old_handler; #define MAX_NAME_LENGTH 100 char_u propInfo[MAX_NAME_LENGTH + 20]; if (commProperty == None) { if (SendInit(dpy) < 0) return -2; } /* * Make sure the name is unique, and append info about it to * the registry property. It's important to lock the server * here to prevent conflicting changes to the registry property. * WARNING: Do not step through this while debugging, it will hangup the X * server! */ XGrabServer(dpy); w = LookupName(dpy, name, FALSE, NULL); if (w != (Window)0) { Status status; int dummyInt; unsigned int dummyUns; Window dummyWin; /* * The name is currently registered. See if the commWindow * associated with the name exists. If not, or if the commWindow * is *our* commWindow, then just unregister the old name (this * could happen if an application dies without cleaning up the * registry). */ old_handler = XSetErrorHandler(x_error_check); status = XGetGeometry(dpy, w, &dummyWin, &dummyInt, &dummyInt, &dummyUns, &dummyUns, &dummyUns, &dummyUns); (void)XSetErrorHandler(old_handler); if (status != Success && w != commWindow) { XUngrabServer(dpy); XFlush(dpy); return -1; } (void)LookupName(dpy, name, /*delete=*/TRUE, NULL); } sprintf((char *)propInfo, "%x %.*s", (int_u)commWindow, MAX_NAME_LENGTH, name); old_handler = XSetErrorHandler(x_error_check); got_x_error = FALSE; XChangeProperty(dpy, RootWindow(dpy, 0), registryProperty, XA_STRING, 8, PropModeAppend, propInfo, STRLEN(propInfo) + 1); XUngrabServer(dpy); XSync(dpy, False); (void)XSetErrorHandler(old_handler); if (!got_x_error) { #ifdef FEAT_EVAL set_vim_var_string(VV_SEND_SERVER, name, -1); #endif serverName = vim_strsave(name); #ifdef FEAT_TITLE need_maketitle = TRUE; #endif return 0; } return -2; } #if defined(FEAT_GUI) || defined(PROTO) /* * Clean out new ID from registry and set it as comm win. * Change any registered window ID. */ void serverChangeRegisteredWindow(dpy, newwin) Display *dpy; /* Display to register with */ Window newwin; /* Re-register to this ID */ { char_u propInfo[MAX_NAME_LENGTH + 20]; commWindow = newwin; /* Always call SendInit() here, to make sure commWindow is marked as a Vim * window. */ if (SendInit(dpy) < 0) return; /* WARNING: Do not step through this while debugging, it will hangup the X * server! */ XGrabServer(dpy); DeleteAnyLingerer(dpy, newwin); if (serverName != NULL) { /* Reinsert name if we was already registered */ (void)LookupName(dpy, serverName, /*delete=*/TRUE, NULL); sprintf((char *)propInfo, "%x %.*s", (int_u)newwin, MAX_NAME_LENGTH, serverName); XChangeProperty(dpy, RootWindow(dpy, 0), registryProperty, XA_STRING, 8, PropModeAppend, (char_u *)propInfo, STRLEN(propInfo) + 1); } XUngrabServer(dpy); } #endif /* * Send to an instance of Vim via the X display. * Returns 0 for OK, negative for an error. */ int serverSendToVim(dpy, name, cmd, result, server, asExpr, localLoop, silent) Display *dpy; /* Where to send. */ char_u *name; /* Where to send. */ char_u *cmd; /* What to send. */ char_u **result; /* Result of eval'ed expression */ Window *server; /* Actual ID of receiving app */ Bool asExpr; /* Interpret as keystrokes or expr ? */ Bool localLoop; /* Throw away everything but result */ int silent; /* don't complain about no server */ { Window w; char_u *property; int length; int res; static int serial = 0; /* Running count of sent commands. * Used to give each command a * different serial number. */ PendingCommand pending; char_u *loosename = NULL; if (result != NULL) *result = NULL; if (name == NULL || *name == NUL) name = (char_u *)"GVIM"; /* use a default name */ if (commProperty == None && dpy != NULL) { if (SendInit(dpy) < 0) return -1; } /* Execute locally if no display or target is ourselves */ if (dpy == NULL || (serverName != NULL && STRICMP(name, serverName) == 0)) { if (asExpr) { char_u *ret; ret = eval_client_expr_to_string(cmd); if (result != NULL) { if (ret == NULL) *result = vim_strsave((char_u *)_(e_invexprmsg)); else *result = ret; } else vim_free(ret); return ret == NULL ? -1 : 0; } else server_to_input_buf(cmd); return 0; } /* * Bind the server name to a communication window. * * Find any survivor with a serialno attached to the name if the * original registrant of the wanted name is no longer present. * * Delete any lingering names from dead editors. */ while (TRUE) { w = LookupName(dpy, name, FALSE, &loosename); /* Check that the window is hot */ if (w != None) { if (!WindowValid(dpy, w)) { LookupName(dpy, loosename ? loosename : name, /*DELETE=*/TRUE, NULL); continue; } } break; } if (w == None) { if (!silent) EMSG2(_(e_noserver), name); return -1; } else if (loosename != NULL) name = loosename; if (server != NULL) *server = w; /* * Send the command to target interpreter by appending it to the * comm window in the communication window. * Length must be computed exactly! */ #ifdef FEAT_MBYTE length = STRLEN(name) + STRLEN(p_enc) + STRLEN(cmd) + 14; #else length = STRLEN(name) + STRLEN(cmd) + 10; #endif property = (char_u *)alloc((unsigned)length + 30); #ifdef FEAT_MBYTE sprintf((char *)property, "%c%c%c-n %s%c-E %s%c-s %s", 0, asExpr ? 'c' : 'k', 0, name, 0, p_enc, 0, cmd); #else sprintf((char *)property, "%c%c%c-n %s%c-s %s", 0, asExpr ? 'c' : 'k', 0, name, 0, cmd); #endif if (name == loosename) vim_free(loosename); /* Add a back reference to our comm window */ serial++; sprintf((char *)property + length, "%c-r %x %d", 0, (int_u)commWindow, serial); /* Add length of what "-r %x %d" resulted in, skipping the NUL. */ length += STRLEN(property + length + 1) + 1; res = AppendPropCarefully(dpy, w, commProperty, property, length + 1); vim_free(property); if (res < 0) { EMSG(_("E248: Failed to send command to the destination program")); return -1; } if (!asExpr) /* There is no answer for this - Keys are sent async */ return 0; /* * Register the fact that we're waiting for a command to * complete (this is needed by SendEventProc and by * AppendErrorProc to pass back the command's results). */ pending.serial = serial; pending.code = 0; pending.result = NULL; pending.nextPtr = pendingCommands; pendingCommands = &pending; ServerWait(dpy, w, WaitForPend, &pending, localLoop, 600); /* * Unregister the information about the pending command * and return the result. */ if (pendingCommands == &pending) pendingCommands = pending.nextPtr; else { PendingCommand *pcPtr; for (pcPtr = pendingCommands; pcPtr != NULL; pcPtr = pcPtr->nextPtr) if (pcPtr->nextPtr == &pending) { pcPtr->nextPtr = pending.nextPtr; break; } } if (result != NULL) *result = pending.result; else vim_free(pending.result); return pending.code == 0 ? 0 : -1; } static int WaitForPend(p) void *p; { PendingCommand *pending = (PendingCommand *) p; return pending->result != NULL; } /* * Return TRUE if window "w" exists and has a "Vim" property on it. */ static int WindowValid(dpy, w) Display *dpy; Window w; { XErrorHandler old_handler; Atom *plist; int numProp; int i; old_handler = XSetErrorHandler(x_error_check); got_x_error = 0; plist = XListProperties(dpy, w, &numProp); XSync(dpy, False); XSetErrorHandler(old_handler); if (plist == NULL || got_x_error) return FALSE; for (i = 0; i < numProp; i++) if (plist[i] == vimProperty) { XFree(plist); return TRUE; } XFree(plist); return FALSE; } /* * Enter a loop processing X events & polling chars until we see a result */ static void ServerWait(dpy, w, endCond, endData, localLoop, seconds) Display *dpy; Window w; EndCond endCond; void *endData; int localLoop; int seconds; { time_t start; time_t now; time_t lastChk = 0; XEvent event; XPropertyEvent *e = (XPropertyEvent *)&event; # define SEND_MSEC_POLL 50 time(&start); while (endCond(endData) == 0) { time(&now); if (seconds >= 0 && (now - start) >= seconds) break; if (now != lastChk) { lastChk = now; if (!WindowValid(dpy, w)) break; /* * Sometimes the PropertyChange event doesn't come. * This can be seen in eg: vim -c 'echo remote_expr("gvim", "3+2")' */ serverEventProc(dpy, NULL); } if (localLoop) { /* Just look out for the answer without calling back into Vim */ #ifndef HAVE_SELECT struct pollfd fds; fds.fd = ConnectionNumber(dpy); fds.events = POLLIN; if (poll(&fds, 1, SEND_MSEC_POLL) < 0) break; #else fd_set fds; struct timeval tv; tv.tv_sec = 0; tv.tv_usec = SEND_MSEC_POLL * 1000; FD_ZERO(&fds); FD_SET(ConnectionNumber(dpy), &fds); if (select(ConnectionNumber(dpy) + 1, &fds, NULL, NULL, &tv) < 0) break; #endif while (XEventsQueued(dpy, QueuedAfterReading) > 0) { XNextEvent(dpy, &event); if (event.type == PropertyNotify && e->window == commWindow) serverEventProc(dpy, &event); } } else { if (got_int) break; ui_delay((long)SEND_MSEC_POLL, TRUE); ui_breakcheck(); } } } /* * Fetch a list of all the Vim instance names currently registered for the * display. * * Returns a newline separated list in allocated memory or NULL. */ char_u * serverGetVimNames(dpy) Display *dpy; { char_u *regProp; char_u *entry; char_u *p; long_u numItems; int_u w; garray_T ga; if (registryProperty == None) { if (SendInit(dpy) < 0) return NULL; } ga_init2(&ga, 1, 100); /* * Read the registry property. */ if (GetRegProp(dpy, &regProp, &numItems, TRUE) == FAIL) return NULL; /* * Scan all of the names out of the property. */ ga_init2(&ga, 1, 100); for (p = regProp; (long_u)(p - regProp) < numItems; p++) { entry = p; while (*p != 0 && !isspace(*p)) p++; if (*p != 0) { w = None; sscanf((char *)entry, "%x", &w); if (WindowValid(dpy, (Window)w)) { ga_concat(&ga, p + 1); ga_concat(&ga, (char_u *)"\n"); } while (*p != 0) p++; } } if (regProp != empty_prop) XFree(regProp); ga_append(&ga, NUL); return ga.ga_data; } /* ---------------------------------------------------------- * Reply stuff */ static struct ServerReply * ServerReplyFind(w, op) Window w; enum ServerReplyOp op; { struct ServerReply *p; struct ServerReply e; int i; p = (struct ServerReply *) serverReply.ga_data; for (i = 0; i < serverReply.ga_len; i++, p++) if (p->id == w) break; if (i >= serverReply.ga_len) p = NULL; if (p == NULL && op == SROP_Add) { if (serverReply.ga_growsize == 0) ga_init2(&serverReply, sizeof(struct ServerReply), 1); if (ga_grow(&serverReply, 1) == OK) { p = ((struct ServerReply *) serverReply.ga_data) + serverReply.ga_len; e.id = w; ga_init2(&e.strings, 1, 100); mch_memmove(p, &e, sizeof(e)); serverReply.ga_len++; } } else if (p != NULL && op == SROP_Delete) { ga_clear(&p->strings); mch_memmove(p, p + 1, (serverReply.ga_len - i - 1) * sizeof(*p)); serverReply.ga_len--; } return p; } /* * Convert string to windowid. * Issue an error if the id is invalid. */ Window serverStrToWin(str) char_u *str; { unsigned id = None; sscanf((char *)str, "0x%x", &id); if (id == None) EMSG2(_("E573: Invalid server id used: %s"), str); return (Window)id; } /* * Send a reply string (notification) to client with id "name". * Return -1 if the window is invalid. */ int serverSendReply(name, str) char_u *name; char_u *str; { char_u *property; int length; int res; Display *dpy = X_DISPLAY; Window win = serverStrToWin(name); if (commProperty == None) { if (SendInit(dpy) < 0) return -2; } if (!WindowValid(dpy, win)) return -1; #ifdef FEAT_MBYTE length = STRLEN(p_enc) + STRLEN(str) + 14; #else length = STRLEN(str) + 10; #endif if ((property = (char_u *)alloc((unsigned)length + 30)) != NULL) { #ifdef FEAT_MBYTE sprintf((char *)property, "%cn%c-E %s%c-n %s%c-w %x", 0, 0, p_enc, 0, str, 0, (unsigned int)commWindow); #else sprintf((char *)property, "%cn%c-n %s%c-w %x", 0, 0, str, 0, (unsigned int)commWindow); #endif /* Add length of what "%x" resulted in. */ length += STRLEN(property + length); res = AppendPropCarefully(dpy, win, commProperty, property, length + 1); vim_free(property); return res; } return -1; } static int WaitForReply(p) void *p; { Window *w = (Window *) p; return ServerReplyFind(*w, SROP_Find) != NULL; } /* * Wait for replies from id (win) * Return 0 and the malloc'ed string when a reply is available. * Return -1 if the window becomes invalid while waiting. */ int serverReadReply(dpy, win, str, localLoop) Display *dpy; Window win; char_u **str; int localLoop; { int len; char_u *s; struct ServerReply *p; ServerWait(dpy, win, WaitForReply, &win, localLoop, -1); if ((p = ServerReplyFind(win, SROP_Find)) != NULL && p->strings.ga_len > 0) { *str = vim_strsave(p->strings.ga_data); len = STRLEN(*str) + 1; if (len < p->strings.ga_len) { s = (char_u *) p->strings.ga_data; mch_memmove(s, s + len, p->strings.ga_len - len); p->strings.ga_len -= len; } else { /* Last string read. Remove from list */ ga_clear(&p->strings); ServerReplyFind(win, SROP_Delete); } return 0; } return -1; } /* * Check for replies from id (win). * Return TRUE and a non-malloc'ed string if there is. Else return FALSE. */ int serverPeekReply(dpy, win, str) Display *dpy; Window win; char_u **str; { struct ServerReply *p; if ((p = ServerReplyFind(win, SROP_Find)) != NULL && p->strings.ga_len > 0) { if (str != NULL) *str = p->strings.ga_data; return 1; } if (!WindowValid(dpy, win)) return -1; return 0; } /* * Initialize the communication channels for sending commands and receiving * results. */ static int SendInit(dpy) Display *dpy; { XErrorHandler old_handler; /* * Create the window used for communication, and set up an * event handler for it. */ old_handler = XSetErrorHandler(x_error_check); got_x_error = FALSE; if (commProperty == None) commProperty = XInternAtom(dpy, "Comm", False); if (vimProperty == None) vimProperty = XInternAtom(dpy, "Vim", False); if (registryProperty == None) registryProperty = XInternAtom(dpy, "VimRegistry", False); if (commWindow == None) { commWindow = XCreateSimpleWindow(dpy, XDefaultRootWindow(dpy), getpid(), 0, 10, 10, 0, WhitePixel(dpy, DefaultScreen(dpy)), WhitePixel(dpy, DefaultScreen(dpy))); XSelectInput(dpy, commWindow, PropertyChangeMask); /* WARNING: Do not step through this while debugging, it will hangup * the X server! */ XGrabServer(dpy); DeleteAnyLingerer(dpy, commWindow); XUngrabServer(dpy); } /* Make window recognizable as a vim window */ XChangeProperty(dpy, commWindow, vimProperty, XA_STRING, 8, PropModeReplace, (char_u *)VIM_VERSION_SHORT, (int)STRLEN(VIM_VERSION_SHORT) + 1); XSync(dpy, False); (void)XSetErrorHandler(old_handler); return got_x_error ? -1 : 0; } /* * Given a server name, see if the name exists in the registry for a * particular display. * * If the given name is registered, return the ID of the window associated * with the name. If the name isn't registered, then return 0. * * Side effects: * If the registry property is improperly formed, then it is deleted. * If "delete" is non-zero, then if the named server is found it is * removed from the registry property. */ static Window LookupName(dpy, name, delete, loose) Display *dpy; /* Display whose registry to check. */ char_u *name; /* Name of a server. */ int delete; /* If non-zero, delete info about name. */ char_u **loose; /* Do another search matching -999 if not found Return result here if a match is found */ { char_u *regProp, *entry; char_u *p; long_u numItems; int_u returnValue; /* * Read the registry property. */ if (GetRegProp(dpy, &regProp, &numItems, FALSE) == FAIL) return 0; /* * Scan the property for the desired name. */ returnValue = (int_u)None; entry = NULL; /* Not needed, but eliminates compiler warning. */ for (p = regProp; (long_u)(p - regProp) < numItems; ) { entry = p; while (*p != 0 && !isspace(*p)) p++; if (*p != 0 && STRICMP(name, p + 1) == 0) { sscanf((char *)entry, "%x", &returnValue); break; } while (*p != 0) p++; p++; } if (loose != NULL && returnValue == (int_u)None && !IsSerialName(name)) { for (p = regProp; (long_u)(p - regProp) < numItems; ) { entry = p; while (*p != 0 && !isspace(*p)) p++; if (*p != 0 && IsSerialName(p + 1) && STRNICMP(name, p + 1, STRLEN(name)) == 0) { sscanf((char *)entry, "%x", &returnValue); *loose = vim_strsave(p + 1); break; } while (*p != 0) p++; p++; } } /* * Delete the property, if that is desired (copy down the * remainder of the registry property to overlay the deleted * info, then rewrite the property). */ if (delete && returnValue != (int_u)None) { int count; while (*p != 0) p++; p++; count = numItems - (p - regProp); if (count > 0) mch_memmove(entry, p, count); XChangeProperty(dpy, RootWindow(dpy, 0), registryProperty, XA_STRING, 8, PropModeReplace, regProp, (int)(numItems - (p - entry))); XSync(dpy, False); } if (regProp != empty_prop) XFree(regProp); return (Window)returnValue; } /* * Delete any lingering occurrence of window id. We promise that any * occurrence is not ours since it is not yet put into the registry (by us) * * This is necessary in the following scenario: * 1. There is an old windowid for an exit'ed vim in the registry * 2. We get that id for our commWindow but only want to send, not register. * 3. The window will mistakenly be regarded valid because of own commWindow */ static void DeleteAnyLingerer(dpy, win) Display *dpy; /* Display whose registry to check. */ Window win; /* Window to remove */ { char_u *regProp, *entry = NULL; char_u *p; long_u numItems; int_u wwin; /* * Read the registry property. */ if (GetRegProp(dpy, &regProp, &numItems, FALSE) == FAIL) return; /* Scan the property for the window id. */ for (p = regProp; (long_u)(p - regProp) < numItems; ) { if (*p != 0) { sscanf((char *)p, "%x", &wwin); if ((Window)wwin == win) { int lastHalf; /* Copy down the remainder to delete entry */ entry = p; while (*p != 0) p++; p++; lastHalf = numItems - (p - regProp); if (lastHalf > 0) mch_memmove(entry, p, lastHalf); numItems = (entry - regProp) + lastHalf; p = entry; continue; } } while (*p != 0) p++; p++; } if (entry != NULL) { XChangeProperty(dpy, RootWindow(dpy, 0), registryProperty, XA_STRING, 8, PropModeReplace, regProp, (int)(p - regProp)); XSync(dpy, False); } if (regProp != empty_prop) XFree(regProp); } /* * Read the registry property. Delete it when it's formatted wrong. * Return the property in "regPropp". "empty_prop" is used when it doesn't * exist yet. * Return OK when successful. */ static int GetRegProp(dpy, regPropp, numItemsp, domsg) Display *dpy; char_u **regPropp; long_u *numItemsp; int domsg; /* When TRUE give error message. */ { int result, actualFormat; long_u bytesAfter; Atom actualType; XErrorHandler old_handler; *regPropp = NULL; old_handler = XSetErrorHandler(x_error_check); got_x_error = FALSE; result = XGetWindowProperty(dpy, RootWindow(dpy, 0), registryProperty, 0L, (long)MAX_PROP_WORDS, False, XA_STRING, &actualType, &actualFormat, numItemsp, &bytesAfter, regPropp); XSync(dpy, FALSE); (void)XSetErrorHandler(old_handler); if (got_x_error) return FAIL; if (actualType == None) { /* No prop yet. Logically equal to the empty list */ *numItemsp = 0; *regPropp = empty_prop; return OK; } /* If the property is improperly formed, then delete it. */ if (result != Success || actualFormat != 8 || actualType != XA_STRING) { if (*regPropp != NULL) XFree(*regPropp); XDeleteProperty(dpy, RootWindow(dpy, 0), registryProperty); if (domsg) EMSG(_("E251: VIM instance registry property is badly formed. Deleted!")); return FAIL; } return OK; } /* * This procedure is invoked by the various X event loops throughout Vims when * a property changes on the communication window. This procedure reads the * property and handles command requests and responses. */ void serverEventProc(dpy, eventPtr) Display *dpy; XEvent *eventPtr; /* Information about event. */ { char_u *propInfo; char_u *p; int result, actualFormat, code; long_u numItems, bytesAfter; Atom actualType; char_u *tofree; if (eventPtr != NULL) { if (eventPtr->xproperty.atom != commProperty || eventPtr->xproperty.state != PropertyNewValue) return; } /* * Read the comm property and delete it. */ propInfo = NULL; result = XGetWindowProperty(dpy, commWindow, commProperty, 0L, (long)MAX_PROP_WORDS, True, XA_STRING, &actualType, &actualFormat, &numItems, &bytesAfter, &propInfo); /* If the property doesn't exist or is improperly formed then ignore it. */ if (result != Success || actualType != XA_STRING || actualFormat != 8) { if (propInfo != NULL) XFree(propInfo); return; } /* * Several commands and results could arrive in the property at * one time; each iteration through the outer loop handles a * single command or result. */ for (p = propInfo; (long_u)(p - propInfo) < numItems; ) { /* * Ignore leading NULs; each command or result starts with a * NUL so that no matter how badly formed a preceding command * is, we'll be able to tell that a new command/result is * starting. */ if (*p == 0) { p++; continue; } if ((*p == 'c' || *p == 'k') && (p[1] == 0)) { Window resWindow; char_u *name, *script, *serial, *end, *res; Bool asKeys = *p == 'k'; garray_T reply; char_u *enc; /* * This is an incoming command from some other application. * Iterate over all of its options. Stop when we reach * the end of the property or something that doesn't look * like an option. */ p += 2; name = NULL; resWindow = None; serial = (char_u *)""; script = NULL; enc = NULL; while ((long_u)(p - propInfo) < numItems && *p == '-') { switch (p[1]) { case 'r': end = skipwhite(p + 2); resWindow = 0; while (vim_isxdigit(*end)) { resWindow = 16 * resWindow + (long_u)hex2nr(*end); ++end; } if (end == p + 2 || *end != ' ') resWindow = None; else { p = serial = end + 1; clientWindow = resWindow; /* Remember in global */ } break; case 'n': if (p[2] == ' ') name = p + 3; break; case 's': if (p[2] == ' ') script = p + 3; break; case 'E': if (p[2] == ' ') enc = p + 3; break; } while (*p != 0) p++; p++; } if (script == NULL || name == NULL) continue; /* * Initialize the result property, so that we're ready at any * time if we need to return an error. */ if (resWindow != None) { ga_init2(&reply, 1, 100); #ifdef FEAT_MBYTE ga_grow(&reply, 50 + STRLEN(p_enc)); sprintf(reply.ga_data, "%cr%c-E %s%c-s %s%c-r ", 0, 0, p_enc, 0, serial, 0); reply.ga_len = 14 + STRLEN(p_enc) + STRLEN(serial); #else ga_grow(&reply, 50); sprintf(reply.ga_data, "%cr%c-s %s%c-r ", 0, 0, serial, 0); reply.ga_len = 10 + STRLEN(serial); #endif } res = NULL; if (serverName != NULL && STRICMP(name, serverName) == 0) { script = serverConvert(enc, script, &tofree); if (asKeys) server_to_input_buf(script); else res = eval_client_expr_to_string(script); vim_free(tofree); } if (resWindow != None) { if (res != NULL) ga_concat(&reply, res); else if (asKeys == 0) { ga_concat(&reply, (char_u *)_(e_invexprmsg)); ga_append(&reply, 0); ga_concat(&reply, (char_u *)"-c 1"); } ga_append(&reply, NUL); (void)AppendPropCarefully(dpy, resWindow, commProperty, reply.ga_data, reply.ga_len); ga_clear(&reply); } vim_free(res); } else if (*p == 'r' && p[1] == 0) { int serial, gotSerial; char_u *res; PendingCommand *pcPtr; char_u *enc; /* * This is a reply to some command that we sent out. Iterate * over all of its options. Stop when we reach the end of the * property or something that doesn't look like an option. */ p += 2; gotSerial = 0; res = (char_u *)""; code = 0; enc = NULL; while ((long_u)(p - propInfo) < numItems && *p == '-') { switch (p[1]) { case 'r': if (p[2] == ' ') res = p + 3; break; case 'E': if (p[2] == ' ') enc = p + 3; break; case 's': if (sscanf((char *)p + 2, " %d", &serial) == 1) gotSerial = 1; break; case 'c': if (sscanf((char *)p + 2, " %d", &code) != 1) code = 0; break; } while (*p != 0) p++; p++; } if (!gotSerial) continue; /* * Give the result information to anyone who's * waiting for it. */ for (pcPtr = pendingCommands; pcPtr != NULL; pcPtr = pcPtr->nextPtr) { if (serial != pcPtr->serial || pcPtr->result != NULL) continue; pcPtr->code = code; if (res != NULL) { res = serverConvert(enc, res, &tofree); if (tofree == NULL) res = vim_strsave(res); pcPtr->result = res; } else pcPtr->result = vim_strsave((char_u *)""); break; } } else if (*p == 'n' && p[1] == 0) { Window win = 0; unsigned int u; int gotWindow; char_u *str; struct ServerReply *r; char_u *enc; /* * This is a (n)otification. Sent with serverreply_send in VimL. * Execute any autocommand and save it for later retrieval */ p += 2; gotWindow = 0; str = (char_u *)""; enc = NULL; while ((long_u)(p - propInfo) < numItems && *p == '-') { switch (p[1]) { case 'n': if (p[2] == ' ') str = p + 3; break; case 'E': if (p[2] == ' ') enc = p + 3; break; case 'w': if (sscanf((char *)p + 2, " %x", &u) == 1) { win = u; gotWindow = 1; } break; } while (*p != 0) p++; p++; } if (!gotWindow) continue; str = serverConvert(enc, str, &tofree); if ((r = ServerReplyFind(win, SROP_Add)) != NULL) { ga_concat(&(r->strings), str); ga_append(&(r->strings), NUL); } #ifdef FEAT_AUTOCMD { char_u winstr[30]; sprintf((char *)winstr, "0x%x", (unsigned int)win); apply_autocmds(EVENT_REMOTEREPLY, winstr, str, TRUE, curbuf); } #endif vim_free(tofree); } else { /* * Didn't recognize this thing. Just skip through the next * null character and try again. * Even if we get an 'r'(eply) we will throw it away as we * never specify (and thus expect) one */ while (*p != 0) p++; p++; } } XFree(propInfo); } /* * Append a given property to a given window, but set up an X error handler so * that if the append fails this procedure can return an error code rather * than having Xlib panic. * Return: 0 for OK, -1 for error */ static int AppendPropCarefully(dpy, window, property, value, length) Display *dpy; /* Display on which to operate. */ Window window; /* Window whose property is to be modified. */ Atom property; /* Name of property. */ char_u *value; /* Characters to append to property. */ int length; /* How much to append */ { XErrorHandler old_handler; old_handler = XSetErrorHandler(x_error_check); got_x_error = FALSE; XChangeProperty(dpy, window, property, XA_STRING, 8, PropModeAppend, value, length); XSync(dpy, False); (void) XSetErrorHandler(old_handler); return got_x_error ? -1 : 0; } /* * Another X Error handler, just used to check for errors. */ static int x_error_check(dpy, error_event) Display *dpy UNUSED; XErrorEvent *error_event UNUSED; { got_x_error = TRUE; return 0; } /* * Check if "str" looks like it had a serial number appended. * Actually just checks if the name ends in a digit. */ static int IsSerialName(str) char_u *str; { int len = STRLEN(str); return (len > 1 && vim_isdigit(str[len - 1])); } #endif /* FEAT_CLIENTSERVER */
zyz2011-vim
src/if_xcmdsrv.c
C
gpl2
38,297
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * quickfix.c: functions for quickfix mode, using a file with error messages */ #include "vim.h" #if defined(FEAT_QUICKFIX) || defined(PROTO) struct dir_stack_T { struct dir_stack_T *next; char_u *dirname; }; static struct dir_stack_T *dir_stack = NULL; /* * For each error the next struct is allocated and linked in a list. */ typedef struct qfline_S qfline_T; struct qfline_S { qfline_T *qf_next; /* pointer to next error in the list */ qfline_T *qf_prev; /* pointer to previous error in the list */ linenr_T qf_lnum; /* line number where the error occurred */ int qf_fnum; /* file number for the line */ int qf_col; /* column where the error occurred */ int qf_nr; /* error number */ char_u *qf_pattern; /* search pattern for the error */ char_u *qf_text; /* description of the error */ char_u qf_viscol; /* set to TRUE if qf_col is screen column */ char_u qf_cleared; /* set to TRUE if line has been deleted */ char_u qf_type; /* type of the error (mostly 'E'); 1 for :helpgrep */ char_u qf_valid; /* valid error message detected */ }; /* * There is a stack of error lists. */ #define LISTCOUNT 10 typedef struct qf_list_S { qfline_T *qf_start; /* pointer to the first error */ qfline_T *qf_ptr; /* pointer to the current error */ int qf_count; /* number of errors (0 means no error list) */ int qf_index; /* current index in the error list */ int qf_nonevalid; /* TRUE if not a single valid entry found */ char_u *qf_title; /* title derived from the command that created * the error list */ } qf_list_T; struct qf_info_S { /* * Count of references to this list. Used only for location lists. * When a location list window reference this list, qf_refcount * will be 2. Otherwise, qf_refcount will be 1. When qf_refcount * reaches 0, the list is freed. */ int qf_refcount; int qf_listcount; /* current number of lists */ int qf_curlist; /* current error list */ qf_list_T qf_lists[LISTCOUNT]; }; static qf_info_T ql_info; /* global quickfix list */ #define FMT_PATTERNS 10 /* maximum number of % recognized */ /* * Structure used to hold the info of one part of 'errorformat' */ typedef struct efm_S efm_T; struct efm_S { regprog_T *prog; /* pre-formatted part of 'errorformat' */ efm_T *next; /* pointer to next (NULL if last) */ char_u addr[FMT_PATTERNS]; /* indices of used % patterns */ char_u prefix; /* prefix of this format line: */ /* 'D' enter directory */ /* 'X' leave directory */ /* 'A' start of multi-line message */ /* 'E' error message */ /* 'W' warning message */ /* 'I' informational message */ /* 'C' continuation line */ /* 'Z' end of multi-line message */ /* 'G' general, unspecific message */ /* 'P' push file (partial) message */ /* 'Q' pop/quit file (partial) message */ /* 'O' overread (partial) message */ char_u flags; /* additional flags given in prefix */ /* '-' do not include this line */ /* '+' include whole line in message */ int conthere; /* %> used */ }; static int qf_init_ext __ARGS((qf_info_T *qi, char_u *efile, buf_T *buf, typval_T *tv, char_u *errorformat, int newlist, linenr_T lnumfirst, linenr_T lnumlast, char_u *qf_title)); static void qf_new_list __ARGS((qf_info_T *qi, char_u *qf_title)); static void ll_free_all __ARGS((qf_info_T **pqi)); static int qf_add_entry __ARGS((qf_info_T *qi, qfline_T **prevp, char_u *dir, char_u *fname, int bufnum, char_u *mesg, long lnum, int col, int vis_col, char_u *pattern, int nr, int type, int valid)); static qf_info_T *ll_new_list __ARGS((void)); static void qf_msg __ARGS((qf_info_T *qi)); static void qf_free __ARGS((qf_info_T *qi, int idx)); static char_u *qf_types __ARGS((int, int)); static int qf_get_fnum __ARGS((char_u *, char_u *)); static char_u *qf_push_dir __ARGS((char_u *, struct dir_stack_T **)); static char_u *qf_pop_dir __ARGS((struct dir_stack_T **)); static char_u *qf_guess_filepath __ARGS((char_u *)); static void qf_fmt_text __ARGS((char_u *text, char_u *buf, int bufsize)); static void qf_clean_dir_stack __ARGS((struct dir_stack_T **)); #ifdef FEAT_WINDOWS static int qf_win_pos_update __ARGS((qf_info_T *qi, int old_qf_index)); static int is_qf_win __ARGS((win_T *win, qf_info_T *qi)); static win_T *qf_find_win __ARGS((qf_info_T *qi)); static buf_T *qf_find_buf __ARGS((qf_info_T *qi)); static void qf_update_buffer __ARGS((qf_info_T *qi)); static void qf_set_title __ARGS((qf_info_T *qi)); static void qf_fill_buffer __ARGS((qf_info_T *qi)); #endif static char_u *get_mef_name __ARGS((void)); static void restore_start_dir __ARGS((char_u *dirname_start)); static buf_T *load_dummy_buffer __ARGS((char_u *fname, char_u *dirname_start, char_u *resulting_dir)); static void wipe_dummy_buffer __ARGS((buf_T *buf, char_u *dirname_start)); static void unload_dummy_buffer __ARGS((buf_T *buf, char_u *dirname_start)); static qf_info_T *ll_get_or_alloc_list __ARGS((win_T *)); /* Quickfix window check helper macro */ #define IS_QF_WINDOW(wp) (bt_quickfix(wp->w_buffer) && wp->w_llist_ref == NULL) /* Location list window check helper macro */ #define IS_LL_WINDOW(wp) (bt_quickfix(wp->w_buffer) && wp->w_llist_ref != NULL) /* * Return location list for window 'wp' * For location list window, return the referenced location list */ #define GET_LOC_LIST(wp) (IS_LL_WINDOW(wp) ? wp->w_llist_ref : wp->w_llist) /* * Read the errorfile "efile" into memory, line by line, building the error * list. Set the error list's title to qf_title. * Return -1 for error, number of errors for success. */ int qf_init(wp, efile, errorformat, newlist, qf_title) win_T *wp; char_u *efile; char_u *errorformat; int newlist; /* TRUE: start a new error list */ char_u *qf_title; { qf_info_T *qi = &ql_info; if (efile == NULL) return FAIL; if (wp != NULL) { qi = ll_get_or_alloc_list(wp); if (qi == NULL) return FAIL; } return qf_init_ext(qi, efile, curbuf, NULL, errorformat, newlist, (linenr_T)0, (linenr_T)0, qf_title); } /* * Read the errorfile "efile" into memory, line by line, building the error * list. * Alternative: when "efile" is null read errors from buffer "buf". * Always use 'errorformat' from "buf" if there is a local value. * Then "lnumfirst" and "lnumlast" specify the range of lines to use. * Set the title of the list to "qf_title". * Return -1 for error, number of errors for success. */ static int qf_init_ext(qi, efile, buf, tv, errorformat, newlist, lnumfirst, lnumlast, qf_title) qf_info_T *qi; char_u *efile; buf_T *buf; typval_T *tv; char_u *errorformat; int newlist; /* TRUE: start a new error list */ linenr_T lnumfirst; /* first line number to use */ linenr_T lnumlast; /* last line number to use */ char_u *qf_title; { char_u *namebuf; char_u *errmsg; char_u *pattern; char_u *fmtstr = NULL; int col = 0; char_u use_viscol = FALSE; int type = 0; int valid; linenr_T buflnum = lnumfirst; long lnum = 0L; int enr = 0; FILE *fd = NULL; qfline_T *qfprev = NULL; /* init to make SASC shut up */ char_u *efmp; efm_T *fmt_first = NULL; efm_T *fmt_last = NULL; efm_T *fmt_ptr; efm_T *fmt_start = NULL; char_u *efm; char_u *ptr; char_u *srcptr; int len; int i; int round; int idx = 0; int multiline = FALSE; int multiignore = FALSE; int multiscan = FALSE; int retval = -1; /* default: return error flag */ char_u *directory = NULL; char_u *currfile = NULL; char_u *tail = NULL; char_u *p_str = NULL; listitem_T *p_li = NULL; struct dir_stack_T *file_stack = NULL; regmatch_T regmatch; static struct fmtpattern { char_u convchar; char *pattern; } fmt_pat[FMT_PATTERNS] = { {'f', ".\\+"}, /* only used when at end */ {'n', "\\d\\+"}, {'l', "\\d\\+"}, {'c', "\\d\\+"}, {'t', "."}, {'m', ".\\+"}, {'r', ".*"}, {'p', "[- .]*"}, {'v', "\\d\\+"}, {'s', ".\\+"} }; namebuf = alloc(CMDBUFFSIZE + 1); errmsg = alloc(CMDBUFFSIZE + 1); pattern = alloc(CMDBUFFSIZE + 1); if (namebuf == NULL || errmsg == NULL || pattern == NULL) goto qf_init_end; if (efile != NULL && (fd = mch_fopen((char *)efile, "r")) == NULL) { EMSG2(_(e_openerrf), efile); goto qf_init_end; } if (newlist || qi->qf_curlist == qi->qf_listcount) /* make place for a new list */ qf_new_list(qi, qf_title); else if (qi->qf_lists[qi->qf_curlist].qf_count > 0) /* Adding to existing list, find last entry. */ for (qfprev = qi->qf_lists[qi->qf_curlist].qf_start; qfprev->qf_next != qfprev; qfprev = qfprev->qf_next) ; /* * Each part of the format string is copied and modified from errorformat to * regex prog. Only a few % characters are allowed. */ /* Use the local value of 'errorformat' if it's set. */ if (errorformat == p_efm && tv == NULL && *buf->b_p_efm != NUL) efm = buf->b_p_efm; else efm = errorformat; /* * Get some space to modify the format string into. */ i = (FMT_PATTERNS * 3) + ((int)STRLEN(efm) << 2); for (round = FMT_PATTERNS; round > 0; ) i += (int)STRLEN(fmt_pat[--round].pattern); #ifdef COLON_IN_FILENAME i += 12; /* "%f" can become twelve chars longer */ #else i += 2; /* "%f" can become two chars longer */ #endif if ((fmtstr = alloc(i)) == NULL) goto error2; while (efm[0] != NUL) { /* * Allocate a new eformat structure and put it at the end of the list */ fmt_ptr = (efm_T *)alloc_clear((unsigned)sizeof(efm_T)); if (fmt_ptr == NULL) goto error2; if (fmt_first == NULL) /* first one */ fmt_first = fmt_ptr; else fmt_last->next = fmt_ptr; fmt_last = fmt_ptr; /* * Isolate one part in the 'errorformat' option */ for (len = 0; efm[len] != NUL && efm[len] != ','; ++len) if (efm[len] == '\\' && efm[len + 1] != NUL) ++len; /* * Build regexp pattern from current 'errorformat' option */ ptr = fmtstr; *ptr++ = '^'; round = 0; for (efmp = efm; efmp < efm + len; ++efmp) { if (*efmp == '%') { ++efmp; for (idx = 0; idx < FMT_PATTERNS; ++idx) if (fmt_pat[idx].convchar == *efmp) break; if (idx < FMT_PATTERNS) { if (fmt_ptr->addr[idx]) { sprintf((char *)errmsg, _("E372: Too many %%%c in format string"), *efmp); EMSG(errmsg); goto error2; } if ((idx && idx < 6 && vim_strchr((char_u *)"DXOPQ", fmt_ptr->prefix) != NULL) || (idx == 6 && vim_strchr((char_u *)"OPQ", fmt_ptr->prefix) == NULL)) { sprintf((char *)errmsg, _("E373: Unexpected %%%c in format string"), *efmp); EMSG(errmsg); goto error2; } fmt_ptr->addr[idx] = (char_u)++round; *ptr++ = '\\'; *ptr++ = '('; #ifdef BACKSLASH_IN_FILENAME if (*efmp == 'f') { /* Also match "c:" in the file name, even when * checking for a colon next: "%f:". * "\%(\a:\)\=" */ STRCPY(ptr, "\\%(\\a:\\)\\="); ptr += 10; } #endif if (*efmp == 'f' && efmp[1] != NUL) { if (efmp[1] != '\\' && efmp[1] != '%') { /* A file name may contain spaces, but this isn't * in "\f". For "%f:%l:%m" there may be a ":" in * the file name. Use ".\{-1,}x" instead (x is * the next character), the requirement that :999: * follows should work. */ STRCPY(ptr, ".\\{-1,}"); ptr += 7; } else { /* File name followed by '\\' or '%': include as * many file name chars as possible. */ STRCPY(ptr, "\\f\\+"); ptr += 4; } } else { srcptr = (char_u *)fmt_pat[idx].pattern; while ((*ptr = *srcptr++) != NUL) ++ptr; } *ptr++ = '\\'; *ptr++ = ')'; } else if (*efmp == '*') { if (*++efmp == '[' || *efmp == '\\') { if ((*ptr++ = *efmp) == '[') /* %*[^a-z0-9] etc. */ { if (efmp[1] == '^') *ptr++ = *++efmp; if (efmp < efm + len) { *ptr++ = *++efmp; /* could be ']' */ while (efmp < efm + len && (*ptr++ = *++efmp) != ']') /* skip */; if (efmp == efm + len) { EMSG(_("E374: Missing ] in format string")); goto error2; } } } else if (efmp < efm + len) /* %*\D, %*\s etc. */ *ptr++ = *++efmp; *ptr++ = '\\'; *ptr++ = '+'; } else { /* TODO: scanf()-like: %*ud, %*3c, %*f, ... ? */ sprintf((char *)errmsg, _("E375: Unsupported %%%c in format string"), *efmp); EMSG(errmsg); goto error2; } } else if (vim_strchr((char_u *)"%\\.^$~[", *efmp) != NULL) *ptr++ = *efmp; /* regexp magic characters */ else if (*efmp == '#') *ptr++ = '*'; else if (*efmp == '>') fmt_ptr->conthere = TRUE; else if (efmp == efm + 1) /* analyse prefix */ { if (vim_strchr((char_u *)"+-", *efmp) != NULL) fmt_ptr->flags = *efmp++; if (vim_strchr((char_u *)"DXAEWICZGOPQ", *efmp) != NULL) fmt_ptr->prefix = *efmp; else { sprintf((char *)errmsg, _("E376: Invalid %%%c in format string prefix"), *efmp); EMSG(errmsg); goto error2; } } else { sprintf((char *)errmsg, _("E377: Invalid %%%c in format string"), *efmp); EMSG(errmsg); goto error2; } } else /* copy normal character */ { if (*efmp == '\\' && efmp + 1 < efm + len) ++efmp; else if (vim_strchr((char_u *)".*^$~[", *efmp) != NULL) *ptr++ = '\\'; /* escape regexp atoms */ if (*efmp) *ptr++ = *efmp; } } *ptr++ = '$'; *ptr = NUL; if ((fmt_ptr->prog = vim_regcomp(fmtstr, RE_MAGIC + RE_STRING)) == NULL) goto error2; /* * Advance to next part */ efm = skip_to_option_part(efm + len); /* skip comma and spaces */ } if (fmt_first == NULL) /* nothing found */ { EMSG(_("E378: 'errorformat' contains no pattern")); goto error2; } /* * got_int is reset here, because it was probably set when killing the * ":make" command, but we still want to read the errorfile then. */ got_int = FALSE; /* Always ignore case when looking for a matching error. */ regmatch.rm_ic = TRUE; if (tv != NULL) { if (tv->v_type == VAR_STRING) p_str = tv->vval.v_string; else if (tv->v_type == VAR_LIST) p_li = tv->vval.v_list->lv_first; } /* * Read the lines in the error file one by one. * Try to recognize one of the error formats in each line. */ while (!got_int) { /* Get the next line. */ if (fd == NULL) { if (tv != NULL) { if (tv->v_type == VAR_STRING) { /* Get the next line from the supplied string */ char_u *p; if (!*p_str) /* Reached the end of the string */ break; p = vim_strchr(p_str, '\n'); if (p) len = (int)(p - p_str + 1); else len = (int)STRLEN(p_str); if (len > CMDBUFFSIZE - 2) vim_strncpy(IObuff, p_str, CMDBUFFSIZE - 2); else vim_strncpy(IObuff, p_str, len); p_str += len; } else if (tv->v_type == VAR_LIST) { /* Get the next line from the supplied list */ while (p_li && p_li->li_tv.v_type != VAR_STRING) p_li = p_li->li_next; /* Skip non-string items */ if (!p_li) /* End of the list */ break; len = (int)STRLEN(p_li->li_tv.vval.v_string); if (len > CMDBUFFSIZE - 2) len = CMDBUFFSIZE - 2; vim_strncpy(IObuff, p_li->li_tv.vval.v_string, len); p_li = p_li->li_next; /* next item */ } } else { /* Get the next line from the supplied buffer */ if (buflnum > lnumlast) break; vim_strncpy(IObuff, ml_get_buf(buf, buflnum++, FALSE), CMDBUFFSIZE - 2); } } else if (fgets((char *)IObuff, CMDBUFFSIZE - 2, fd) == NULL) break; IObuff[CMDBUFFSIZE - 2] = NUL; /* for very long lines */ #ifdef FEAT_MBYTE remove_bom(IObuff); #endif if ((efmp = vim_strrchr(IObuff, '\n')) != NULL) *efmp = NUL; #ifdef USE_CRNL if ((efmp = vim_strrchr(IObuff, '\r')) != NULL) *efmp = NUL; #endif /* If there was no %> item start at the first pattern */ if (fmt_start == NULL) fmt_ptr = fmt_first; else { fmt_ptr = fmt_start; fmt_start = NULL; } /* * Try to match each part of 'errorformat' until we find a complete * match or no match. */ valid = TRUE; restofline: for ( ; fmt_ptr != NULL; fmt_ptr = fmt_ptr->next) { idx = fmt_ptr->prefix; if (multiscan && vim_strchr((char_u *)"OPQ", idx) == NULL) continue; namebuf[0] = NUL; pattern[0] = NUL; if (!multiscan) errmsg[0] = NUL; lnum = 0; col = 0; use_viscol = FALSE; enr = -1; type = 0; tail = NULL; regmatch.regprog = fmt_ptr->prog; if (vim_regexec(&regmatch, IObuff, (colnr_T)0)) { if ((idx == 'C' || idx == 'Z') && !multiline) continue; if (vim_strchr((char_u *)"EWI", idx) != NULL) type = idx; else type = 0; /* * Extract error message data from matched line. * We check for an actual submatch, because "\[" and "\]" in * the 'errorformat' may cause the wrong submatch to be used. */ if ((i = (int)fmt_ptr->addr[0]) > 0) /* %f */ { int c; if (regmatch.startp[i] == NULL || regmatch.endp[i] == NULL) continue; /* Expand ~/file and $HOME/file to full path. */ c = *regmatch.endp[i]; *regmatch.endp[i] = NUL; expand_env(regmatch.startp[i], namebuf, CMDBUFFSIZE); *regmatch.endp[i] = c; if (vim_strchr((char_u *)"OPQ", idx) != NULL && mch_getperm(namebuf) == -1) continue; } if ((i = (int)fmt_ptr->addr[1]) > 0) /* %n */ { if (regmatch.startp[i] == NULL) continue; enr = (int)atol((char *)regmatch.startp[i]); } if ((i = (int)fmt_ptr->addr[2]) > 0) /* %l */ { if (regmatch.startp[i] == NULL) continue; lnum = atol((char *)regmatch.startp[i]); } if ((i = (int)fmt_ptr->addr[3]) > 0) /* %c */ { if (regmatch.startp[i] == NULL) continue; col = (int)atol((char *)regmatch.startp[i]); } if ((i = (int)fmt_ptr->addr[4]) > 0) /* %t */ { if (regmatch.startp[i] == NULL) continue; type = *regmatch.startp[i]; } if (fmt_ptr->flags == '+' && !multiscan) /* %+ */ STRCPY(errmsg, IObuff); else if ((i = (int)fmt_ptr->addr[5]) > 0) /* %m */ { if (regmatch.startp[i] == NULL || regmatch.endp[i] == NULL) continue; len = (int)(regmatch.endp[i] - regmatch.startp[i]); vim_strncpy(errmsg, regmatch.startp[i], len); } if ((i = (int)fmt_ptr->addr[6]) > 0) /* %r */ { if (regmatch.startp[i] == NULL) continue; tail = regmatch.startp[i]; } if ((i = (int)fmt_ptr->addr[7]) > 0) /* %p */ { char_u *match_ptr; if (regmatch.startp[i] == NULL || regmatch.endp[i] == NULL) continue; col = 0; for (match_ptr = regmatch.startp[i]; match_ptr != regmatch.endp[i]; ++match_ptr) { ++col; if (*match_ptr == TAB) { col += 7; col -= col % 8; } } ++col; use_viscol = TRUE; } if ((i = (int)fmt_ptr->addr[8]) > 0) /* %v */ { if (regmatch.startp[i] == NULL) continue; col = (int)atol((char *)regmatch.startp[i]); use_viscol = TRUE; } if ((i = (int)fmt_ptr->addr[9]) > 0) /* %s */ { if (regmatch.startp[i] == NULL || regmatch.endp[i] == NULL) continue; len = (int)(regmatch.endp[i] - regmatch.startp[i]); if (len > CMDBUFFSIZE - 5) len = CMDBUFFSIZE - 5; STRCPY(pattern, "^\\V"); STRNCAT(pattern, regmatch.startp[i], len); pattern[len + 3] = '\\'; pattern[len + 4] = '$'; pattern[len + 5] = NUL; } break; } } multiscan = FALSE; if (fmt_ptr == NULL || idx == 'D' || idx == 'X') { if (fmt_ptr != NULL) { if (idx == 'D') /* enter directory */ { if (*namebuf == NUL) { EMSG(_("E379: Missing or empty directory name")); goto error2; } if ((directory = qf_push_dir(namebuf, &dir_stack)) == NULL) goto error2; } else if (idx == 'X') /* leave directory */ directory = qf_pop_dir(&dir_stack); } namebuf[0] = NUL; /* no match found, remove file name */ lnum = 0; /* don't jump to this line */ valid = FALSE; STRCPY(errmsg, IObuff); /* copy whole line to error message */ if (fmt_ptr == NULL) multiline = multiignore = FALSE; } else if (fmt_ptr != NULL) { /* honor %> item */ if (fmt_ptr->conthere) fmt_start = fmt_ptr; if (vim_strchr((char_u *)"AEWI", idx) != NULL) multiline = TRUE; /* start of a multi-line message */ else if (vim_strchr((char_u *)"CZ", idx) != NULL) { /* continuation of multi-line msg */ if (qfprev == NULL) goto error2; if (*errmsg && !multiignore) { len = (int)STRLEN(qfprev->qf_text); if ((ptr = alloc((unsigned)(len + STRLEN(errmsg) + 2))) == NULL) goto error2; STRCPY(ptr, qfprev->qf_text); vim_free(qfprev->qf_text); qfprev->qf_text = ptr; *(ptr += len) = '\n'; STRCPY(++ptr, errmsg); } if (qfprev->qf_nr == -1) qfprev->qf_nr = enr; if (vim_isprintc(type) && !qfprev->qf_type) qfprev->qf_type = type; /* only printable chars allowed */ if (!qfprev->qf_lnum) qfprev->qf_lnum = lnum; if (!qfprev->qf_col) qfprev->qf_col = col; qfprev->qf_viscol = use_viscol; if (!qfprev->qf_fnum) qfprev->qf_fnum = qf_get_fnum(directory, *namebuf || directory ? namebuf : currfile && valid ? currfile : 0); if (idx == 'Z') multiline = multiignore = FALSE; line_breakcheck(); continue; } else if (vim_strchr((char_u *)"OPQ", idx) != NULL) { /* global file names */ valid = FALSE; if (*namebuf == NUL || mch_getperm(namebuf) >= 0) { if (*namebuf && idx == 'P') currfile = qf_push_dir(namebuf, &file_stack); else if (idx == 'Q') currfile = qf_pop_dir(&file_stack); *namebuf = NUL; if (tail && *tail) { STRMOVE(IObuff, skipwhite(tail)); multiscan = TRUE; goto restofline; } } } if (fmt_ptr->flags == '-') /* generally exclude this line */ { if (multiline) multiignore = TRUE; /* also exclude continuation lines */ continue; } } if (qf_add_entry(qi, &qfprev, directory, (*namebuf || directory) ? namebuf : ((currfile && valid) ? currfile : (char_u *)NULL), 0, errmsg, lnum, col, use_viscol, pattern, enr, type, valid) == FAIL) goto error2; line_breakcheck(); } if (fd == NULL || !ferror(fd)) { if (qi->qf_lists[qi->qf_curlist].qf_index == 0) { /* no valid entry found */ qi->qf_lists[qi->qf_curlist].qf_ptr = qi->qf_lists[qi->qf_curlist].qf_start; qi->qf_lists[qi->qf_curlist].qf_index = 1; qi->qf_lists[qi->qf_curlist].qf_nonevalid = TRUE; } else { qi->qf_lists[qi->qf_curlist].qf_nonevalid = FALSE; if (qi->qf_lists[qi->qf_curlist].qf_ptr == NULL) qi->qf_lists[qi->qf_curlist].qf_ptr = qi->qf_lists[qi->qf_curlist].qf_start; } /* return number of matches */ retval = qi->qf_lists[qi->qf_curlist].qf_count; goto qf_init_ok; } EMSG(_(e_readerrf)); error2: qf_free(qi, qi->qf_curlist); qi->qf_listcount--; if (qi->qf_curlist > 0) --qi->qf_curlist; qf_init_ok: if (fd != NULL) fclose(fd); for (fmt_ptr = fmt_first; fmt_ptr != NULL; fmt_ptr = fmt_first) { fmt_first = fmt_ptr->next; vim_free(fmt_ptr->prog); vim_free(fmt_ptr); } qf_clean_dir_stack(&dir_stack); qf_clean_dir_stack(&file_stack); qf_init_end: vim_free(namebuf); vim_free(errmsg); vim_free(pattern); vim_free(fmtstr); #ifdef FEAT_WINDOWS qf_update_buffer(qi); #endif return retval; } /* * Prepare for adding a new quickfix list. */ static void qf_new_list(qi, qf_title) qf_info_T *qi; char_u *qf_title; { int i; /* * If the current entry is not the last entry, delete entries below * the current entry. This makes it possible to browse in a tree-like * way with ":grep'. */ while (qi->qf_listcount > qi->qf_curlist + 1) qf_free(qi, --qi->qf_listcount); /* * When the stack is full, remove to oldest entry * Otherwise, add a new entry. */ if (qi->qf_listcount == LISTCOUNT) { qf_free(qi, 0); for (i = 1; i < LISTCOUNT; ++i) qi->qf_lists[i - 1] = qi->qf_lists[i]; qi->qf_curlist = LISTCOUNT - 1; } else qi->qf_curlist = qi->qf_listcount++; vim_memset(&qi->qf_lists[qi->qf_curlist], 0, (size_t)(sizeof(qf_list_T))); if (qf_title != NULL) { char_u *p = alloc((int)STRLEN(qf_title) + 2); qi->qf_lists[qi->qf_curlist].qf_title = p; if (p != NULL) sprintf((char *)p, ":%s", (char *)qf_title); } } /* * Free a location list */ static void ll_free_all(pqi) qf_info_T **pqi; { int i; qf_info_T *qi; qi = *pqi; if (qi == NULL) return; *pqi = NULL; /* Remove reference to this list */ qi->qf_refcount--; if (qi->qf_refcount < 1) { /* No references to this location list */ for (i = 0; i < qi->qf_listcount; ++i) qf_free(qi, i); vim_free(qi); } } void qf_free_all(wp) win_T *wp; { int i; qf_info_T *qi = &ql_info; if (wp != NULL) { /* location list */ ll_free_all(&wp->w_llist); ll_free_all(&wp->w_llist_ref); } else /* quickfix list */ for (i = 0; i < qi->qf_listcount; ++i) qf_free(qi, i); } /* * Add an entry to the end of the list of errors. * Returns OK or FAIL. */ static int qf_add_entry(qi, prevp, dir, fname, bufnum, mesg, lnum, col, vis_col, pattern, nr, type, valid) qf_info_T *qi; /* quickfix list */ qfline_T **prevp; /* pointer to previously added entry or NULL */ char_u *dir; /* optional directory name */ char_u *fname; /* file name or NULL */ int bufnum; /* buffer number or zero */ char_u *mesg; /* message */ long lnum; /* line number */ int col; /* column */ int vis_col; /* using visual column */ char_u *pattern; /* search pattern */ int nr; /* error number */ int type; /* type character */ int valid; /* valid entry */ { qfline_T *qfp; if ((qfp = (qfline_T *)alloc((unsigned)sizeof(qfline_T))) == NULL) return FAIL; if (bufnum != 0) qfp->qf_fnum = bufnum; else qfp->qf_fnum = qf_get_fnum(dir, fname); if ((qfp->qf_text = vim_strsave(mesg)) == NULL) { vim_free(qfp); return FAIL; } qfp->qf_lnum = lnum; qfp->qf_col = col; qfp->qf_viscol = vis_col; if (pattern == NULL || *pattern == NUL) qfp->qf_pattern = NULL; else if ((qfp->qf_pattern = vim_strsave(pattern)) == NULL) { vim_free(qfp->qf_text); vim_free(qfp); return FAIL; } qfp->qf_nr = nr; if (type != 1 && !vim_isprintc(type)) /* only printable chars allowed */ type = 0; qfp->qf_type = type; qfp->qf_valid = valid; if (qi->qf_lists[qi->qf_curlist].qf_count == 0) /* first element in the list */ { qi->qf_lists[qi->qf_curlist].qf_start = qfp; qfp->qf_prev = qfp; /* first element points to itself */ } else { qfp->qf_prev = *prevp; (*prevp)->qf_next = qfp; } qfp->qf_next = qfp; /* last element points to itself */ qfp->qf_cleared = FALSE; *prevp = qfp; ++qi->qf_lists[qi->qf_curlist].qf_count; if (qi->qf_lists[qi->qf_curlist].qf_index == 0 && qfp->qf_valid) /* first valid entry */ { qi->qf_lists[qi->qf_curlist].qf_index = qi->qf_lists[qi->qf_curlist].qf_count; qi->qf_lists[qi->qf_curlist].qf_ptr = qfp; } return OK; } /* * Allocate a new location list */ static qf_info_T * ll_new_list() { qf_info_T *qi; qi = (qf_info_T *)alloc((unsigned)sizeof(qf_info_T)); if (qi != NULL) { vim_memset(qi, 0, (size_t)(sizeof(qf_info_T))); qi->qf_refcount++; } return qi; } /* * Return the location list for window 'wp'. * If not present, allocate a location list */ static qf_info_T * ll_get_or_alloc_list(wp) win_T *wp; { if (IS_LL_WINDOW(wp)) /* For a location list window, use the referenced location list */ return wp->w_llist_ref; /* * For a non-location list window, w_llist_ref should not point to a * location list. */ ll_free_all(&wp->w_llist_ref); if (wp->w_llist == NULL) wp->w_llist = ll_new_list(); /* new location list */ return wp->w_llist; } /* * Copy the location list from window "from" to window "to". */ void copy_loclist(from, to) win_T *from; win_T *to; { qf_info_T *qi; int idx; int i; /* * When copying from a location list window, copy the referenced * location list. For other windows, copy the location list for * that window. */ if (IS_LL_WINDOW(from)) qi = from->w_llist_ref; else qi = from->w_llist; if (qi == NULL) /* no location list to copy */ return; /* allocate a new location list */ if ((to->w_llist = ll_new_list()) == NULL) return; to->w_llist->qf_listcount = qi->qf_listcount; /* Copy the location lists one at a time */ for (idx = 0; idx < qi->qf_listcount; idx++) { qf_list_T *from_qfl; qf_list_T *to_qfl; to->w_llist->qf_curlist = idx; from_qfl = &qi->qf_lists[idx]; to_qfl = &to->w_llist->qf_lists[idx]; /* Some of the fields are populated by qf_add_entry() */ to_qfl->qf_nonevalid = from_qfl->qf_nonevalid; to_qfl->qf_count = 0; to_qfl->qf_index = 0; to_qfl->qf_start = NULL; to_qfl->qf_ptr = NULL; if (from_qfl->qf_title != NULL) to_qfl->qf_title = vim_strsave(from_qfl->qf_title); else to_qfl->qf_title = NULL; if (from_qfl->qf_count) { qfline_T *from_qfp; qfline_T *prevp = NULL; /* copy all the location entries in this list */ for (i = 0, from_qfp = from_qfl->qf_start; i < from_qfl->qf_count; ++i, from_qfp = from_qfp->qf_next) { if (qf_add_entry(to->w_llist, &prevp, NULL, NULL, 0, from_qfp->qf_text, from_qfp->qf_lnum, from_qfp->qf_col, from_qfp->qf_viscol, from_qfp->qf_pattern, from_qfp->qf_nr, 0, from_qfp->qf_valid) == FAIL) { qf_free_all(to); return; } /* * qf_add_entry() will not set the qf_num field, as the * directory and file names are not supplied. So the qf_fnum * field is copied here. */ prevp->qf_fnum = from_qfp->qf_fnum; /* file number */ prevp->qf_type = from_qfp->qf_type; /* error type */ if (from_qfl->qf_ptr == from_qfp) to_qfl->qf_ptr = prevp; /* current location */ } } to_qfl->qf_index = from_qfl->qf_index; /* current index in the list */ /* When no valid entries are present in the list, qf_ptr points to * the first item in the list */ if (to_qfl->qf_nonevalid) to_qfl->qf_ptr = to_qfl->qf_start; } to->w_llist->qf_curlist = qi->qf_curlist; /* current list */ } /* * get buffer number for file "dir.name" */ static int qf_get_fnum(directory, fname) char_u *directory; char_u *fname; { if (fname == NULL || *fname == NUL) /* no file name */ return 0; { char_u *ptr; int fnum; #ifdef VMS vms_remove_version(fname); #endif #ifdef BACKSLASH_IN_FILENAME if (directory != NULL) slash_adjust(directory); slash_adjust(fname); #endif if (directory != NULL && !vim_isAbsName(fname) && (ptr = concat_fnames(directory, fname, TRUE)) != NULL) { /* * Here we check if the file really exists. * This should normally be true, but if make works without * "leaving directory"-messages we might have missed a * directory change. */ if (mch_getperm(ptr) < 0) { vim_free(ptr); directory = qf_guess_filepath(fname); if (directory) ptr = concat_fnames(directory, fname, TRUE); else ptr = vim_strsave(fname); } /* Use concatenated directory name and file name */ fnum = buflist_add(ptr, 0); vim_free(ptr); return fnum; } return buflist_add(fname, 0); } } /* * push dirbuf onto the directory stack and return pointer to actual dir or * NULL on error */ static char_u * qf_push_dir(dirbuf, stackptr) char_u *dirbuf; struct dir_stack_T **stackptr; { struct dir_stack_T *ds_new; struct dir_stack_T *ds_ptr; /* allocate new stack element and hook it in */ ds_new = (struct dir_stack_T *)alloc((unsigned)sizeof(struct dir_stack_T)); if (ds_new == NULL) return NULL; ds_new->next = *stackptr; *stackptr = ds_new; /* store directory on the stack */ if (vim_isAbsName(dirbuf) || (*stackptr)->next == NULL || (*stackptr && dir_stack != *stackptr)) (*stackptr)->dirname = vim_strsave(dirbuf); else { /* Okay we don't have an absolute path. * dirbuf must be a subdir of one of the directories on the stack. * Let's search... */ ds_new = (*stackptr)->next; (*stackptr)->dirname = NULL; while (ds_new) { vim_free((*stackptr)->dirname); (*stackptr)->dirname = concat_fnames(ds_new->dirname, dirbuf, TRUE); if (mch_isdir((*stackptr)->dirname) == TRUE) break; ds_new = ds_new->next; } /* clean up all dirs we already left */ while ((*stackptr)->next != ds_new) { ds_ptr = (*stackptr)->next; (*stackptr)->next = (*stackptr)->next->next; vim_free(ds_ptr->dirname); vim_free(ds_ptr); } /* Nothing found -> it must be on top level */ if (ds_new == NULL) { vim_free((*stackptr)->dirname); (*stackptr)->dirname = vim_strsave(dirbuf); } } if ((*stackptr)->dirname != NULL) return (*stackptr)->dirname; else { ds_ptr = *stackptr; *stackptr = (*stackptr)->next; vim_free(ds_ptr); return NULL; } } /* * pop dirbuf from the directory stack and return previous directory or NULL if * stack is empty */ static char_u * qf_pop_dir(stackptr) struct dir_stack_T **stackptr; { struct dir_stack_T *ds_ptr; /* TODO: Should we check if dirbuf is the directory on top of the stack? * What to do if it isn't? */ /* pop top element and free it */ if (*stackptr != NULL) { ds_ptr = *stackptr; *stackptr = (*stackptr)->next; vim_free(ds_ptr->dirname); vim_free(ds_ptr); } /* return NEW top element as current dir or NULL if stack is empty*/ return *stackptr ? (*stackptr)->dirname : NULL; } /* * clean up directory stack */ static void qf_clean_dir_stack(stackptr) struct dir_stack_T **stackptr; { struct dir_stack_T *ds_ptr; while ((ds_ptr = *stackptr) != NULL) { *stackptr = (*stackptr)->next; vim_free(ds_ptr->dirname); vim_free(ds_ptr); } } /* * Check in which directory of the directory stack the given file can be * found. * Returns a pointer to the directory name or NULL if not found * Cleans up intermediate directory entries. * * TODO: How to solve the following problem? * If we have the this directory tree: * ./ * ./aa * ./aa/bb * ./bb * ./bb/x.c * and make says: * making all in aa * making all in bb * x.c:9: Error * Then qf_push_dir thinks we are in ./aa/bb, but we are in ./bb. * qf_guess_filepath will return NULL. */ static char_u * qf_guess_filepath(filename) char_u *filename; { struct dir_stack_T *ds_ptr; struct dir_stack_T *ds_tmp; char_u *fullname; /* no dirs on the stack - there's nothing we can do */ if (dir_stack == NULL) return NULL; ds_ptr = dir_stack->next; fullname = NULL; while (ds_ptr) { vim_free(fullname); fullname = concat_fnames(ds_ptr->dirname, filename, TRUE); /* If concat_fnames failed, just go on. The worst thing that can happen * is that we delete the entire stack. */ if ((fullname != NULL) && (mch_getperm(fullname) >= 0)) break; ds_ptr = ds_ptr->next; } vim_free(fullname); /* clean up all dirs we already left */ while (dir_stack->next != ds_ptr) { ds_tmp = dir_stack->next; dir_stack->next = dir_stack->next->next; vim_free(ds_tmp->dirname); vim_free(ds_tmp); } return ds_ptr==NULL? NULL: ds_ptr->dirname; } /* * jump to a quickfix line * if dir == FORWARD go "errornr" valid entries forward * if dir == BACKWARD go "errornr" valid entries backward * if dir == FORWARD_FILE go "errornr" valid entries files backward * if dir == BACKWARD_FILE go "errornr" valid entries files backward * else if "errornr" is zero, redisplay the same line * else go to entry "errornr" */ void qf_jump(qi, dir, errornr, forceit) qf_info_T *qi; int dir; int errornr; int forceit; { qf_info_T *ll_ref; qfline_T *qf_ptr; qfline_T *old_qf_ptr; int qf_index; int old_qf_fnum; int old_qf_index; int prev_index; static char_u *e_no_more_items = (char_u *)N_("E553: No more items"); char_u *err = e_no_more_items; linenr_T i; buf_T *old_curbuf; linenr_T old_lnum; colnr_T screen_col; colnr_T char_col; char_u *line; #ifdef FEAT_WINDOWS char_u *old_swb = p_swb; unsigned old_swb_flags = swb_flags; int opened_window = FALSE; win_T *win; win_T *altwin; int flags; #endif win_T *oldwin = curwin; int print_message = TRUE; int len; #ifdef FEAT_FOLDING int old_KeyTyped = KeyTyped; /* getting file may reset it */ #endif int ok = OK; int usable_win; if (qi == NULL) qi = &ql_info; if (qi->qf_curlist >= qi->qf_listcount || qi->qf_lists[qi->qf_curlist].qf_count == 0) { EMSG(_(e_quickfix)); return; } qf_ptr = qi->qf_lists[qi->qf_curlist].qf_ptr; old_qf_ptr = qf_ptr; qf_index = qi->qf_lists[qi->qf_curlist].qf_index; old_qf_index = qf_index; if (dir == FORWARD || dir == FORWARD_FILE) /* next valid entry */ { while (errornr--) { old_qf_ptr = qf_ptr; prev_index = qf_index; old_qf_fnum = qf_ptr->qf_fnum; do { if (qf_index == qi->qf_lists[qi->qf_curlist].qf_count || qf_ptr->qf_next == NULL) { qf_ptr = old_qf_ptr; qf_index = prev_index; if (err != NULL) { EMSG(_(err)); goto theend; } errornr = 0; break; } ++qf_index; qf_ptr = qf_ptr->qf_next; } while ((!qi->qf_lists[qi->qf_curlist].qf_nonevalid && !qf_ptr->qf_valid) || (dir == FORWARD_FILE && qf_ptr->qf_fnum == old_qf_fnum)); err = NULL; } } else if (dir == BACKWARD || dir == BACKWARD_FILE) /* prev. valid entry */ { while (errornr--) { old_qf_ptr = qf_ptr; prev_index = qf_index; old_qf_fnum = qf_ptr->qf_fnum; do { if (qf_index == 1 || qf_ptr->qf_prev == NULL) { qf_ptr = old_qf_ptr; qf_index = prev_index; if (err != NULL) { EMSG(_(err)); goto theend; } errornr = 0; break; } --qf_index; qf_ptr = qf_ptr->qf_prev; } while ((!qi->qf_lists[qi->qf_curlist].qf_nonevalid && !qf_ptr->qf_valid) || (dir == BACKWARD_FILE && qf_ptr->qf_fnum == old_qf_fnum)); err = NULL; } } else if (errornr != 0) /* go to specified number */ { while (errornr < qf_index && qf_index > 1 && qf_ptr->qf_prev != NULL) { --qf_index; qf_ptr = qf_ptr->qf_prev; } while (errornr > qf_index && qf_index < qi->qf_lists[qi->qf_curlist].qf_count && qf_ptr->qf_next != NULL) { ++qf_index; qf_ptr = qf_ptr->qf_next; } } #ifdef FEAT_WINDOWS qi->qf_lists[qi->qf_curlist].qf_index = qf_index; if (qf_win_pos_update(qi, old_qf_index)) /* No need to print the error message if it's visible in the error * window */ print_message = FALSE; /* * For ":helpgrep" find a help window or open one. */ if (qf_ptr->qf_type == 1 && (!curwin->w_buffer->b_help || cmdmod.tab != 0)) { win_T *wp; if (cmdmod.tab != 0) wp = NULL; else for (wp = firstwin; wp != NULL; wp = wp->w_next) if (wp->w_buffer != NULL && wp->w_buffer->b_help) break; if (wp != NULL && wp->w_buffer->b_nwindows > 0) win_enter(wp, TRUE); else { /* * Split off help window; put it at far top if no position * specified, the current window is vertically split and narrow. */ flags = WSP_HELP; # ifdef FEAT_VERTSPLIT if (cmdmod.split == 0 && curwin->w_width != Columns && curwin->w_width < 80) flags |= WSP_TOP; # endif if (qi != &ql_info) flags |= WSP_NEWLOC; /* don't copy the location list */ if (win_split(0, flags) == FAIL) goto theend; opened_window = TRUE; /* close it when fail */ if (curwin->w_height < p_hh) win_setheight((int)p_hh); if (qi != &ql_info) /* not a quickfix list */ { /* The new window should use the supplied location list */ curwin->w_llist = qi; qi->qf_refcount++; } } if (!p_im) restart_edit = 0; /* don't want insert mode in help file */ } /* * If currently in the quickfix window, find another window to show the * file in. */ if (bt_quickfix(curbuf) && !opened_window) { /* * If there is no file specified, we don't know where to go. * But do advance, otherwise ":cn" gets stuck. */ if (qf_ptr->qf_fnum == 0) goto theend; /* Locate a window showing a normal buffer */ usable_win = 0; FOR_ALL_WINDOWS(win) if (win->w_buffer->b_p_bt[0] == NUL) { usable_win = 1; break; } /* * If no usable window is found and 'switchbuf' contains "usetab" * then search in other tabs. */ if (!usable_win && (swb_flags & SWB_USETAB)) { tabpage_T *tp; win_T *wp; FOR_ALL_TAB_WINDOWS(tp, wp) { if (wp->w_buffer->b_fnum == qf_ptr->qf_fnum) { goto_tabpage_win(tp, wp); usable_win = 1; goto win_found; } } } win_found: /* * If there is only one window and it is the quickfix window, create a * new one above the quickfix window. */ if (((firstwin == lastwin) && bt_quickfix(curbuf)) || !usable_win) { ll_ref = curwin->w_llist_ref; flags = WSP_ABOVE; if (ll_ref != NULL) flags |= WSP_NEWLOC; if (win_split(0, flags) == FAIL) goto failed; /* not enough room for window */ opened_window = TRUE; /* close it when fail */ p_swb = empty_option; /* don't split again */ swb_flags = 0; RESET_BINDING(curwin); if (ll_ref != NULL) { /* The new window should use the location list from the * location list window */ curwin->w_llist = ll_ref; ll_ref->qf_refcount++; } } else { if (curwin->w_llist_ref != NULL) { /* In a location window */ ll_ref = curwin->w_llist_ref; /* Find the window with the same location list */ FOR_ALL_WINDOWS(win) if (win->w_llist == ll_ref) break; if (win == NULL) { /* Find the window showing the selected file */ FOR_ALL_WINDOWS(win) if (win->w_buffer->b_fnum == qf_ptr->qf_fnum) break; if (win == NULL) { /* Find a previous usable window */ win = curwin; do { if (win->w_buffer->b_p_bt[0] == NUL) break; if (win->w_prev == NULL) win = lastwin; /* wrap around the top */ else win = win->w_prev; /* go to previous window */ } while (win != curwin); } } win_goto(win); /* If the location list for the window is not set, then set it * to the location list from the location window */ if (win->w_llist == NULL) { win->w_llist = ll_ref; ll_ref->qf_refcount++; } } else { /* * Try to find a window that shows the right buffer. * Default to the window just above the quickfix buffer. */ win = curwin; altwin = NULL; for (;;) { if (win->w_buffer->b_fnum == qf_ptr->qf_fnum) break; if (win->w_prev == NULL) win = lastwin; /* wrap around the top */ else win = win->w_prev; /* go to previous window */ if (IS_QF_WINDOW(win)) { /* Didn't find it, go to the window before the quickfix * window. */ if (altwin != NULL) win = altwin; else if (curwin->w_prev != NULL) win = curwin->w_prev; else win = curwin->w_next; break; } /* Remember a usable window. */ if (altwin == NULL && !win->w_p_pvw && win->w_buffer->b_p_bt[0] == NUL) altwin = win; } win_goto(win); } } } #endif /* * If there is a file name, * read the wanted file if needed, and check autowrite etc. */ old_curbuf = curbuf; old_lnum = curwin->w_cursor.lnum; if (qf_ptr->qf_fnum != 0) { if (qf_ptr->qf_type == 1) { /* Open help file (do_ecmd() will set b_help flag, readfile() will * set b_p_ro flag). */ if (!can_abandon(curbuf, forceit)) { EMSG(_(e_nowrtmsg)); ok = FALSE; } else ok = do_ecmd(qf_ptr->qf_fnum, NULL, NULL, NULL, (linenr_T)1, ECMD_HIDE + ECMD_SET_HELP, oldwin == curwin ? curwin : NULL); } else ok = buflist_getfile(qf_ptr->qf_fnum, (linenr_T)1, GETF_SETMARK | GETF_SWITCH, forceit); } if (ok == OK) { /* When not switched to another buffer, still need to set pc mark */ if (curbuf == old_curbuf) setpcmark(); if (qf_ptr->qf_pattern == NULL) { /* * Go to line with error, unless qf_lnum is 0. */ i = qf_ptr->qf_lnum; if (i > 0) { if (i > curbuf->b_ml.ml_line_count) i = curbuf->b_ml.ml_line_count; curwin->w_cursor.lnum = i; } if (qf_ptr->qf_col > 0) { curwin->w_cursor.col = qf_ptr->qf_col - 1; if (qf_ptr->qf_viscol == TRUE) { /* * Check each character from the beginning of the error * line up to the error column. For each tab character * found, reduce the error column value by the length of * a tab character. */ line = ml_get_curline(); screen_col = 0; for (char_col = 0; char_col < curwin->w_cursor.col; ++char_col) { if (*line == NUL) break; if (*line++ == '\t') { curwin->w_cursor.col -= 7 - (screen_col % 8); screen_col += 8 - (screen_col % 8); } else ++screen_col; } } check_cursor(); } else beginline(BL_WHITE | BL_FIX); } else { pos_T save_cursor; /* Move the cursor to the first line in the buffer */ save_cursor = curwin->w_cursor; curwin->w_cursor.lnum = 0; if (!do_search(NULL, '/', qf_ptr->qf_pattern, (long)1, SEARCH_KEEP, NULL)) curwin->w_cursor = save_cursor; } #ifdef FEAT_FOLDING if ((fdo_flags & FDO_QUICKFIX) && old_KeyTyped) foldOpenCursor(); #endif if (print_message) { /* Update the screen before showing the message, unless the screen * scrolled up. */ if (!msg_scrolled) update_topline_redraw(); sprintf((char *)IObuff, _("(%d of %d)%s%s: "), qf_index, qi->qf_lists[qi->qf_curlist].qf_count, qf_ptr->qf_cleared ? _(" (line deleted)") : "", (char *)qf_types(qf_ptr->qf_type, qf_ptr->qf_nr)); /* Add the message, skipping leading whitespace and newlines. */ len = (int)STRLEN(IObuff); qf_fmt_text(skipwhite(qf_ptr->qf_text), IObuff + len, IOSIZE - len); /* Output the message. Overwrite to avoid scrolling when the 'O' * flag is present in 'shortmess'; But when not jumping, print the * whole message. */ i = msg_scroll; if (curbuf == old_curbuf && curwin->w_cursor.lnum == old_lnum) msg_scroll = TRUE; else if (!msg_scrolled && shortmess(SHM_OVERALL)) msg_scroll = FALSE; msg_attr_keep(IObuff, 0, TRUE); msg_scroll = i; } } else { #ifdef FEAT_WINDOWS if (opened_window) win_close(curwin, TRUE); /* Close opened window */ #endif if (qf_ptr->qf_fnum != 0) { /* * Couldn't open file, so put index back where it was. This could * happen if the file was readonly and we changed something. */ #ifdef FEAT_WINDOWS failed: #endif qf_ptr = old_qf_ptr; qf_index = old_qf_index; } } theend: qi->qf_lists[qi->qf_curlist].qf_ptr = qf_ptr; qi->qf_lists[qi->qf_curlist].qf_index = qf_index; #ifdef FEAT_WINDOWS if (p_swb != old_swb && opened_window) { /* Restore old 'switchbuf' value, but not when an autocommand or * modeline has changed the value. */ if (p_swb == empty_option) { p_swb = old_swb; swb_flags = old_swb_flags; } else free_string_option(old_swb); } #endif } /* * ":clist": list all errors * ":llist": list all locations */ void qf_list(eap) exarg_T *eap; { buf_T *buf; char_u *fname; qfline_T *qfp; int i; int idx1 = 1; int idx2 = -1; char_u *arg = eap->arg; int all = eap->forceit; /* if not :cl!, only show recognised errors */ qf_info_T *qi = &ql_info; if (eap->cmdidx == CMD_llist) { qi = GET_LOC_LIST(curwin); if (qi == NULL) { EMSG(_(e_loclist)); return; } } if (qi->qf_curlist >= qi->qf_listcount || qi->qf_lists[qi->qf_curlist].qf_count == 0) { EMSG(_(e_quickfix)); return; } if (!get_list_range(&arg, &idx1, &idx2) || *arg != NUL) { EMSG(_(e_trailing)); return; } i = qi->qf_lists[qi->qf_curlist].qf_count; if (idx1 < 0) idx1 = (-idx1 > i) ? 0 : idx1 + i + 1; if (idx2 < 0) idx2 = (-idx2 > i) ? 0 : idx2 + i + 1; if (qi->qf_lists[qi->qf_curlist].qf_nonevalid) all = TRUE; qfp = qi->qf_lists[qi->qf_curlist].qf_start; for (i = 1; !got_int && i <= qi->qf_lists[qi->qf_curlist].qf_count; ) { if ((qfp->qf_valid || all) && idx1 <= i && i <= idx2) { msg_putchar('\n'); if (got_int) break; fname = NULL; if (qfp->qf_fnum != 0 && (buf = buflist_findnr(qfp->qf_fnum)) != NULL) { fname = buf->b_fname; if (qfp->qf_type == 1) /* :helpgrep */ fname = gettail(fname); } if (fname == NULL) sprintf((char *)IObuff, "%2d", i); else vim_snprintf((char *)IObuff, IOSIZE, "%2d %s", i, (char *)fname); msg_outtrans_attr(IObuff, i == qi->qf_lists[qi->qf_curlist].qf_index ? hl_attr(HLF_L) : hl_attr(HLF_D)); if (qfp->qf_lnum == 0) IObuff[0] = NUL; else if (qfp->qf_col == 0) sprintf((char *)IObuff, ":%ld", qfp->qf_lnum); else sprintf((char *)IObuff, ":%ld col %d", qfp->qf_lnum, qfp->qf_col); sprintf((char *)IObuff + STRLEN(IObuff), "%s:", (char *)qf_types(qfp->qf_type, qfp->qf_nr)); msg_puts_attr(IObuff, hl_attr(HLF_N)); if (qfp->qf_pattern != NULL) { qf_fmt_text(qfp->qf_pattern, IObuff, IOSIZE); STRCAT(IObuff, ":"); msg_puts(IObuff); } msg_puts((char_u *)" "); /* Remove newlines and leading whitespace from the text. For an * unrecognized line keep the indent, the compiler may mark a word * with ^^^^. */ qf_fmt_text((fname != NULL || qfp->qf_lnum != 0) ? skipwhite(qfp->qf_text) : qfp->qf_text, IObuff, IOSIZE); msg_prt_line(IObuff, FALSE); out_flush(); /* show one line at a time */ } qfp = qfp->qf_next; ++i; ui_breakcheck(); } } /* * Remove newlines and leading whitespace from an error message. * Put the result in "buf[bufsize]". */ static void qf_fmt_text(text, buf, bufsize) char_u *text; char_u *buf; int bufsize; { int i; char_u *p = text; for (i = 0; *p != NUL && i < bufsize - 1; ++i) { if (*p == '\n') { buf[i] = ' '; while (*++p != NUL) if (!vim_iswhite(*p) && *p != '\n') break; } else buf[i] = *p++; } buf[i] = NUL; } /* * ":colder [count]": Up in the quickfix stack. * ":cnewer [count]": Down in the quickfix stack. * ":lolder [count]": Up in the location list stack. * ":lnewer [count]": Down in the location list stack. */ void qf_age(eap) exarg_T *eap; { qf_info_T *qi = &ql_info; int count; if (eap->cmdidx == CMD_lolder || eap->cmdidx == CMD_lnewer) { qi = GET_LOC_LIST(curwin); if (qi == NULL) { EMSG(_(e_loclist)); return; } } if (eap->addr_count != 0) count = eap->line2; else count = 1; while (count--) { if (eap->cmdidx == CMD_colder || eap->cmdidx == CMD_lolder) { if (qi->qf_curlist == 0) { EMSG(_("E380: At bottom of quickfix stack")); return; } --qi->qf_curlist; } else { if (qi->qf_curlist >= qi->qf_listcount - 1) { EMSG(_("E381: At top of quickfix stack")); return; } ++qi->qf_curlist; } } qf_msg(qi); } static void qf_msg(qi) qf_info_T *qi; { smsg((char_u *)_("error list %d of %d; %d errors"), qi->qf_curlist + 1, qi->qf_listcount, qi->qf_lists[qi->qf_curlist].qf_count); #ifdef FEAT_WINDOWS qf_update_buffer(qi); #endif } /* * Free error list "idx". */ static void qf_free(qi, idx) qf_info_T *qi; int idx; { qfline_T *qfp; while (qi->qf_lists[idx].qf_count) { qfp = qi->qf_lists[idx].qf_start->qf_next; vim_free(qi->qf_lists[idx].qf_start->qf_text); vim_free(qi->qf_lists[idx].qf_start->qf_pattern); vim_free(qi->qf_lists[idx].qf_start); qi->qf_lists[idx].qf_start = qfp; --qi->qf_lists[idx].qf_count; } vim_free(qi->qf_lists[idx].qf_title); qi->qf_lists[idx].qf_title = NULL; } /* * qf_mark_adjust: adjust marks */ void qf_mark_adjust(wp, line1, line2, amount, amount_after) win_T *wp; linenr_T line1; linenr_T line2; long amount; long amount_after; { int i; qfline_T *qfp; int idx; qf_info_T *qi = &ql_info; if (wp != NULL) { if (wp->w_llist == NULL) return; qi = wp->w_llist; } for (idx = 0; idx < qi->qf_listcount; ++idx) if (qi->qf_lists[idx].qf_count) for (i = 0, qfp = qi->qf_lists[idx].qf_start; i < qi->qf_lists[idx].qf_count; ++i, qfp = qfp->qf_next) if (qfp->qf_fnum == curbuf->b_fnum) { if (qfp->qf_lnum >= line1 && qfp->qf_lnum <= line2) { if (amount == MAXLNUM) qfp->qf_cleared = TRUE; else qfp->qf_lnum += amount; } else if (amount_after && qfp->qf_lnum > line2) qfp->qf_lnum += amount_after; } } /* * Make a nice message out of the error character and the error number: * char number message * e or E 0 " error" * w or W 0 " warning" * i or I 0 " info" * 0 0 "" * other 0 " c" * e or E n " error n" * w or W n " warning n" * i or I n " info n" * 0 n " error n" * other n " c n" * 1 x "" :helpgrep */ static char_u * qf_types(c, nr) int c, nr; { static char_u buf[20]; static char_u cc[3]; char_u *p; if (c == 'W' || c == 'w') p = (char_u *)" warning"; else if (c == 'I' || c == 'i') p = (char_u *)" info"; else if (c == 'E' || c == 'e' || (c == 0 && nr > 0)) p = (char_u *)" error"; else if (c == 0 || c == 1) p = (char_u *)""; else { cc[0] = ' '; cc[1] = c; cc[2] = NUL; p = cc; } if (nr <= 0) return p; sprintf((char *)buf, "%s %3d", (char *)p, nr); return buf; } #if defined(FEAT_WINDOWS) || defined(PROTO) /* * ":cwindow": open the quickfix window if we have errors to display, * close it if not. * ":lwindow": open the location list window if we have locations to display, * close it if not. */ void ex_cwindow(eap) exarg_T *eap; { qf_info_T *qi = &ql_info; win_T *win; if (eap->cmdidx == CMD_lwindow) { qi = GET_LOC_LIST(curwin); if (qi == NULL) return; } /* Look for an existing quickfix window. */ win = qf_find_win(qi); /* * If a quickfix window is open but we have no errors to display, * close the window. If a quickfix window is not open, then open * it if we have errors; otherwise, leave it closed. */ if (qi->qf_lists[qi->qf_curlist].qf_nonevalid || qi->qf_lists[qi->qf_curlist].qf_count == 0 || qi->qf_curlist >= qi->qf_listcount) { if (win != NULL) ex_cclose(eap); } else if (win == NULL) ex_copen(eap); } /* * ":cclose": close the window showing the list of errors. * ":lclose": close the window showing the location list */ void ex_cclose(eap) exarg_T *eap; { win_T *win = NULL; qf_info_T *qi = &ql_info; if (eap->cmdidx == CMD_lclose || eap->cmdidx == CMD_lwindow) { qi = GET_LOC_LIST(curwin); if (qi == NULL) return; } /* Find existing quickfix window and close it. */ win = qf_find_win(qi); if (win != NULL) win_close(win, FALSE); } /* * ":copen": open a window that shows the list of errors. * ":lopen": open a window that shows the location list. */ void ex_copen(eap) exarg_T *eap; { qf_info_T *qi = &ql_info; int height; win_T *win; tabpage_T *prevtab = curtab; buf_T *qf_buf; win_T *oldwin = curwin; if (eap->cmdidx == CMD_lopen || eap->cmdidx == CMD_lwindow) { qi = GET_LOC_LIST(curwin); if (qi == NULL) { EMSG(_(e_loclist)); return; } } if (eap->addr_count != 0) height = eap->line2; else height = QF_WINHEIGHT; #ifdef FEAT_VISUAL reset_VIsual_and_resel(); /* stop Visual mode */ #endif #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif /* * Find existing quickfix window, or open a new one. */ win = qf_find_win(qi); if (win != NULL && cmdmod.tab == 0) win_goto(win); else { qf_buf = qf_find_buf(qi); /* The current window becomes the previous window afterwards. */ win = curwin; if (eap->cmdidx == CMD_copen || eap->cmdidx == CMD_cwindow) /* Create the new window at the very bottom. */ win_goto(lastwin); if (win_split(height, WSP_BELOW | WSP_NEWLOC) == FAIL) return; /* not enough room for window */ RESET_BINDING(curwin); if (eap->cmdidx == CMD_lopen || eap->cmdidx == CMD_lwindow) { /* * For the location list window, create a reference to the * location list from the window 'win'. */ curwin->w_llist_ref = win->w_llist; win->w_llist->qf_refcount++; } if (oldwin != curwin) oldwin = NULL; /* don't store info when in another window */ if (qf_buf != NULL) /* Use the existing quickfix buffer */ (void)do_ecmd(qf_buf->b_fnum, NULL, NULL, NULL, ECMD_ONE, ECMD_HIDE + ECMD_OLDBUF, oldwin); else { /* Create a new quickfix buffer */ (void)do_ecmd(0, NULL, NULL, NULL, ECMD_ONE, ECMD_HIDE, oldwin); /* switch off 'swapfile' */ set_option_value((char_u *)"swf", 0L, NULL, OPT_LOCAL); set_option_value((char_u *)"bt", 0L, (char_u *)"quickfix", OPT_LOCAL); set_option_value((char_u *)"bh", 0L, (char_u *)"wipe", OPT_LOCAL); RESET_BINDING(curwin); #ifdef FEAT_DIFF curwin->w_p_diff = FALSE; #endif #ifdef FEAT_FOLDING set_option_value((char_u *)"fdm", 0L, (char_u *)"manual", OPT_LOCAL); #endif } /* Only set the height when still in the same tab page and there is no * window to the side. */ if (curtab == prevtab #ifdef FEAT_VERTSPLIT && curwin->w_width == Columns #endif ) win_setheight(height); curwin->w_p_wfh = TRUE; /* set 'winfixheight' */ if (win_valid(win)) prevwin = win; } /* * Fill the buffer with the quickfix list. */ qf_fill_buffer(qi); if (qi->qf_lists[qi->qf_curlist].qf_title != NULL) qf_set_title(qi); curwin->w_cursor.lnum = qi->qf_lists[qi->qf_curlist].qf_index; curwin->w_cursor.col = 0; check_cursor(); update_topline(); /* scroll to show the line */ } /* * Return the number of the current entry (line number in the quickfix * window). */ linenr_T qf_current_entry(wp) win_T *wp; { qf_info_T *qi = &ql_info; if (IS_LL_WINDOW(wp)) /* In the location list window, use the referenced location list */ qi = wp->w_llist_ref; return qi->qf_lists[qi->qf_curlist].qf_index; } /* * Update the cursor position in the quickfix window to the current error. * Return TRUE if there is a quickfix window. */ static int qf_win_pos_update(qi, old_qf_index) qf_info_T *qi; int old_qf_index; /* previous qf_index or zero */ { win_T *win; int qf_index = qi->qf_lists[qi->qf_curlist].qf_index; /* * Put the cursor on the current error in the quickfix window, so that * it's viewable. */ win = qf_find_win(qi); if (win != NULL && qf_index <= win->w_buffer->b_ml.ml_line_count && old_qf_index != qf_index) { win_T *old_curwin = curwin; curwin = win; curbuf = win->w_buffer; if (qf_index > old_qf_index) { curwin->w_redraw_top = old_qf_index; curwin->w_redraw_bot = qf_index; } else { curwin->w_redraw_top = qf_index; curwin->w_redraw_bot = old_qf_index; } curwin->w_cursor.lnum = qf_index; curwin->w_cursor.col = 0; update_topline(); /* scroll to show the line */ redraw_later(VALID); curwin->w_redr_status = TRUE; /* update ruler */ curwin = old_curwin; curbuf = curwin->w_buffer; } return win != NULL; } /* * Check whether the given window is displaying the specified quickfix/location * list buffer */ static int is_qf_win(win, qi) win_T *win; qf_info_T *qi; { /* * A window displaying the quickfix buffer will have the w_llist_ref field * set to NULL. * A window displaying a location list buffer will have the w_llist_ref * pointing to the location list. */ if (bt_quickfix(win->w_buffer)) if ((qi == &ql_info && win->w_llist_ref == NULL) || (qi != &ql_info && win->w_llist_ref == qi)) return TRUE; return FALSE; } /* * Find a window displaying the quickfix/location list 'qi' * Searches in only the windows opened in the current tab. */ static win_T * qf_find_win(qi) qf_info_T *qi; { win_T *win; FOR_ALL_WINDOWS(win) if (is_qf_win(win, qi)) break; return win; } /* * Find a quickfix buffer. * Searches in windows opened in all the tabs. */ static buf_T * qf_find_buf(qi) qf_info_T *qi; { tabpage_T *tp; win_T *win; FOR_ALL_TAB_WINDOWS(tp, win) if (is_qf_win(win, qi)) return win->w_buffer; return NULL; } /* * Find the quickfix buffer. If it exists, update the contents. */ static void qf_update_buffer(qi) qf_info_T *qi; { buf_T *buf; win_T *win; win_T *curwin_save; aco_save_T aco; /* Check if a buffer for the quickfix list exists. Update it. */ buf = qf_find_buf(qi); if (buf != NULL) { /* set curwin/curbuf to buf and save a few things */ aucmd_prepbuf(&aco, buf); qf_fill_buffer(qi); if (qi->qf_lists[qi->qf_curlist].qf_title != NULL && (win = qf_find_win(qi)) != NULL) { curwin_save = curwin; curwin = win; qf_set_title(qi); curwin = curwin_save; } /* restore curwin/curbuf and a few other things */ aucmd_restbuf(&aco); (void)qf_win_pos_update(qi, 0); } } static void qf_set_title(qi) qf_info_T *qi; { set_internal_string_var((char_u *)"w:quickfix_title", qi->qf_lists[qi->qf_curlist].qf_title); } /* * Fill current buffer with quickfix errors, replacing any previous contents. * curbuf must be the quickfix buffer! */ static void qf_fill_buffer(qi) qf_info_T *qi; { linenr_T lnum; qfline_T *qfp; buf_T *errbuf; int len; int old_KeyTyped = KeyTyped; /* delete all existing lines */ while ((curbuf->b_ml.ml_flags & ML_EMPTY) == 0) (void)ml_delete((linenr_T)1, FALSE); /* Check if there is anything to display */ if (qi->qf_curlist < qi->qf_listcount) { /* Add one line for each error */ qfp = qi->qf_lists[qi->qf_curlist].qf_start; for (lnum = 0; lnum < qi->qf_lists[qi->qf_curlist].qf_count; ++lnum) { if (qfp->qf_fnum != 0 && (errbuf = buflist_findnr(qfp->qf_fnum)) != NULL && errbuf->b_fname != NULL) { if (qfp->qf_type == 1) /* :helpgrep */ STRCPY(IObuff, gettail(errbuf->b_fname)); else STRCPY(IObuff, errbuf->b_fname); len = (int)STRLEN(IObuff); } else len = 0; IObuff[len++] = '|'; if (qfp->qf_lnum > 0) { sprintf((char *)IObuff + len, "%ld", qfp->qf_lnum); len += (int)STRLEN(IObuff + len); if (qfp->qf_col > 0) { sprintf((char *)IObuff + len, " col %d", qfp->qf_col); len += (int)STRLEN(IObuff + len); } sprintf((char *)IObuff + len, "%s", (char *)qf_types(qfp->qf_type, qfp->qf_nr)); len += (int)STRLEN(IObuff + len); } else if (qfp->qf_pattern != NULL) { qf_fmt_text(qfp->qf_pattern, IObuff + len, IOSIZE - len); len += (int)STRLEN(IObuff + len); } IObuff[len++] = '|'; IObuff[len++] = ' '; /* Remove newlines and leading whitespace from the text. * For an unrecognized line keep the indent, the compiler may * mark a word with ^^^^. */ qf_fmt_text(len > 3 ? skipwhite(qfp->qf_text) : qfp->qf_text, IObuff + len, IOSIZE - len); if (ml_append(lnum, IObuff, (colnr_T)STRLEN(IObuff) + 1, FALSE) == FAIL) break; qfp = qfp->qf_next; } /* Delete the empty line which is now at the end */ (void)ml_delete(lnum + 1, FALSE); } /* correct cursor position */ check_lnums(TRUE); /* Set the 'filetype' to "qf" each time after filling the buffer. This * resembles reading a file into a buffer, it's more logical when using * autocommands. */ set_option_value((char_u *)"ft", 0L, (char_u *)"qf", OPT_LOCAL); curbuf->b_p_ma = FALSE; #ifdef FEAT_AUTOCMD keep_filetype = TRUE; /* don't detect 'filetype' */ apply_autocmds(EVENT_BUFREADPOST, (char_u *)"quickfix", NULL, FALSE, curbuf); apply_autocmds(EVENT_BUFWINENTER, (char_u *)"quickfix", NULL, FALSE, curbuf); keep_filetype = FALSE; #endif /* make sure it will be redrawn */ redraw_curbuf_later(NOT_VALID); /* Restore KeyTyped, setting 'filetype' may reset it. */ KeyTyped = old_KeyTyped; } #endif /* FEAT_WINDOWS */ /* * Return TRUE if "buf" is the quickfix buffer. */ int bt_quickfix(buf) buf_T *buf; { return buf != NULL && buf->b_p_bt[0] == 'q'; } /* * Return TRUE if "buf" is a "nofile" or "acwrite" buffer. * This means the buffer name is not a file name. */ int bt_nofile(buf) buf_T *buf; { return buf != NULL && ((buf->b_p_bt[0] == 'n' && buf->b_p_bt[2] == 'f') || buf->b_p_bt[0] == 'a'); } /* * Return TRUE if "buf" is a "nowrite" or "nofile" buffer. */ int bt_dontwrite(buf) buf_T *buf; { return buf != NULL && buf->b_p_bt[0] == 'n'; } int bt_dontwrite_msg(buf) buf_T *buf; { if (bt_dontwrite(buf)) { EMSG(_("E382: Cannot write, 'buftype' option is set")); return TRUE; } return FALSE; } /* * Return TRUE if the buffer should be hidden, according to 'hidden', ":hide" * and 'bufhidden'. */ int buf_hide(buf) buf_T *buf; { /* 'bufhidden' overrules 'hidden' and ":hide", check it first */ switch (buf->b_p_bh[0]) { case 'u': /* "unload" */ case 'w': /* "wipe" */ case 'd': return FALSE; /* "delete" */ case 'h': return TRUE; /* "hide" */ } return (p_hid || cmdmod.hide); } /* * Return TRUE when using ":vimgrep" for ":grep". */ int grep_internal(cmdidx) cmdidx_T cmdidx; { return ((cmdidx == CMD_grep || cmdidx == CMD_lgrep || cmdidx == CMD_grepadd || cmdidx == CMD_lgrepadd) && STRCMP("internal", *curbuf->b_p_gp == NUL ? p_gp : curbuf->b_p_gp) == 0); } /* * Used for ":make", ":lmake", ":grep", ":lgrep", ":grepadd", and ":lgrepadd" */ void ex_make(eap) exarg_T *eap; { char_u *fname; char_u *cmd; unsigned len; win_T *wp = NULL; qf_info_T *qi = &ql_info; int res; #ifdef FEAT_AUTOCMD char_u *au_name = NULL; /* Redirect ":grep" to ":vimgrep" if 'grepprg' is "internal". */ if (grep_internal(eap->cmdidx)) { ex_vimgrep(eap); return; } switch (eap->cmdidx) { case CMD_make: au_name = (char_u *)"make"; break; case CMD_lmake: au_name = (char_u *)"lmake"; break; case CMD_grep: au_name = (char_u *)"grep"; break; case CMD_lgrep: au_name = (char_u *)"lgrep"; break; case CMD_grepadd: au_name = (char_u *)"grepadd"; break; case CMD_lgrepadd: au_name = (char_u *)"lgrepadd"; break; default: break; } if (au_name != NULL) { apply_autocmds(EVENT_QUICKFIXCMDPRE, au_name, curbuf->b_fname, TRUE, curbuf); # ifdef FEAT_EVAL if (did_throw || force_abort) return; # endif } #endif if (eap->cmdidx == CMD_lmake || eap->cmdidx == CMD_lgrep || eap->cmdidx == CMD_lgrepadd) wp = curwin; autowrite_all(); fname = get_mef_name(); if (fname == NULL) return; mch_remove(fname); /* in case it's not unique */ /* * If 'shellpipe' empty: don't redirect to 'errorfile'. */ len = (unsigned)STRLEN(p_shq) * 2 + (unsigned)STRLEN(eap->arg) + 1; if (*p_sp != NUL) len += (unsigned)STRLEN(p_sp) + (unsigned)STRLEN(fname) + 3; cmd = alloc(len); if (cmd == NULL) return; sprintf((char *)cmd, "%s%s%s", (char *)p_shq, (char *)eap->arg, (char *)p_shq); if (*p_sp != NUL) append_redir(cmd, len, p_sp, fname); /* * Output a newline if there's something else than the :make command that * was typed (in which case the cursor is in column 0). */ if (msg_col == 0) msg_didout = FALSE; msg_start(); MSG_PUTS(":!"); msg_outtrans(cmd); /* show what we are doing */ /* let the shell know if we are redirecting output or not */ do_shell(cmd, *p_sp != NUL ? SHELL_DOOUT : 0); #ifdef AMIGA out_flush(); /* read window status report and redraw before message */ (void)char_avail(); #endif res = qf_init(wp, fname, (eap->cmdidx != CMD_make && eap->cmdidx != CMD_lmake) ? p_gefm : p_efm, (eap->cmdidx != CMD_grepadd && eap->cmdidx != CMD_lgrepadd), *eap->cmdlinep); if (wp != NULL) qi = GET_LOC_LIST(wp); #ifdef FEAT_AUTOCMD if (au_name != NULL) { apply_autocmds(EVENT_QUICKFIXCMDPOST, au_name, curbuf->b_fname, TRUE, curbuf); if (qi->qf_curlist < qi->qf_listcount) res = qi->qf_lists[qi->qf_curlist].qf_count; else res = 0; } #endif if (res > 0 && !eap->forceit) qf_jump(qi, 0, 0, FALSE); /* display first error */ mch_remove(fname); vim_free(fname); vim_free(cmd); } /* * Return the name for the errorfile, in allocated memory. * Find a new unique name when 'makeef' contains "##". * Returns NULL for error. */ static char_u * get_mef_name() { char_u *p; char_u *name; static int start = -1; static int off = 0; #ifdef HAVE_LSTAT struct stat sb; #endif if (*p_mef == NUL) { name = vim_tempname('e'); if (name == NULL) EMSG(_(e_notmp)); return name; } for (p = p_mef; *p; ++p) if (p[0] == '#' && p[1] == '#') break; if (*p == NUL) return vim_strsave(p_mef); /* Keep trying until the name doesn't exist yet. */ for (;;) { if (start == -1) start = mch_get_pid(); else off += 19; name = alloc((unsigned)STRLEN(p_mef) + 30); if (name == NULL) break; STRCPY(name, p_mef); sprintf((char *)name + (p - p_mef), "%d%d", start, off); STRCAT(name, p + 2); if (mch_getperm(name) < 0 #ifdef HAVE_LSTAT /* Don't accept a symbolic link, its a security risk. */ && mch_lstat((char *)name, &sb) < 0 #endif ) break; vim_free(name); } return name; } /* * ":cc", ":crewind", ":cfirst" and ":clast". * ":ll", ":lrewind", ":lfirst" and ":llast". */ void ex_cc(eap) exarg_T *eap; { qf_info_T *qi = &ql_info; if (eap->cmdidx == CMD_ll || eap->cmdidx == CMD_lrewind || eap->cmdidx == CMD_lfirst || eap->cmdidx == CMD_llast) { qi = GET_LOC_LIST(curwin); if (qi == NULL) { EMSG(_(e_loclist)); return; } } qf_jump(qi, 0, eap->addr_count > 0 ? (int)eap->line2 : (eap->cmdidx == CMD_cc || eap->cmdidx == CMD_ll) ? 0 : (eap->cmdidx == CMD_crewind || eap->cmdidx == CMD_lrewind || eap->cmdidx == CMD_cfirst || eap->cmdidx == CMD_lfirst) ? 1 : 32767, eap->forceit); } /* * ":cnext", ":cnfile", ":cNext" and ":cprevious". * ":lnext", ":lNext", ":lprevious", ":lnfile", ":lNfile" and ":lpfile". */ void ex_cnext(eap) exarg_T *eap; { qf_info_T *qi = &ql_info; if (eap->cmdidx == CMD_lnext || eap->cmdidx == CMD_lNext || eap->cmdidx == CMD_lprevious || eap->cmdidx == CMD_lnfile || eap->cmdidx == CMD_lNfile || eap->cmdidx == CMD_lpfile) { qi = GET_LOC_LIST(curwin); if (qi == NULL) { EMSG(_(e_loclist)); return; } } qf_jump(qi, (eap->cmdidx == CMD_cnext || eap->cmdidx == CMD_lnext) ? FORWARD : (eap->cmdidx == CMD_cnfile || eap->cmdidx == CMD_lnfile) ? FORWARD_FILE : (eap->cmdidx == CMD_cpfile || eap->cmdidx == CMD_lpfile || eap->cmdidx == CMD_cNfile || eap->cmdidx == CMD_lNfile) ? BACKWARD_FILE : BACKWARD, eap->addr_count > 0 ? (int)eap->line2 : 1, eap->forceit); } /* * ":cfile"/":cgetfile"/":caddfile" commands. * ":lfile"/":lgetfile"/":laddfile" commands. */ void ex_cfile(eap) exarg_T *eap; { win_T *wp = NULL; qf_info_T *qi = &ql_info; #ifdef FEAT_AUTOCMD char_u *au_name = NULL; #endif if (eap->cmdidx == CMD_lfile || eap->cmdidx == CMD_lgetfile || eap->cmdidx == CMD_laddfile) wp = curwin; #ifdef FEAT_AUTOCMD switch (eap->cmdidx) { case CMD_cfile: au_name = (char_u *)"cfile"; break; case CMD_cgetfile: au_name = (char_u *)"cgetfile"; break; case CMD_caddfile: au_name = (char_u *)"caddfile"; break; case CMD_lfile: au_name = (char_u *)"lfile"; break; case CMD_lgetfile: au_name = (char_u *)"lgetfile"; break; case CMD_laddfile: au_name = (char_u *)"laddfile"; break; default: break; } if (au_name != NULL) apply_autocmds(EVENT_QUICKFIXCMDPRE, au_name, NULL, FALSE, curbuf); #endif #ifdef FEAT_BROWSE if (cmdmod.browse) { char_u *browse_file = do_browse(0, (char_u *)_("Error file"), eap->arg, NULL, NULL, BROWSE_FILTER_ALL_FILES, NULL); if (browse_file == NULL) return; set_string_option_direct((char_u *)"ef", -1, browse_file, OPT_FREE, 0); vim_free(browse_file); } else #endif if (*eap->arg != NUL) set_string_option_direct((char_u *)"ef", -1, eap->arg, OPT_FREE, 0); /* * This function is used by the :cfile, :cgetfile and :caddfile * commands. * :cfile always creates a new quickfix list and jumps to the * first error. * :cgetfile creates a new quickfix list but doesn't jump to the * first error. * :caddfile adds to an existing quickfix list. If there is no * quickfix list then a new list is created. */ if (qf_init(wp, p_ef, p_efm, (eap->cmdidx != CMD_caddfile && eap->cmdidx != CMD_laddfile), *eap->cmdlinep) > 0 && (eap->cmdidx == CMD_cfile || eap->cmdidx == CMD_lfile)) { #ifdef FEAT_AUTOCMD if (au_name != NULL) apply_autocmds(EVENT_QUICKFIXCMDPOST, au_name, NULL, FALSE, curbuf); #endif if (wp != NULL) qi = GET_LOC_LIST(wp); qf_jump(qi, 0, 0, eap->forceit); /* display first error */ } else { #ifdef FEAT_AUTOCMD if (au_name != NULL) apply_autocmds(EVENT_QUICKFIXCMDPOST, au_name, NULL, FALSE, curbuf); #endif } } /* * ":vimgrep {pattern} file(s)" * ":vimgrepadd {pattern} file(s)" * ":lvimgrep {pattern} file(s)" * ":lvimgrepadd {pattern} file(s)" */ void ex_vimgrep(eap) exarg_T *eap; { regmmatch_T regmatch; int fcount; char_u **fnames; char_u *fname; char_u *s; char_u *p; int fi; qf_info_T *qi = &ql_info; qfline_T *prevp = NULL; long lnum; buf_T *buf; int duplicate_name = FALSE; int using_dummy; int redraw_for_dummy = FALSE; int found_match; buf_T *first_match_buf = NULL; time_t seconds = 0; int save_mls; #if defined(FEAT_AUTOCMD) && defined(FEAT_SYN_HL) char_u *save_ei = NULL; #endif aco_save_T aco; int flags = 0; colnr_T col; long tomatch; char_u *dirname_start = NULL; char_u *dirname_now = NULL; char_u *target_dir = NULL; #ifdef FEAT_AUTOCMD char_u *au_name = NULL; switch (eap->cmdidx) { case CMD_vimgrep: au_name = (char_u *)"vimgrep"; break; case CMD_lvimgrep: au_name = (char_u *)"lvimgrep"; break; case CMD_vimgrepadd: au_name = (char_u *)"vimgrepadd"; break; case CMD_lvimgrepadd: au_name = (char_u *)"lvimgrepadd"; break; case CMD_grep: au_name = (char_u *)"grep"; break; case CMD_lgrep: au_name = (char_u *)"lgrep"; break; case CMD_grepadd: au_name = (char_u *)"grepadd"; break; case CMD_lgrepadd: au_name = (char_u *)"lgrepadd"; break; default: break; } if (au_name != NULL) { apply_autocmds(EVENT_QUICKFIXCMDPRE, au_name, curbuf->b_fname, TRUE, curbuf); if (did_throw || force_abort) return; } #endif if (eap->cmdidx == CMD_lgrep || eap->cmdidx == CMD_lvimgrep || eap->cmdidx == CMD_lgrepadd || eap->cmdidx == CMD_lvimgrepadd) { qi = ll_get_or_alloc_list(curwin); if (qi == NULL) return; } if (eap->addr_count > 0) tomatch = eap->line2; else tomatch = MAXLNUM; /* Get the search pattern: either white-separated or enclosed in // */ regmatch.regprog = NULL; p = skip_vimgrep_pat(eap->arg, &s, &flags); if (p == NULL) { EMSG(_(e_invalpat)); goto theend; } regmatch.regprog = vim_regcomp(s, RE_MAGIC); if (regmatch.regprog == NULL) goto theend; regmatch.rmm_ic = p_ic; regmatch.rmm_maxcol = 0; p = skipwhite(p); if (*p == NUL) { EMSG(_("E683: File name missing or invalid pattern")); goto theend; } if ((eap->cmdidx != CMD_grepadd && eap->cmdidx != CMD_lgrepadd && eap->cmdidx != CMD_vimgrepadd && eap->cmdidx != CMD_lvimgrepadd) || qi->qf_curlist == qi->qf_listcount) /* make place for a new list */ qf_new_list(qi, *eap->cmdlinep); else if (qi->qf_lists[qi->qf_curlist].qf_count > 0) /* Adding to existing list, find last entry. */ for (prevp = qi->qf_lists[qi->qf_curlist].qf_start; prevp->qf_next != prevp; prevp = prevp->qf_next) ; /* parse the list of arguments */ if (get_arglist_exp(p, &fcount, &fnames) == FAIL) goto theend; if (fcount == 0) { EMSG(_(e_nomatch)); goto theend; } dirname_start = alloc(MAXPATHL); dirname_now = alloc(MAXPATHL); if (dirname_start == NULL || dirname_now == NULL) goto theend; /* Remember the current directory, because a BufRead autocommand that does * ":lcd %:p:h" changes the meaning of short path names. */ mch_dirname(dirname_start, MAXPATHL); seconds = (time_t)0; for (fi = 0; fi < fcount && !got_int && tomatch > 0; ++fi) { fname = shorten_fname1(fnames[fi]); if (time(NULL) > seconds) { /* Display the file name every second or so, show the user we are * working on it. */ seconds = time(NULL); msg_start(); p = msg_strtrunc(fname, TRUE); if (p == NULL) msg_outtrans(fname); else { msg_outtrans(p); vim_free(p); } msg_clr_eos(); msg_didout = FALSE; /* overwrite this message */ msg_nowait = TRUE; /* don't wait for this message */ msg_col = 0; out_flush(); } buf = buflist_findname_exp(fnames[fi]); if (buf == NULL || buf->b_ml.ml_mfp == NULL) { /* Remember that a buffer with this name already exists. */ duplicate_name = (buf != NULL); using_dummy = TRUE; redraw_for_dummy = TRUE; #if defined(FEAT_AUTOCMD) && defined(FEAT_SYN_HL) /* Don't do Filetype autocommands to avoid loading syntax and * indent scripts, a great speed improvement. */ save_ei = au_event_disable(",Filetype"); #endif /* Don't use modelines here, it's useless. */ save_mls = p_mls; p_mls = 0; /* Load file into a buffer, so that 'fileencoding' is detected, * autocommands applied, etc. */ buf = load_dummy_buffer(fname, dirname_start, dirname_now); p_mls = save_mls; #if defined(FEAT_AUTOCMD) && defined(FEAT_SYN_HL) au_event_restore(save_ei); #endif } else /* Use existing, loaded buffer. */ using_dummy = FALSE; if (buf == NULL) { if (!got_int) smsg((char_u *)_("Cannot open file \"%s\""), fname); } else { /* Try for a match in all lines of the buffer. * For ":1vimgrep" look for first match only. */ found_match = FALSE; for (lnum = 1; lnum <= buf->b_ml.ml_line_count && tomatch > 0; ++lnum) { col = 0; while (vim_regexec_multi(&regmatch, curwin, buf, lnum, col, NULL) > 0) { ; if (qf_add_entry(qi, &prevp, NULL, /* dir */ fname, 0, ml_get_buf(buf, regmatch.startpos[0].lnum + lnum, FALSE), regmatch.startpos[0].lnum + lnum, regmatch.startpos[0].col + 1, FALSE, /* vis_col */ NULL, /* search pattern */ 0, /* nr */ 0, /* type */ TRUE /* valid */ ) == FAIL) { got_int = TRUE; break; } found_match = TRUE; if (--tomatch == 0) break; if ((flags & VGR_GLOBAL) == 0 || regmatch.endpos[0].lnum > 0) break; col = regmatch.endpos[0].col + (col == regmatch.endpos[0].col); if (col > (colnr_T)STRLEN(ml_get_buf(buf, lnum, FALSE))) break; } line_breakcheck(); if (got_int) break; } if (using_dummy) { if (found_match && first_match_buf == NULL) first_match_buf = buf; if (duplicate_name) { /* Never keep a dummy buffer if there is another buffer * with the same name. */ wipe_dummy_buffer(buf, dirname_start); buf = NULL; } else if (!cmdmod.hide || buf->b_p_bh[0] == 'u' /* "unload" */ || buf->b_p_bh[0] == 'w' /* "wipe" */ || buf->b_p_bh[0] == 'd') /* "delete" */ { /* When no match was found we don't need to remember the * buffer, wipe it out. If there was a match and it * wasn't the first one or we won't jump there: only * unload the buffer. * Ignore 'hidden' here, because it may lead to having too * many swap files. */ if (!found_match) { wipe_dummy_buffer(buf, dirname_start); buf = NULL; } else if (buf != first_match_buf || (flags & VGR_NOJUMP)) { unload_dummy_buffer(buf, dirname_start); buf = NULL; } } if (buf != NULL) { /* If the buffer is still loaded we need to use the * directory we jumped to below. */ if (buf == first_match_buf && target_dir == NULL && STRCMP(dirname_start, dirname_now) != 0) target_dir = vim_strsave(dirname_now); /* The buffer is still loaded, the Filetype autocommands * need to be done now, in that buffer. And the modelines * need to be done (again). But not the window-local * options! */ aucmd_prepbuf(&aco, buf); #if defined(FEAT_AUTOCMD) && defined(FEAT_SYN_HL) apply_autocmds(EVENT_FILETYPE, buf->b_p_ft, buf->b_fname, TRUE, buf); #endif do_modelines(OPT_NOWIN); aucmd_restbuf(&aco); } } } } FreeWild(fcount, fnames); qi->qf_lists[qi->qf_curlist].qf_nonevalid = FALSE; qi->qf_lists[qi->qf_curlist].qf_ptr = qi->qf_lists[qi->qf_curlist].qf_start; qi->qf_lists[qi->qf_curlist].qf_index = 1; #ifdef FEAT_WINDOWS qf_update_buffer(qi); #endif #ifdef FEAT_AUTOCMD if (au_name != NULL) apply_autocmds(EVENT_QUICKFIXCMDPOST, au_name, curbuf->b_fname, TRUE, curbuf); #endif /* Jump to first match. */ if (qi->qf_lists[qi->qf_curlist].qf_count > 0) { if ((flags & VGR_NOJUMP) == 0) { buf = curbuf; qf_jump(qi, 0, 0, eap->forceit); if (buf != curbuf) /* If we jumped to another buffer redrawing will already be * taken care of. */ redraw_for_dummy = FALSE; /* Jump to the directory used after loading the buffer. */ if (curbuf == first_match_buf && target_dir != NULL) { exarg_T ea; ea.arg = target_dir; ea.cmdidx = CMD_lcd; ex_cd(&ea); } } } else EMSG2(_(e_nomatch2), s); /* If we loaded a dummy buffer into the current window, the autocommands * may have messed up things, need to redraw and recompute folds. */ if (redraw_for_dummy) { #ifdef FEAT_FOLDING foldUpdateAll(curwin); #else redraw_later(NOT_VALID); #endif } theend: vim_free(dirname_now); vim_free(dirname_start); vim_free(target_dir); vim_free(regmatch.regprog); } /* * Skip over the pattern argument of ":vimgrep /pat/[g][j]". * Put the start of the pattern in "*s", unless "s" is NULL. * If "flags" is not NULL put the flags in it: VGR_GLOBAL, VGR_NOJUMP. * If "s" is not NULL terminate the pattern with a NUL. * Return a pointer to the char just past the pattern plus flags. */ char_u * skip_vimgrep_pat(p, s, flags) char_u *p; char_u **s; int *flags; { int c; if (vim_isIDc(*p)) { /* ":vimgrep pattern fname" */ if (s != NULL) *s = p; p = skiptowhite(p); if (s != NULL && *p != NUL) *p++ = NUL; } else { /* ":vimgrep /pattern/[g][j] fname" */ if (s != NULL) *s = p + 1; c = *p; p = skip_regexp(p + 1, c, TRUE, NULL); if (*p != c) return NULL; /* Truncate the pattern. */ if (s != NULL) *p = NUL; ++p; /* Find the flags */ while (*p == 'g' || *p == 'j') { if (flags != NULL) { if (*p == 'g') *flags |= VGR_GLOBAL; else *flags |= VGR_NOJUMP; } ++p; } } return p; } /* * Restore current working directory to "dirname_start" if they differ, taking * into account whether it is set locally or globally. */ static void restore_start_dir(dirname_start) char_u *dirname_start; { char_u *dirname_now = alloc(MAXPATHL); if (NULL != dirname_now) { mch_dirname(dirname_now, MAXPATHL); if (STRCMP(dirname_start, dirname_now) != 0) { /* If the directory has changed, change it back by building up an * appropriate ex command and executing it. */ exarg_T ea; ea.arg = dirname_start; ea.cmdidx = (curwin->w_localdir == NULL) ? CMD_cd : CMD_lcd; ex_cd(&ea); } } } /* * Load file "fname" into a dummy buffer and return the buffer pointer, * placing the directory resulting from the buffer load into the * "resulting_dir" pointer. "resulting_dir" must be allocated by the caller * prior to calling this function. Restores directory to "dirname_start" prior * to returning, if autocmds or the 'autochdir' option have changed it. * * If creating the dummy buffer does not fail, must call unload_dummy_buffer() * or wipe_dummy_buffer() later! * * Returns NULL if it fails. */ static buf_T * load_dummy_buffer(fname, dirname_start, resulting_dir) char_u *fname; char_u *dirname_start; /* in: old directory */ char_u *resulting_dir; /* out: new directory */ { buf_T *newbuf; buf_T *newbuf_to_wipe = NULL; int failed = TRUE; aco_save_T aco; /* Allocate a buffer without putting it in the buffer list. */ newbuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY); if (newbuf == NULL) return NULL; /* Init the options. */ buf_copy_options(newbuf, BCO_ENTER | BCO_NOHELP); /* need to open the memfile before putting the buffer in a window */ if (ml_open(newbuf) == OK) { /* set curwin/curbuf to buf and save a few things */ aucmd_prepbuf(&aco, newbuf); /* Need to set the filename for autocommands. */ (void)setfname(curbuf, fname, NULL, FALSE); /* Create swap file now to avoid the ATTENTION message. */ check_need_swap(TRUE); /* Remove the "dummy" flag, otherwise autocommands may not * work. */ curbuf->b_flags &= ~BF_DUMMY; if (readfile(fname, NULL, (linenr_T)0, (linenr_T)0, (linenr_T)MAXLNUM, NULL, READ_NEW | READ_DUMMY) == OK && !got_int && !(curbuf->b_flags & BF_NEW)) { failed = FALSE; if (curbuf != newbuf) { /* Bloody autocommands changed the buffer! Can happen when * using netrw and editing a remote file. Use the current * buffer instead, delete the dummy one after restoring the * window stuff. */ newbuf_to_wipe = newbuf; newbuf = curbuf; } } /* restore curwin/curbuf and a few other things */ aucmd_restbuf(&aco); if (newbuf_to_wipe != NULL && buf_valid(newbuf_to_wipe)) wipe_buffer(newbuf_to_wipe, FALSE); } /* * When autocommands/'autochdir' option changed directory: go back. * Let the caller know what the resulting dir was first, in case it is * important. */ mch_dirname(resulting_dir, MAXPATHL); restore_start_dir(dirname_start); if (!buf_valid(newbuf)) return NULL; if (failed) { wipe_dummy_buffer(newbuf, dirname_start); return NULL; } return newbuf; } /* * Wipe out the dummy buffer that load_dummy_buffer() created. Restores * directory to "dirname_start" prior to returning, if autocmds or the * 'autochdir' option have changed it. */ static void wipe_dummy_buffer(buf, dirname_start) buf_T *buf; char_u *dirname_start; { if (curbuf != buf) /* safety check */ { #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL) cleanup_T cs; /* Reset the error/interrupt/exception state here so that aborting() * returns FALSE when wiping out the buffer. Otherwise it doesn't * work when got_int is set. */ enter_cleanup(&cs); #endif wipe_buffer(buf, FALSE); #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL) /* Restore the error/interrupt/exception state if not discarded by a * new aborting error, interrupt, or uncaught exception. */ leave_cleanup(&cs); #endif /* When autocommands/'autochdir' option changed directory: go back. */ restore_start_dir(dirname_start); } } /* * Unload the dummy buffer that load_dummy_buffer() created. Restores * directory to "dirname_start" prior to returning, if autocmds or the * 'autochdir' option have changed it. */ static void unload_dummy_buffer(buf, dirname_start) buf_T *buf; char_u *dirname_start; { if (curbuf != buf) /* safety check */ { close_buffer(NULL, buf, DOBUF_UNLOAD, FALSE); /* When autocommands/'autochdir' option changed directory: go back. */ restore_start_dir(dirname_start); } } #if defined(FEAT_EVAL) || defined(PROTO) /* * Add each quickfix error to list "list" as a dictionary. */ int get_errorlist(wp, list) win_T *wp; list_T *list; { qf_info_T *qi = &ql_info; dict_T *dict; char_u buf[2]; qfline_T *qfp; int i; int bufnum; if (wp != NULL) { qi = GET_LOC_LIST(wp); if (qi == NULL) return FAIL; } if (qi->qf_curlist >= qi->qf_listcount || qi->qf_lists[qi->qf_curlist].qf_count == 0) return FAIL; qfp = qi->qf_lists[qi->qf_curlist].qf_start; for (i = 1; !got_int && i <= qi->qf_lists[qi->qf_curlist].qf_count; ++i) { /* Handle entries with a non-existing buffer number. */ bufnum = qfp->qf_fnum; if (bufnum != 0 && (buflist_findnr(bufnum) == NULL)) bufnum = 0; if ((dict = dict_alloc()) == NULL) return FAIL; if (list_append_dict(list, dict) == FAIL) return FAIL; buf[0] = qfp->qf_type; buf[1] = NUL; if ( dict_add_nr_str(dict, "bufnr", (long)bufnum, NULL) == FAIL || dict_add_nr_str(dict, "lnum", (long)qfp->qf_lnum, NULL) == FAIL || dict_add_nr_str(dict, "col", (long)qfp->qf_col, NULL) == FAIL || dict_add_nr_str(dict, "vcol", (long)qfp->qf_viscol, NULL) == FAIL || dict_add_nr_str(dict, "nr", (long)qfp->qf_nr, NULL) == FAIL || dict_add_nr_str(dict, "pattern", 0L, qfp->qf_pattern == NULL ? (char_u *)"" : qfp->qf_pattern) == FAIL || dict_add_nr_str(dict, "text", 0L, qfp->qf_text == NULL ? (char_u *)"" : qfp->qf_text) == FAIL || dict_add_nr_str(dict, "type", 0L, buf) == FAIL || dict_add_nr_str(dict, "valid", (long)qfp->qf_valid, NULL) == FAIL) return FAIL; qfp = qfp->qf_next; } return OK; } /* * Populate the quickfix list with the items supplied in the list * of dictionaries. "title" will be copied to w:quickfix_title */ int set_errorlist(wp, list, action, title) win_T *wp; list_T *list; int action; char_u *title; { listitem_T *li; dict_T *d; char_u *filename, *pattern, *text, *type; int bufnum; long lnum; int col, nr; int vcol; qfline_T *prevp = NULL; int valid, status; int retval = OK; qf_info_T *qi = &ql_info; int did_bufnr_emsg = FALSE; if (wp != NULL) { qi = ll_get_or_alloc_list(wp); if (qi == NULL) return FAIL; } if (action == ' ' || qi->qf_curlist == qi->qf_listcount) /* make place for a new list */ qf_new_list(qi, title); else if (action == 'a' && qi->qf_lists[qi->qf_curlist].qf_count > 0) /* Adding to existing list, find last entry. */ for (prevp = qi->qf_lists[qi->qf_curlist].qf_start; prevp->qf_next != prevp; prevp = prevp->qf_next) ; else if (action == 'r') qf_free(qi, qi->qf_curlist); for (li = list->lv_first; li != NULL; li = li->li_next) { if (li->li_tv.v_type != VAR_DICT) continue; /* Skip non-dict items */ d = li->li_tv.vval.v_dict; if (d == NULL) continue; filename = get_dict_string(d, (char_u *)"filename", TRUE); bufnum = get_dict_number(d, (char_u *)"bufnr"); lnum = get_dict_number(d, (char_u *)"lnum"); col = get_dict_number(d, (char_u *)"col"); vcol = get_dict_number(d, (char_u *)"vcol"); nr = get_dict_number(d, (char_u *)"nr"); type = get_dict_string(d, (char_u *)"type", TRUE); pattern = get_dict_string(d, (char_u *)"pattern", TRUE); text = get_dict_string(d, (char_u *)"text", TRUE); if (text == NULL) text = vim_strsave((char_u *)""); valid = TRUE; if ((filename == NULL && bufnum == 0) || (lnum == 0 && pattern == NULL)) valid = FALSE; /* Mark entries with non-existing buffer number as not valid. Give the * error message only once. */ if (bufnum != 0 && (buflist_findnr(bufnum) == NULL)) { if (!did_bufnr_emsg) { did_bufnr_emsg = TRUE; EMSGN(_("E92: Buffer %ld not found"), bufnum); } valid = FALSE; bufnum = 0; } status = qf_add_entry(qi, &prevp, NULL, /* dir */ filename, bufnum, text, lnum, col, vcol, /* vis_col */ pattern, /* search pattern */ nr, type == NULL ? NUL : *type, valid); vim_free(filename); vim_free(pattern); vim_free(text); vim_free(type); if (status == FAIL) { retval = FAIL; break; } } if (qi->qf_lists[qi->qf_curlist].qf_index == 0) /* no valid entry */ qi->qf_lists[qi->qf_curlist].qf_nonevalid = TRUE; else qi->qf_lists[qi->qf_curlist].qf_nonevalid = FALSE; qi->qf_lists[qi->qf_curlist].qf_ptr = qi->qf_lists[qi->qf_curlist].qf_start; qi->qf_lists[qi->qf_curlist].qf_index = 1; #ifdef FEAT_WINDOWS qf_update_buffer(qi); #endif return retval; } #endif /* * ":[range]cbuffer [bufnr]" command. * ":[range]caddbuffer [bufnr]" command. * ":[range]cgetbuffer [bufnr]" command. * ":[range]lbuffer [bufnr]" command. * ":[range]laddbuffer [bufnr]" command. * ":[range]lgetbuffer [bufnr]" command. */ void ex_cbuffer(eap) exarg_T *eap; { buf_T *buf = NULL; qf_info_T *qi = &ql_info; if (eap->cmdidx == CMD_lbuffer || eap->cmdidx == CMD_lgetbuffer || eap->cmdidx == CMD_laddbuffer) { qi = ll_get_or_alloc_list(curwin); if (qi == NULL) return; } if (*eap->arg == NUL) buf = curbuf; else if (*skipwhite(skipdigits(eap->arg)) == NUL) buf = buflist_findnr(atoi((char *)eap->arg)); if (buf == NULL) EMSG(_(e_invarg)); else if (buf->b_ml.ml_mfp == NULL) EMSG(_("E681: Buffer is not loaded")); else { if (eap->addr_count == 0) { eap->line1 = 1; eap->line2 = buf->b_ml.ml_line_count; } if (eap->line1 < 1 || eap->line1 > buf->b_ml.ml_line_count || eap->line2 < 1 || eap->line2 > buf->b_ml.ml_line_count) EMSG(_(e_invrange)); else { char_u *qf_title = *eap->cmdlinep; if (buf->b_sfname) { vim_snprintf((char *)IObuff, IOSIZE, "%s (%s)", (char *)qf_title, (char *)buf->b_sfname); qf_title = IObuff; } if (qf_init_ext(qi, NULL, buf, NULL, p_efm, (eap->cmdidx != CMD_caddbuffer && eap->cmdidx != CMD_laddbuffer), eap->line1, eap->line2, qf_title) > 0 && (eap->cmdidx == CMD_cbuffer || eap->cmdidx == CMD_lbuffer)) qf_jump(qi, 0, 0, eap->forceit); /* display first error */ } } } #if defined(FEAT_EVAL) || defined(PROTO) /* * ":cexpr {expr}", ":cgetexpr {expr}", ":caddexpr {expr}" command. * ":lexpr {expr}", ":lgetexpr {expr}", ":laddexpr {expr}" command. */ void ex_cexpr(eap) exarg_T *eap; { typval_T *tv; qf_info_T *qi = &ql_info; if (eap->cmdidx == CMD_lexpr || eap->cmdidx == CMD_lgetexpr || eap->cmdidx == CMD_laddexpr) { qi = ll_get_or_alloc_list(curwin); if (qi == NULL) return; } /* Evaluate the expression. When the result is a string or a list we can * use it to fill the errorlist. */ tv = eval_expr(eap->arg, NULL); if (tv != NULL) { if ((tv->v_type == VAR_STRING && tv->vval.v_string != NULL) || (tv->v_type == VAR_LIST && tv->vval.v_list != NULL)) { if (qf_init_ext(qi, NULL, NULL, tv, p_efm, (eap->cmdidx != CMD_caddexpr && eap->cmdidx != CMD_laddexpr), (linenr_T)0, (linenr_T)0, *eap->cmdlinep) > 0 && (eap->cmdidx == CMD_cexpr || eap->cmdidx == CMD_lexpr)) qf_jump(qi, 0, 0, eap->forceit); /* display first error */ } else EMSG(_("E777: String or List expected")); free_tv(tv); } } #endif /* * ":helpgrep {pattern}" */ void ex_helpgrep(eap) exarg_T *eap; { regmatch_T regmatch; char_u *save_cpo; char_u *p; int fcount; char_u **fnames; FILE *fd; int fi; qfline_T *prevp = NULL; long lnum; #ifdef FEAT_MULTI_LANG char_u *lang; #endif qf_info_T *qi = &ql_info; int new_qi = FALSE; win_T *wp; #ifdef FEAT_AUTOCMD char_u *au_name = NULL; #endif #ifdef FEAT_MULTI_LANG /* Check for a specified language */ lang = check_help_lang(eap->arg); #endif #ifdef FEAT_AUTOCMD switch (eap->cmdidx) { case CMD_helpgrep: au_name = (char_u *)"helpgrep"; break; case CMD_lhelpgrep: au_name = (char_u *)"lhelpgrep"; break; default: break; } if (au_name != NULL) { apply_autocmds(EVENT_QUICKFIXCMDPRE, au_name, curbuf->b_fname, TRUE, curbuf); if (did_throw || force_abort) return; } #endif /* Make 'cpoptions' empty, the 'l' flag should not be used here. */ save_cpo = p_cpo; p_cpo = empty_option; if (eap->cmdidx == CMD_lhelpgrep) { /* Find an existing help window */ FOR_ALL_WINDOWS(wp) if (wp->w_buffer != NULL && wp->w_buffer->b_help) break; if (wp == NULL) /* Help window not found */ qi = NULL; else qi = wp->w_llist; if (qi == NULL) { /* Allocate a new location list for help text matches */ if ((qi = ll_new_list()) == NULL) return; new_qi = TRUE; } } regmatch.regprog = vim_regcomp(eap->arg, RE_MAGIC + RE_STRING); regmatch.rm_ic = FALSE; if (regmatch.regprog != NULL) { #ifdef FEAT_MBYTE vimconv_T vc; /* Help files are in utf-8 or latin1, convert lines when 'encoding' * differs. */ vc.vc_type = CONV_NONE; if (!enc_utf8) convert_setup(&vc, (char_u *)"utf-8", p_enc); #endif /* create a new quickfix list */ qf_new_list(qi, *eap->cmdlinep); /* Go through all directories in 'runtimepath' */ p = p_rtp; while (*p != NUL && !got_int) { copy_option_part(&p, NameBuff, MAXPATHL, ","); /* Find all "*.txt" and "*.??x" files in the "doc" directory. */ add_pathsep(NameBuff); STRCAT(NameBuff, "doc/*.\\(txt\\|??x\\)"); if (gen_expand_wildcards(1, &NameBuff, &fcount, &fnames, EW_FILE|EW_SILENT) == OK && fcount > 0) { for (fi = 0; fi < fcount && !got_int; ++fi) { #ifdef FEAT_MULTI_LANG /* Skip files for a different language. */ if (lang != NULL && STRNICMP(lang, fnames[fi] + STRLEN(fnames[fi]) - 3, 2) != 0 && !(STRNICMP(lang, "en", 2) == 0 && STRNICMP("txt", fnames[fi] + STRLEN(fnames[fi]) - 3, 3) == 0)) continue; #endif fd = mch_fopen((char *)fnames[fi], "r"); if (fd != NULL) { lnum = 1; while (!vim_fgets(IObuff, IOSIZE, fd) && !got_int) { char_u *line = IObuff; #ifdef FEAT_MBYTE /* Convert a line if 'encoding' is not utf-8 and * the line contains a non-ASCII character. */ if (vc.vc_type != CONV_NONE && has_non_ascii(IObuff)) { line = string_convert(&vc, IObuff, NULL); if (line == NULL) line = IObuff; } #endif if (vim_regexec(&regmatch, line, (colnr_T)0)) { int l = (int)STRLEN(line); /* remove trailing CR, LF, spaces, etc. */ while (l > 0 && line[l - 1] <= ' ') line[--l] = NUL; if (qf_add_entry(qi, &prevp, NULL, /* dir */ fnames[fi], 0, line, lnum, (int)(regmatch.startp[0] - line) + 1, /* col */ FALSE, /* vis_col */ NULL, /* search pattern */ 0, /* nr */ 1, /* type */ TRUE /* valid */ ) == FAIL) { got_int = TRUE; #ifdef FEAT_MBYTE if (line != IObuff) vim_free(line); #endif break; } } #ifdef FEAT_MBYTE if (line != IObuff) vim_free(line); #endif ++lnum; line_breakcheck(); } fclose(fd); } } FreeWild(fcount, fnames); } } vim_free(regmatch.regprog); #ifdef FEAT_MBYTE if (vc.vc_type != CONV_NONE) convert_setup(&vc, NULL, NULL); #endif qi->qf_lists[qi->qf_curlist].qf_nonevalid = FALSE; qi->qf_lists[qi->qf_curlist].qf_ptr = qi->qf_lists[qi->qf_curlist].qf_start; qi->qf_lists[qi->qf_curlist].qf_index = 1; } if (p_cpo == empty_option) p_cpo = save_cpo; else /* Darn, some plugin changed the value. */ free_string_option(save_cpo); #ifdef FEAT_WINDOWS qf_update_buffer(qi); #endif #ifdef FEAT_AUTOCMD if (au_name != NULL) { apply_autocmds(EVENT_QUICKFIXCMDPOST, au_name, curbuf->b_fname, TRUE, curbuf); if (!new_qi && qi != &ql_info && qf_find_buf(qi) == NULL) /* autocommands made "qi" invalid */ return; } #endif /* Jump to first match. */ if (qi->qf_lists[qi->qf_curlist].qf_count > 0) qf_jump(qi, 0, 0, FALSE); else EMSG2(_(e_nomatch2), eap->arg); if (eap->cmdidx == CMD_lhelpgrep) { /* If the help window is not opened or if it already points to the * correct location list, then free the new location list. */ if (!curwin->w_buffer->b_help || curwin->w_llist == qi) { if (new_qi) ll_free_all(&qi); } else if (curwin->w_llist == NULL) curwin->w_llist = qi; } } #endif /* FEAT_QUICKFIX */
zyz2011-vim
src/quickfix.c
C
gpl2
104,190
# Makefile for Vim on Win32 (Windows NT/2000/XP/2003 and Windows 95/98/Me) # and Win64, using the Microsoft Visual C++ compilers. Known to work with # VC5, VC6 (VS98), VC7.0 (VS2002), VC7.1 (VS2003), VC8 (VS2005), # VC9 (VS2008), and VC10 (VS2010). # # To build using other Windows compilers, see INSTALLpc.txt # # This makefile can build the console, GUI, OLE-enable, Perl-enabled and # Python-enabled versions of Vim for Win32 platforms. # # The basic command line to build Vim is: # # nmake -f Make_mvc.mak # # This will build the console version of Vim with no additional interfaces. # To add features, define any of the following: # # !!!! After changing features do "nmake clean" first !!!! # # Feature Set: FEATURES=[TINY, SMALL, NORMAL, BIG, HUGE] (default is BIG) # # GUI interface: GUI=yes (default is no) # # OLE interface: OLE=yes (usually with GUI=yes) # # Multibyte support: MBYTE=yes (default is no) # # IME support: IME=yes (requires GUI=yes) # DYNAMIC_IME=[yes or no] (to load the imm32.dll dynamically, default # is yes) # Global IME support: GIME=yes (requires GUI=yes) # # Lua interface: # LUA=[Path to Lua directory] # DYNAMIC_LUA=yes (to load the Lua DLL dynamically) # LUA_VER=[Lua version] (default is 51) # # MzScheme interface: # MZSCHEME=[Path to MzScheme directory] # DYNAMIC_MZSCHEME=yes (to load the MzScheme DLLs dynamically) # MZSCHEME_VER=[version, 205_000, ...] # MZSCHEME_DEBUG=no # # Perl interface: # PERL=[Path to Perl directory] # DYNAMIC_PERL=yes (to load the Perl DLL dynamically) # PERL_VER=[Perl version, in the form 55 (5.005), 56 (5.6.x), etc] # (default is 56) # # Python interface: # PYTHON=[Path to Python directory] # DYNAMIC_PYTHON=yes (to load the Python DLL dynamically) # PYTHON_VER=[Python version, eg 15, 20] (default is 22) # # Python3 interface: # PYTHON3=[Path to Python3 directory] # DYNAMIC_PYTHON3=yes (to load the Python3 DLL dynamically) # PYTHON3_VER=[Python3 version, eg 30, 31] (default is 31) # # Ruby interface: # RUBY=[Path to Ruby directory] # DYNAMIC_RUBY=yes (to load the Ruby DLL dynamically) # RUBY_VER=[Ruby version, eg 16, 17] (default is 18) # RUBY_VER_LONG=[Ruby version, eg 1.6, 1.7] (default is 1.8) # You must set RUBY_VER_LONG when change RUBY_VER. # # Tcl interface: # TCL=[Path to Tcl directory] # DYNAMIC_TCL=yes (to load the Tcl DLL dynamically) # TCL_VER=[Tcl version, e.g. 80, 83] (default is 83) # TCL_VER_LONG=[Tcl version, eg 8.3] (default is 8.3) # You must set TCL_VER_LONG when you set TCL_VER. # # SNiFF+ interface: SNIFF=yes # # Cscope support: CSCOPE=yes # # Iconv library support (always dynamically loaded): # ICONV=[yes or no] (default is yes) # # Intl library support (always dynamically loaded): # GETTEXT=[yes or no] (default is yes) # See http://sourceforge.net/projects/gettext/ # # PostScript printing: POSTSCRIPT=yes (default is no) # # Netbeans Support: NETBEANS=[yes or no] (default is yes if GUI is yes) # # XPM Image Support: XPM=[path to XPM directory] # # Optimization: OPTIMIZE=[SPACE, SPEED, MAXSPEED] (default is MAXSPEED) # # Processor Version: CPUNR=[i386, i486, i586, i686, pentium4] (default is # i386) # # Version Support: WINVER=[0x0400, 0x0500] (default is 0x0400) # # Debug version: DEBUG=yes # Mapfile: MAP=[no, yes or lines] (default is yes) # no: Don't write a mapfile. # yes: Write a normal mapfile. # lines: Write a mapfile with line numbers (only for VC6 and later) # # Netbeans Debugging Support: NBDEBUG=[yes or no] (should be no, yes # doesn't work) # # Visual C Version: MSVCVER=m.n (default derived from nmake if undefined) # # You can combine any of these interfaces # # Example: To build the non-debug, GUI version with Perl interface: # nmake -f Make_mvc.mak GUI=yes PERL=C:\Perl # # DEBUG with Make_mvc.mak and Make_dvc.mak: # This makefile gives a fineness of control which is not supported in # Visual C++ configuration files. Therefore, debugging requires a bit of # extra work. # Make_dvc.mak is a Visual C++ project to access that support. It may be # badly out of date for the Visual C++ you are using... # To use Make_dvc.mak: # 1) Build Vim with Make_mvc.mak. # Use a "DEBUG=yes" argument to build Vim with debug support. # E.g. the following builds gvimd.exe: # nmake -f Make_mvc.mak debug=yes gui=yes # 2) Use MS Devstudio and set it up to allow that file to be debugged: # i) Pass Make_dvc.mak to the IDE. # Use the "open workspace" menu entry to load Make_dvc.mak. # Alternatively, from the command line: # msdev /nologo Make_dvc.mak # Note: Make_dvc.mak is in VC4.0 format. Later VC versions see # this and offer to convert it to their own format. Accept that. # It creates a file called Make_dvc.dsw which can then be used # for further operations. E.g. # msdev /nologo Make_dvc.dsw # ii) Set the built executable for debugging: # a) Alt+F7/Debug takes you to the Debug dialog. # b) Fill "Executable for debug session". e.g. gvimd.exe # c) Fill "Program arguments". e.g. -R dosinst.c # d) Complete the dialog # 3) You can now debug the executable you built with Make_mvc.mak # # Note: Make_dvc.mak builds vimrun.exe, because it must build something # to be a valid makefile.. ### See feature.h for a list of optionals. # If you want to build some optional features without modifying the source, # you can set DEFINES on the command line, e.g., # nmake -f Make_mvc.mvc "DEFINES=-DEMACS_TAGS" # Build on both Windows NT/XP and Windows 9x TARGETOS = BOTH # Select one of eight object code directories, depends on GUI, OLE, DEBUG and # interfaces. # If you change something else, do "make clean" first! !if "$(GUI)" == "yes" OBJDIR = .\ObjG !else OBJDIR = .\ObjC !endif !if "$(OLE)" == "yes" OBJDIR = $(OBJDIR)O !endif !ifdef LUA OBJDIR = $(OBJDIR)U !endif !ifdef PERL OBJDIR = $(OBJDIR)L !endif !ifdef PYTHON OBJDIR = $(OBJDIR)Y !endif !ifdef PYTHON3 OBJDIR = $(OBJDIR)H !endif !ifdef TCL OBJDIR = $(OBJDIR)T !endif !ifdef RUBY OBJDIR = $(OBJDIR)R !endif !ifdef MZSCHEME OBJDIR = $(OBJDIR)Z !endif !if "$(DEBUG)" == "yes" OBJDIR = $(OBJDIR)d !endif # Win32.mak requires that CPU be set appropriately. # To cross-compile for Win64, set CPU=AMD64 or CPU=IA64. !ifdef PROCESSOR_ARCHITECTURE # We're on Windows NT or using VC 6+ ! ifdef CPU ASSEMBLY_ARCHITECTURE=$(CPU) # Using I386 for $ASSEMBLY_ARCHITECTURE doesn't work for VC7. ! if ("$(ASSEMBLY_ARCHITECTURE)" == "i386") || ("$(ASSEMBLY_ARCHITECTURE)" == "I386") ASSEMBLY_ARCHITECTURE = x86 ! endif ! else CPU = $(PROCESSOR_ARCHITECTURE) ASSEMBLY_ARCHITECTURE = $(PROCESSOR_ARCHITECTURE) ! if ("$(CPU)" == "x86") || ("$(CPU)" == "X86") CPU = i386 ! endif ! endif !else # !PROCESSOR_ARCHITECTURE # We're on Windows 95 CPU = i386 !endif # !PROCESSOR_ARCHITECTURE # Build a retail version by default !if "$(DEBUG)" != "yes" NODEBUG = 1 !else !undef NODEBUG MAKEFLAGS_GVIMEXT = DEBUG=yes !endif # Get all sorts of useful, standard macros from the Platform SDK. !include <Win32.mak> # Flag to turn on Win64 compatibility warnings for VC7.x and VC8. WP64CHECK = /Wp64 #>>>>> path of the compiler and linker; name of include and lib directories # PATH = c:\msvc20\bin;$(PATH) # INCLUDE = c:\msvc20\include # LIB = c:\msvc20\lib !ifndef CTAGS CTAGS = ctags !endif !if "$(SNIFF)" == "yes" # SNIFF - Include support for SNiFF+. SNIFF_INCL = if_sniff.h SNIFF_OBJ = $(OBJDIR)/if_sniff.obj SNIFF_LIB = shell32.lib SNIFF_DEFS = -DFEAT_SNIFF # The SNiFF integration needs multithreaded libraries! MULTITHREADED = yes !endif !ifndef CSCOPE CSCOPE = yes !endif !if "$(CSCOPE)" == "yes" # CSCOPE - Include support for Cscope CSCOPE_INCL = if_cscope.h CSCOPE_OBJ = $(OBJDIR)/if_cscope.obj CSCOPE_DEFS = -DFEAT_CSCOPE !endif !ifndef NETBEANS NETBEANS = $(GUI) !endif # Only allow NETBEANS and XPM for a GUI build. !if "$(GUI)" == "yes" !if "$(NETBEANS)" == "yes" # NETBEANS - Include support for Netbeans integration NETBEANS_PRO = proto/netbeans.pro NETBEANS_OBJ = $(OBJDIR)/netbeans.obj NETBEANS_DEFS = -DFEAT_NETBEANS_INTG !if "$(NBDEBUG)" == "yes" NBDEBUG_DEFS = -DNBDEBUG NBDEBUG_INCL = nbdebug.h NBDEBUG_SRC = nbdebug.c !endif NETBEANS_LIB = WSock32.lib !endif !ifdef XPM # XPM - Include support for XPM signs # you can get xpm.lib from http://iamphet.nm.ru/xpm or create it yourself XPM_OBJ = $(OBJDIR)/xpm_w32.obj XPM_DEFS = -DFEAT_XPM_W32 XPM_LIB = $(XPM)\lib\libXpm.lib XPM_INC = -I $(XPM)\include !endif !endif # Set which version of the CRT to use !if defined(USE_MSVCRT) # CVARS = $(cvarsdll) # !elseif defined(MULTITHREADED) # CVARS = $(cvarsmt) !else # CVARS = $(cvars) # CVARS = $(cvarsmt) !endif # need advapi32.lib for GetUserName() # need shell32.lib for ExtractIcon() # gdi32.lib and comdlg32.lib for printing support # ole32.lib and uuid.lib are needed for FEAT_SHORTCUT CON_LIB = oldnames.lib kernel32.lib advapi32.lib shell32.lib gdi32.lib \ comdlg32.lib ole32.lib uuid.lib /machine:$(CPU) /nodefaultlib !if "$(DELAYLOAD)" == "yes" CON_LIB = $(CON_LIB) /DELAYLOAD:comdlg32.dll /DELAYLOAD:ole32.dll DelayImp.lib !endif ### Set the default $(WINVER) to make it work with VC++7.0 (VS.NET) # When set to 0x0500 ":browse" stops working. !ifndef WINVER WINVER = 0x0400 !endif # If you have a fixed directory for $VIM or $VIMRUNTIME, other than the normal # default, use these lines. #VIMRCLOC = somewhere #VIMRUNTIMEDIR = somewhere CFLAGS = -c /W3 /nologo $(CVARS) -I. -Iproto -DHAVE_PATHDEF -DWIN32 \ $(SNIFF_DEFS) $(CSCOPE_DEFS) $(NETBEANS_DEFS) \ $(NBDEBUG_DEFS) $(XPM_DEFS) \ $(DEFINES) -DWINVER=$(WINVER) -D_WIN32_WINNT=$(WINVER) \ /Fo$(OUTDIR)/ #>>>>> end of choices ########################################################################### !ifdef OS OS_TYPE = winnt DEL_TREE = rmdir /s /q !else OS_TYPE = win95 DEL_TREE = deltree /y !endif INTDIR=$(OBJDIR) OUTDIR=$(OBJDIR) # Derive version of VC being used from nmake if not specified !if "$(MSVCVER)" == "" !if "$(_NMAKE_VER)" == "" MSVCVER = 4.0 !endif !if "$(_NMAKE_VER)" == "162" MSVCVER = 5.0 !endif !if "$(_NMAKE_VER)" == "6.00.8168.0" MSVCVER = 6.0 CPU = ix86 !endif !if "$(_NMAKE_VER)" == "7.00.9466" MSVCVER = 7.0 !endif !if "$(_NMAKE_VER)" == "7.10.3077" MSVCVER = 7.1 !endif !if "$(_NMAKE_VER)" == "8.00.50727.42" MSVCVER = 8.0 !endif !if "$(_NMAKE_VER)" == "8.00.50727.762" MSVCVER = 8.0 !endif !if "$(_NMAKE_VER)" == "9.00.20706.01" MSVCVER = 9.0 !endif !if "$(_NMAKE_VER)" == "9.00.21022.08" MSVCVER = 9.0 !endif !if "$(_NMAKE_VER)" == "9.00.30729.01" MSVCVER = 9.0 !endif !if "$(_NMAKE_VER)" == "10.00.20506.01" MSVCVER = 10.0 !endif !if "$(_NMAKE_VER)" == "10.00.30128.01" MSVCVER = 10.0 !endif !if "$(_NMAKE_VER)" == "10.00.30319.01" MSVCVER = 10.0 !endif !endif # Abort bulding VIM if version of VC is unrecognised. !ifndef MSVCVER !message *** ERROR !message Cannot determine Visual C version being used. If you are using the !message Windows SDK then you must have the environment variable MSVCVER set to !message your version of the VC compiler. If you are not using the Express !message version of Visual C, you can either set MSVCVER or update this makefile !message to handle the new value for _NMAKE_VER, "$(_NMAKE_VER)". !error Make aborted. !endif # Convert processor ID to MVC-compatible number !if ("$(MSVCVER)" != "8.0") && ("$(MSVCVER)" != "9.0") && ("$(MSVCVER)" != "10.0") !if "$(CPUNR)" == "i386" CPUARG = /G3 !elseif "$(CPUNR)" == "i486" CPUARG = /G4 !elseif "$(CPUNR)" == "i586" CPUARG = /G5 !elseif "$(CPUNR)" == "i686" CPUARG = /G6 !elseif "$(CPUNR)" == "pentium4" CPUARG = /G7 /arch:SSE2 !else CPUARG = !endif !else # VC8/9/10 only allows specifying SSE architecture but only for 32bit !if "$(ASSEMBLY_ARCHITECTURE)" == "x86" && "$(CPUNR)" == "pentium4" CPUARG = /arch:SSE2 !endif !endif LIBC = DEBUGINFO = /Zi !ifdef NODEBUG VIM = vim !if "$(OPTIMIZE)" == "SPACE" OPTFLAG = /O1 !elseif "$(OPTIMIZE)" == "SPEED" OPTFLAG = /O2 !else # MAXSPEED OPTFLAG = /Ox !endif !if ("$(MSVCVER)" == "8.0") || ("$(MSVCVER)" == "9.0") || ("$(MSVCVER)" == "10.0") # Use link time code generation if not worried about size !if "$(OPTIMIZE)" != "SPACE" OPTFLAG = $(OPTFLAG) /GL !endif !endif # (/Wp64 is deprecated in VC9 and generates an obnoxious warning.) !if ("$(MSVCVER)" == "7.0") || ("$(MSVCVER)" == "7.1") || ("$(MSVCVER)" == "8.0") CFLAGS=$(CFLAGS) $(WP64CHECK) !endif CFLAGS = $(CFLAGS) $(OPTFLAG) -DNDEBUG $(CPUARG) RCFLAGS = $(rcflags) $(rcvars) -DNDEBUG ! ifdef USE_MSVCRT CFLAGS = $(CFLAGS) /MD LIBC = msvcrt.lib ! else LIBC = libcmt.lib CFLAGS = $(CFLAGS) /Zl /MT ! endif !else # DEBUG VIM = vimd ! if ("$(CPU)" == "i386") || ("$(CPU)" == "ix86") DEBUGINFO = /ZI ! endif CFLAGS = $(CFLAGS) -D_DEBUG -DDEBUG /Od RCFLAGS = $(rcflags) $(rcvars) -D_DEBUG -DDEBUG # The /fixed:no is needed for Quantify. Assume not 4.? as unsupported in VC4.0. ! if "$(MSVCVER)" == "4.0" LIBC = ! else LIBC = /fixed:no ! endif ! ifdef USE_MSVCRT CFLAGS = $(CFLAGS) /MDd LIBC = $(LIBC) msvcrtd.lib ! else LIBC = $(LIBC) libcmtd.lib CFLAGS = $(CFLAGS) /Zl /MTd ! endif !endif # DEBUG INCL = vim.h os_win32.h ascii.h feature.h globals.h keymap.h macros.h \ proto.h option.h structs.h term.h $(SNIFF_INCL) $(CSCOPE_INCL) \ $(NBDEBUG_INCL) OBJ = \ $(OUTDIR)\blowfish.obj \ $(OUTDIR)\buffer.obj \ $(OUTDIR)\charset.obj \ $(OUTDIR)\diff.obj \ $(OUTDIR)\digraph.obj \ $(OUTDIR)\edit.obj \ $(OUTDIR)\eval.obj \ $(OUTDIR)\ex_cmds.obj \ $(OUTDIR)\ex_cmds2.obj \ $(OUTDIR)\ex_docmd.obj \ $(OUTDIR)\ex_eval.obj \ $(OUTDIR)\ex_getln.obj \ $(OUTDIR)\fileio.obj \ $(OUTDIR)\fold.obj \ $(OUTDIR)\getchar.obj \ $(OUTDIR)\hardcopy.obj \ $(OUTDIR)\hashtab.obj \ $(OUTDIR)\main.obj \ $(OUTDIR)\mark.obj \ $(OUTDIR)\mbyte.obj \ $(OUTDIR)\memfile.obj \ $(OUTDIR)\memline.obj \ $(OUTDIR)\menu.obj \ $(OUTDIR)\message.obj \ $(OUTDIR)\misc1.obj \ $(OUTDIR)\misc2.obj \ $(OUTDIR)\move.obj \ $(OUTDIR)\normal.obj \ $(OUTDIR)\ops.obj \ $(OUTDIR)\option.obj \ $(OUTDIR)\os_mswin.obj \ $(OUTDIR)\os_win32.obj \ $(OUTDIR)\pathdef.obj \ $(OUTDIR)\popupmnu.obj \ $(OUTDIR)\quickfix.obj \ $(OUTDIR)\regexp.obj \ $(OUTDIR)\screen.obj \ $(OUTDIR)\search.obj \ $(OUTDIR)\sha256.obj \ $(OUTDIR)\spell.obj \ $(OUTDIR)\syntax.obj \ $(OUTDIR)\tag.obj \ $(OUTDIR)\term.obj \ $(OUTDIR)\ui.obj \ $(OUTDIR)\undo.obj \ $(OUTDIR)\window.obj \ $(OUTDIR)\vim.res !if "$(OLE)" == "yes" CFLAGS = $(CFLAGS) -DFEAT_OLE RCFLAGS = $(RCFLAGS) -DFEAT_OLE OLE_OBJ = $(OUTDIR)\if_ole.obj OLE_IDL = if_ole.idl OLE_LIB = oleaut32.lib !endif !if "$(IME)" == "yes" CFLAGS = $(CFLAGS) -DFEAT_MBYTE_IME !ifndef DYNAMIC_IME DYNAMIC_IME = yes !endif !if "$(DYNAMIC_IME)" == "yes" CFLAGS = $(CFLAGS) -DDYNAMIC_IME !else IME_LIB = imm32.lib !endif !endif !if "$(GIME)" == "yes" CFLAGS = $(CFLAGS) -DGLOBAL_IME OBJ = $(OBJ) $(OUTDIR)\dimm_i.obj $(OUTDIR)\glbl_ime.obj MBYTE = yes !endif !if "$(MBYTE)" == "yes" CFLAGS = $(CFLAGS) -DFEAT_MBYTE !endif !if "$(GUI)" == "yes" SUBSYSTEM = windows CFLAGS = $(CFLAGS) -DFEAT_GUI_W32 RCFLAGS = $(RCFLAGS) -DFEAT_GUI_W32 VIM = g$(VIM) GUI_INCL = \ gui.h \ regexp.h \ ascii.h \ ex_cmds.h \ farsi.h \ feature.h \ globals.h \ gui_beval.h \ keymap.h \ macros.h \ option.h \ os_dos.h \ os_win32.h GUI_OBJ = \ $(OUTDIR)\gui.obj \ $(OUTDIR)\gui_beval.obj \ $(OUTDIR)\gui_w32.obj \ $(OUTDIR)\os_w32exe.obj GUI_LIB = \ gdi32.lib version.lib $(IME_LIB) \ winspool.lib comctl32.lib advapi32.lib shell32.lib \ /machine:$(CPU) /nodefaultlib !else SUBSYSTEM = console !endif # iconv.dll library (dynamically loaded) !ifndef ICONV ICONV = yes !endif !if "$(ICONV)" == "yes" CFLAGS = $(CFLAGS) -DDYNAMIC_ICONV !endif # libintl.dll library !ifndef GETTEXT GETTEXT = yes !endif !if "$(GETTEXT)" == "yes" CFLAGS = $(CFLAGS) -DDYNAMIC_GETTEXT !endif # TCL interface !ifdef TCL !ifndef TCL_VER TCL_VER = 83 TCL_VER_LONG = 8.3 !endif !message Tcl requested (version $(TCL_VER)) - root dir is "$(TCL)" !if "$(DYNAMIC_TCL)" == "yes" !message Tcl DLL will be loaded dynamically TCL_DLL = tcl$(TCL_VER).dll CFLAGS = $(CFLAGS) -DFEAT_TCL -DDYNAMIC_TCL -DDYNAMIC_TCL_DLL=\"$(TCL_DLL)\" \ -DDYNAMIC_TCL_VER=\"$(TCL_VER_LONG)\" TCL_OBJ = $(OUTDIR)\if_tcl.obj TCL_INC = /I "$(TCL)\Include" /I "$(TCL)" TCL_LIB = "$(TCL)\lib\tclstub$(TCL_VER).lib" !else CFLAGS = $(CFLAGS) -DFEAT_TCL TCL_OBJ = $(OUTDIR)\if_tcl.obj TCL_INC = /I "$(TCL)\Include" /I "$(TCL)" TCL_LIB = $(TCL)\lib\tcl$(TCL_VER)vc.lib !endif !endif # Lua interface !ifdef LUA !ifndef LUA_VER LUA_VER = 51 !endif !message Lua requested (version $(LUA_VER)) - root dir is "$(LUA)" !if "$(DYNAMIC_LUA)" == "yes" !message Lua DLL will be loaded dynamically !endif CFLAGS = $(CFLAGS) -DFEAT_LUA LUA_OBJ = $(OUTDIR)\if_lua.obj LUA_INC = /I "$(LUA)\include" /I "$(LUA)" !if "$(DYNAMIC_LUA)" == "yes" CFLAGS = $(CFLAGS) -DDYNAMIC_LUA \ -DDYNAMIC_LUA_DLL=\"lua$(LUA_VER).dll\" LUA_LIB = /nodefaultlib:lua$(LUA_VER).lib !else LUA_LIB = "$(LUA)\lib\lua$(LUA_VER).lib" !endif !endif !ifdef PYTHON !ifdef PYTHON3 DYNAMIC_PYTHON=yes DYNAMIC_PYTHON3=yes !endif !endif # PYTHON interface !ifdef PYTHON !ifndef PYTHON_VER PYTHON_VER = 22 !endif !message Python requested (version $(PYTHON_VER)) - root dir is "$(PYTHON)" !if "$(DYNAMIC_PYTHON)" == "yes" !message Python DLL will be loaded dynamically !endif CFLAGS = $(CFLAGS) -DFEAT_PYTHON PYTHON_OBJ = $(OUTDIR)\if_python.obj PYTHON_INC = /I "$(PYTHON)\Include" /I "$(PYTHON)\PC" !if "$(DYNAMIC_PYTHON)" == "yes" CFLAGS = $(CFLAGS) -DDYNAMIC_PYTHON \ -DDYNAMIC_PYTHON_DLL=\"python$(PYTHON_VER).dll\" PYTHON_LIB = /nodefaultlib:python$(PYTHON_VER).lib !else PYTHON_LIB = $(PYTHON)\libs\python$(PYTHON_VER).lib !endif !endif # PYTHON3 interface !ifdef PYTHON3 !ifndef PYTHON3_VER PYTHON3_VER = 31 !endif !message Python3 requested (version $(PYTHON3_VER)) - root dir is "$(PYTHON3)" !if "$(DYNAMIC_PYTHON3)" == "yes" !message Python3 DLL will be loaded dynamically !endif CFLAGS = $(CFLAGS) -DFEAT_PYTHON3 PYTHON3_OBJ = $(OUTDIR)\if_python3.obj PYTHON3_INC = /I "$(PYTHON3)\Include" /I "$(PYTHON3)\PC" !if "$(DYNAMIC_PYTHON3)" == "yes" CFLAGS = $(CFLAGS) -DDYNAMIC_PYTHON3 \ -DDYNAMIC_PYTHON3_DLL=\"python$(PYTHON3_VER).dll\" PYTHON3_LIB = /nodefaultlib:python$(PYTHON3_VER).lib !else PYTHON3_LIB = $(PYTHON3)\libs\python$(PYTHON3_VER).lib !endif !endif # MzScheme interface !ifdef MZSCHEME !message MzScheme requested - root dir is "$(MZSCHEME)" !ifndef MZSCHEME_VER MZSCHEME_VER = 205_000 !endif CFLAGS = $(CFLAGS) -DFEAT_MZSCHEME -I $(MZSCHEME)\include !if EXIST("$(MZSCHEME)\collects\scheme\base.ss") \ || EXIST("$(MZSCHEME)\collects\scheme\base.rkt") # for MzScheme >= 4 we need to include byte code for basic Scheme stuff MZSCHEME_EXTRA_DEP = mzscheme_base.c CFLAGS = $(CFLAGS) -DINCLUDE_MZSCHEME_BASE !endif !if EXIST("$(MZSCHEME)\lib\msvc\libmzsch$(MZSCHEME_VER).lib") MZSCHEME_MAIN_LIB=mzsch !else MZSCHEME_MAIN_LIB=racket !endif !if EXIST("$(MZSCHEME)\lib\msvc\lib$(MZSCHEME_MAIN_LIB)$(MZSCHEME_VER).lib") \ && !EXIST("$(MZSCHEME)\lib\msvc\libmzgc$(MZSCHEME_VER).lib") !message Building with Precise GC MZSCHEME_PRECISE_GC = yes CFLAGS = $(CFLAGS) -DMZ_PRECISE_GC !endif !if "$(DYNAMIC_MZSCHEME)" == "yes" !if "$(MZSCHEME_PRECISE_GC)" == "yes" !error MzScheme with Precise GC cannot be loaded dynamically !endif !message MzScheme DLLs will be loaded dynamically CFLAGS = $(CFLAGS) -DDYNAMIC_MZSCHEME \ -DDYNAMIC_MZSCH_DLL=\"lib$(MZSCHEME_MAIN_LIB)$(MZSCHEME_VER).dll\" \ -DDYNAMIC_MZGC_DLL=\"libmzgc$(MZSCHEME_VER).dll\" !else !if "$(MZSCHEME_DEBUG)" == "yes" CFLAGS = $(CFLAGS) -DMZSCHEME_FORCE_GC !endif !if "$(MZSCHEME_PRECISE_GC)" == "yes" # Precise GC does not use separate dll MZSCHEME_LIB = $(MZSCHEME)\lib\msvc\lib$(MZSCHEME_MAIN_LIB)$(MZSCHEME_VER).lib !else MZSCHEME_LIB = $(MZSCHEME)\lib\msvc\libmzgc$(MZSCHEME_VER).lib \ $(MZSCHEME)\lib\msvc\lib$(MZSCHEME_MAIN_LIB)$(MZSCHEME_VER).lib !endif !endif MZSCHEME_OBJ = $(OUTDIR)\if_mzsch.obj # increase stack size MZSCHEME_LIB = $(MZSCHEME_LIB) /STACK:8388608 !endif # Perl interface !ifdef PERL !ifndef PERL_VER PERL_VER = 56 !endif !message Perl requested (version $(PERL_VER)) - root dir is "$(PERL)" !if "$(DYNAMIC_PERL)" == "yes" !if $(PERL_VER) >= 56 !message Perl DLL will be loaded dynamically !else !message Dynamic loading is not supported for Perl versions earlier than 5.6.0 !message Reverting to static loading... !undef DYNAMIC_PERL !endif !endif # Is Perl installed in architecture-specific directories? !if exist($(PERL)\Bin\MSWin32-x86) PERL_ARCH = \MSWin32-x86 !endif PERL_INCDIR = $(PERL)\Lib$(PERL_ARCH)\Core # Version-dependent stuff !if $(PERL_VER) == 55 PERL_LIB = $(PERL_INCDIR)\perl.lib !else PERL_DLL = perl$(PERL_VER).dll PERL_LIB = $(PERL_INCDIR)\perl$(PERL_VER).lib !endif CFLAGS = $(CFLAGS) -DFEAT_PERL # Do we want to load Perl dynamically? !if "$(DYNAMIC_PERL)" == "yes" CFLAGS = $(CFLAGS) -DDYNAMIC_PERL -DDYNAMIC_PERL_DLL=\"$(PERL_DLL)\" !undef PERL_LIB !endif PERL_EXE = $(PERL)\Bin$(PERL_ARCH)\perl PERL_INC = /I $(PERL_INCDIR) PERL_OBJ = $(OUTDIR)\if_perl.obj $(OUTDIR)\if_perlsfio.obj XSUBPP = $(PERL)\lib\ExtUtils\xsubpp !if exist($(XSUBPP)) XSUBPP = $(PERL_EXE) $(XSUBPP) !else XSUBPP = xsubpp !endif XSUBPP_TYPEMAP = $(PERL)\lib\ExtUtils\typemap !endif # # Support Ruby interface # !ifdef RUBY # Set default value !ifndef RUBY_VER RUBY_VER = 18 !endif !ifndef RUBY_VER_LONG RUBY_VER_LONG = 1.8 !endif !if $(RUBY_VER) >= 18 !ifndef RUBY_PLATFORM RUBY_PLATFORM = i386-mswin32 !endif !ifndef RUBY_INSTALL_NAME RUBY_INSTALL_NAME = msvcrt-ruby$(RUBY_VER) !endif !else !ifndef RUBY_PLATFORM RUBY_PLATFORM = i586-mswin32 !endif !ifndef RUBY_INSTALL_NAME RUBY_INSTALL_NAME = mswin32-ruby$(RUBY_VER) !endif !endif # $(RUBY_VER) >= 18 !message Ruby requested (version $(RUBY_VER)) - root dir is "$(RUBY)" CFLAGS = $(CFLAGS) -DFEAT_RUBY RUBY_OBJ = $(OUTDIR)\if_ruby.obj !if $(RUBY_VER) >= 190 RUBY_INC = /I "$(RUBY)\include\ruby-$(RUBY_VER_LONG)\$(RUBY_PLATFORM)" /I "$(RUBY)\include\ruby-$(RUBY_VER_LONG)" !else RUBY_INC = /I "$(RUBY)\lib\ruby\$(RUBY_VER_LONG)\$(RUBY_PLATFORM)" !endif RUBY_LIB = $(RUBY)\lib\$(RUBY_INSTALL_NAME).lib # Do we want to load Ruby dynamically? !if "$(DYNAMIC_RUBY)" == "yes" !message Ruby DLL will be loaded dynamically CFLAGS = $(CFLAGS) -DDYNAMIC_RUBY -DDYNAMIC_RUBY_VER=$(RUBY_VER) \ -DDYNAMIC_RUBY_DLL=\"$(RUBY_INSTALL_NAME).dll\" !undef RUBY_LIB !endif !endif # RUBY # # Support PostScript printing # !if "$(POSTSCRIPT)" == "yes" CFLAGS = $(CFLAGS) -DMSWINPS !endif # POSTSCRIPT # # FEATURES: TINY, SMALL, NORMAL, BIG or HUGE # !if "$(FEATURES)"=="" FEATURES = BIG !endif CFLAGS = $(CFLAGS) -DFEAT_$(FEATURES) # # Always generate the .pdb file, so that we get debug symbols that can be used # on a crash (doesn't add overhead to the executable). # Generate edit-and-continue debug info when no optimization - allows to # debug more conveniently (able to look at variables which are in registers) # CFLAGS = $(CFLAGS) /Fd$(OUTDIR)/ $(DEBUGINFO) LINK_PDB = /PDB:$(VIM).pdb -debug # # End extra feature include # !message conflags = /nologo /subsystem:$(SUBSYSTEM) PATHDEF_SRC = $(OUTDIR)\pathdef.c !IF "$(MAP)" == "yes" # "/map" is for debugging conflags = $(conflags) /map !ELSEIF "$(MAP)" == "lines" # "/mapinfo:lines" is for debugging, only works for VC6 and later conflags = $(conflags) /map /mapinfo:lines !ENDIF LINKARGS1 = $(linkdebug) $(conflags) LINKARGS2 = $(CON_LIB) $(GUI_LIB) $(LIBC) $(OLE_LIB) user32.lib $(SNIFF_LIB) \ $(LUA_LIB) $(MZSCHEME_LIB) $(PERL_LIB) $(PYTHON_LIB) $(PYTHON3_LIB) $(RUBY_LIB) \ $(TCL_LIB) $(NETBEANS_LIB) $(XPM_LIB) $(LINK_PDB) # Report link time code generation progress if used. !ifdef NODEBUG !if ("$(MSVCVER)" == "8.0") || ("$(MSVCVER)" == "9.0") || ("$(MSVCVER)" == "10.0") !if "$(OPTIMIZE)" != "SPACE" LINKARGS1 = $(LINKARGS1) /LTCG:STATUS !endif !endif !endif all: $(VIM).exe vimrun.exe install.exe uninstal.exe xxd/xxd.exe \ GvimExt/gvimext.dll $(VIM).exe: $(OUTDIR) $(OBJ) $(GUI_OBJ) $(OLE_OBJ) $(OLE_IDL) $(MZSCHEME_OBJ) \ $(LUA_OBJ) $(PERL_OBJ) $(PYTHON_OBJ) $(PYTHON3_OBJ) $(RUBY_OBJ) $(TCL_OBJ) \ $(SNIFF_OBJ) $(CSCOPE_OBJ) $(NETBEANS_OBJ) $(XPM_OBJ) \ version.c version.h $(CC) $(CFLAGS) version.c $(link) $(LINKARGS1) -out:$(VIM).exe $(OBJ) $(GUI_OBJ) $(OLE_OBJ) \ $(LUA_OBJ) $(MZSCHEME_OBJ) $(PERL_OBJ) $(PYTHON_OBJ) $(PYTHON3_OBJ) $(RUBY_OBJ) \ $(TCL_OBJ) $(SNIFF_OBJ) $(CSCOPE_OBJ) $(NETBEANS_OBJ) \ $(XPM_OBJ) $(OUTDIR)\version.obj $(LINKARGS2) $(VIM): $(VIM).exe $(OUTDIR): if not exist $(OUTDIR)/nul mkdir $(OUTDIR) install.exe: dosinst.c $(CC) /nologo -DNDEBUG -DWIN32 dosinst.c kernel32.lib shell32.lib \ user32.lib ole32.lib advapi32.lib uuid.lib - if exist install.exe del install.exe ren dosinst.exe install.exe uninstal.exe: uninstal.c $(CC) /nologo -DNDEBUG -DWIN32 uninstal.c shell32.lib advapi32.lib vimrun.exe: vimrun.c $(CC) /nologo -DNDEBUG vimrun.c xxd/xxd.exe: xxd/xxd.c cd xxd $(MAKE) /NOLOGO -f Make_mvc.mak cd .. GvimExt/gvimext.dll: GvimExt/gvimext.cpp GvimExt/gvimext.rc GvimExt/gvimext.h cd GvimExt $(MAKE) /NOLOGO -f Makefile $(MAKEFLAGS_GVIMEXT) cd .. tags: notags $(CTAGS) *.c *.cpp *.h if_perl.xs proto\*.pro notags: - if exist tags del tags clean: - if exist $(OUTDIR)/nul $(DEL_TREE) $(OUTDIR) - if exist *.obj del *.obj - if exist $(VIM).exe del $(VIM).exe - if exist $(VIM).ilk del $(VIM).ilk - if exist $(VIM).pdb del $(VIM).pdb - if exist $(VIM).map del $(VIM).map - if exist $(VIM).ncb del $(VIM).ncb - if exist vimrun.exe del vimrun.exe - if exist install.exe del install.exe - if exist uninstal.exe del uninstal.exe - if exist if_perl.c del if_perl.c - if exist dimm.h del dimm.h - if exist dimm_i.c del dimm_i.c - if exist dimm.tlb del dimm.tlb - if exist dosinst.exe del dosinst.exe - if exist mzscheme_base.c del mzscheme_base.c cd xxd $(MAKE) /NOLOGO -f Make_mvc.mak clean cd .. cd GvimExt $(MAKE) /NOLOGO -f Makefile clean cd .. cd GvimExt $(MAKE) /NOLOGO -f Makefile clean cd .. - if exist testdir\*.out del testdir\*.out test: cd testdir $(MAKE) /NOLOGO -f Make_dos.mak win32 cd .. testclean: cd testdir $(MAKE) /NOLOGO -f Make_dos.mak clean cd .. ########################################################################### # Create a default rule for transforming .c files to .obj files in $(OUTDIR) # Batch compilation is supported by nmake 1.62 (part of VS 5.0) and later) !IF "$(MSVCVER)" == "4.0" .c{$(OUTDIR)/}.obj: !ELSE .c{$(OUTDIR)/}.obj:: !ENDIF $(CC) $(CFLAGS) $< # Create a default rule for transforming .cpp files to .obj files in $(OUTDIR) # Batch compilation is supported by nmake 1.62 (part of VS 5.0) and later) !IF "$(MSVCVER)" == "4.0" .cpp{$(OUTDIR)/}.obj: !ELSE .cpp{$(OUTDIR)/}.obj:: !ENDIF $(CC) $(CFLAGS) $< $(OUTDIR)/blowfish.obj: $(OUTDIR) blowfish.c $(INCL) $(OUTDIR)/buffer.obj: $(OUTDIR) buffer.c $(INCL) $(OUTDIR)/charset.obj: $(OUTDIR) charset.c $(INCL) $(OUTDIR)/diff.obj: $(OUTDIR) diff.c $(INCL) $(OUTDIR)/digraph.obj: $(OUTDIR) digraph.c $(INCL) $(OUTDIR)/edit.obj: $(OUTDIR) edit.c $(INCL) $(OUTDIR)/eval.obj: $(OUTDIR) eval.c $(INCL) $(OUTDIR)/ex_cmds.obj: $(OUTDIR) ex_cmds.c $(INCL) $(OUTDIR)/ex_cmds2.obj: $(OUTDIR) ex_cmds2.c $(INCL) $(OUTDIR)/ex_docmd.obj: $(OUTDIR) ex_docmd.c $(INCL) ex_cmds.h $(OUTDIR)/ex_eval.obj: $(OUTDIR) ex_eval.c $(INCL) ex_cmds.h $(OUTDIR)/ex_getln.obj: $(OUTDIR) ex_getln.c $(INCL) $(OUTDIR)/fileio.obj: $(OUTDIR) fileio.c $(INCL) $(OUTDIR)/fold.obj: $(OUTDIR) fold.c $(INCL) $(OUTDIR)/getchar.obj: $(OUTDIR) getchar.c $(INCL) $(OUTDIR)/hardcopy.obj: $(OUTDIR) hardcopy.c $(INCL) $(OUTDIR)/hashtab.obj: $(OUTDIR) hashtab.c $(INCL) $(OUTDIR)/gui.obj: $(OUTDIR) gui.c $(INCL) $(GUI_INCL) $(OUTDIR)/gui_beval.obj: $(OUTDIR) gui_beval.c $(INCL) $(GUI_INCL) $(OUTDIR)/gui_w32.obj: $(OUTDIR) gui_w32.c gui_w48.c $(INCL) $(GUI_INCL) $(OUTDIR)/if_cscope.obj: $(OUTDIR) if_cscope.c $(INCL) $(OUTDIR)/if_lua.obj: $(OUTDIR) if_lua.c $(INCL) $(CC) $(CFLAGS) $(LUA_INC) if_lua.c if_perl.c : if_perl.xs typemap $(XSUBPP) -prototypes -typemap $(XSUBPP_TYPEMAP) \ -typemap typemap if_perl.xs > if_perl.c $(OUTDIR)/if_perl.obj: $(OUTDIR) if_perl.c $(INCL) $(CC) $(CFLAGS) $(PERL_INC) if_perl.c $(OUTDIR)/if_perlsfio.obj: $(OUTDIR) if_perlsfio.c $(INCL) $(CC) $(CFLAGS) $(PERL_INC) if_perlsfio.c $(OUTDIR)/if_mzsch.obj: $(OUTDIR) if_mzsch.c $(INCL) $(MZSCHEME_EXTRA_DEP) $(CC) $(CFLAGS) if_mzsch.c \ -DMZSCHEME_COLLECTS=\"$(MZSCHEME:\=\\)\\collects\" mzscheme_base.c: $(MZSCHEME)\mzc --c-mods mzscheme_base.c ++lib scheme/base $(OUTDIR)/if_python.obj: $(OUTDIR) if_python.c $(INCL) $(CC) $(CFLAGS) $(PYTHON_INC) if_python.c $(OUTDIR)/if_python3.obj: $(OUTDIR) if_python3.c $(INCL) $(CC) $(CFLAGS) $(PYTHON3_INC) if_python3.c $(OUTDIR)/if_ole.obj: $(OUTDIR) if_ole.cpp $(INCL) if_ole.h $(OUTDIR)/if_ruby.obj: $(OUTDIR) if_ruby.c $(INCL) $(CC) $(CFLAGS) $(RUBY_INC) if_ruby.c $(OUTDIR)/if_sniff.obj: $(OUTDIR) if_sniff.c $(INCL) $(CC) $(CFLAGS) if_sniff.c $(OUTDIR)/if_tcl.obj: $(OUTDIR) if_tcl.c $(INCL) $(CC) $(CFLAGS) $(TCL_INC) if_tcl.c $(OUTDIR)/main.obj: $(OUTDIR) main.c $(INCL) $(OUTDIR)/mark.obj: $(OUTDIR) mark.c $(INCL) $(OUTDIR)/memfile.obj: $(OUTDIR) memfile.c $(INCL) $(OUTDIR)/memline.obj: $(OUTDIR) memline.c $(INCL) $(OUTDIR)/menu.obj: $(OUTDIR) menu.c $(INCL) $(OUTDIR)/message.obj: $(OUTDIR) message.c $(INCL) $(OUTDIR)/misc1.obj: $(OUTDIR) misc1.c $(INCL) $(OUTDIR)/misc2.obj: $(OUTDIR) misc2.c $(INCL) $(OUTDIR)/move.obj: $(OUTDIR) move.c $(INCL) $(OUTDIR)/mbyte.obj: $(OUTDIR) mbyte.c $(INCL) $(OUTDIR)/netbeans.obj: $(OUTDIR) netbeans.c $(NBDEBUG_SRC) $(INCL) $(OUTDIR)/normal.obj: $(OUTDIR) normal.c $(INCL) $(OUTDIR)/option.obj: $(OUTDIR) option.c $(INCL) $(OUTDIR)/ops.obj: $(OUTDIR) ops.c $(INCL) $(OUTDIR)/os_mswin.obj: $(OUTDIR) os_mswin.c $(INCL) $(OUTDIR)/os_win32.obj: $(OUTDIR) os_win32.c $(INCL) os_win32.h $(OUTDIR)/os_w32exe.obj: $(OUTDIR) os_w32exe.c $(INCL) $(OUTDIR)/pathdef.obj: $(OUTDIR) $(PATHDEF_SRC) $(INCL) $(CC) $(CFLAGS) $(PATHDEF_SRC) $(OUTDIR)/popupmnu.obj: $(OUTDIR) popupmnu.c $(INCL) $(OUTDIR)/quickfix.obj: $(OUTDIR) quickfix.c $(INCL) $(OUTDIR)/regexp.obj: $(OUTDIR) regexp.c $(INCL) $(OUTDIR)/screen.obj: $(OUTDIR) screen.c $(INCL) $(OUTDIR)/search.obj: $(OUTDIR) search.c $(INCL) $(OUTDIR)/sha256.obj: $(OUTDIR) sha256.c $(INCL) $(OUTDIR)/spell.obj: $(OUTDIR) spell.c $(INCL) $(OUTDIR)/syntax.obj: $(OUTDIR) syntax.c $(INCL) $(OUTDIR)/tag.obj: $(OUTDIR) tag.c $(INCL) $(OUTDIR)/term.obj: $(OUTDIR) term.c $(INCL) $(OUTDIR)/ui.obj: $(OUTDIR) ui.c $(INCL) $(OUTDIR)/undo.obj: $(OUTDIR) undo.c $(INCL) $(OUTDIR)/window.obj: $(OUTDIR) window.c $(INCL) $(OUTDIR)/xpm_w32.obj: $(OUTDIR) xpm_w32.c $(CC) $(CFLAGS) $(XPM_INC) xpm_w32.c $(OUTDIR)/vim.res: $(OUTDIR) vim.rc gvim.exe.mnf version.h tools.bmp \ tearoff.bmp vim.ico vim_error.ico \ vim_alert.ico vim_info.ico vim_quest.ico $(RC) /l 0x409 /Fo$(OUTDIR)/vim.res $(RCFLAGS) vim.rc iid_ole.c if_ole.h vim.tlb: if_ole.idl midl /nologo /error none /proxy nul /iid iid_ole.c /tlb vim.tlb \ /header if_ole.h if_ole.idl dimm.h dimm_i.c: dimm.idl midl /nologo /error none /proxy nul dimm.idl $(OUTDIR)/dimm_i.obj: $(OUTDIR) dimm_i.c $(INCL) $(OUTDIR)/glbl_ime.obj: $(OUTDIR) glbl_ime.cpp dimm.h $(INCL) # $CFLAGS may contain backslashes and double quotes, escape them both. E0_CFLAGS = $(CFLAGS:\=\\) E_CFLAGS = $(E0_CFLAGS:"=\") # ") stop the string # $LINKARGS2 may contain backslashes and double quotes, escape them both. E0_LINKARGS2 = $(LINKARGS2:\=\\) E_LINKARGS2 = $(E0_LINKARGS2:"=\") # ") stop the string $(PATHDEF_SRC): auto @echo creating $(PATHDEF_SRC) @echo /* pathdef.c */ > $(PATHDEF_SRC) @echo #include "vim.h" >> $(PATHDEF_SRC) @echo char_u *default_vim_dir = (char_u *)"$(VIMRCLOC:\=\\)"; >> $(PATHDEF_SRC) @echo char_u *default_vimruntime_dir = (char_u *)"$(VIMRUNTIMEDIR:\=\\)"; >> $(PATHDEF_SRC) @echo char_u *all_cflags = (char_u *)"$(CC:\=\\) $(E_CFLAGS)"; >> $(PATHDEF_SRC) @echo char_u *all_lflags = (char_u *)"$(link:\=\\) $(LINKARGS1:\=\\) $(E_LINKARGS2)"; >> $(PATHDEF_SRC) @echo char_u *compiled_user = (char_u *)"$(USERNAME)"; >> $(PATHDEF_SRC) @echo char_u *compiled_sys = (char_u *)"$(USERDOMAIN)"; >> $(PATHDEF_SRC) auto: if not exist auto/nul mkdir auto # End Custom Build proto.h: \ proto/blowfish.pro \ proto/buffer.pro \ proto/charset.pro \ proto/diff.pro \ proto/digraph.pro \ proto/edit.pro \ proto/eval.pro \ proto/ex_cmds.pro \ proto/ex_cmds2.pro \ proto/ex_docmd.pro \ proto/ex_eval.pro \ proto/ex_getln.pro \ proto/fileio.pro \ proto/getchar.pro \ proto/hardcopy.pro \ proto/hashtab.pro \ proto/main.pro \ proto/mark.pro \ proto/memfile.pro \ proto/memline.pro \ proto/menu.pro \ proto/message.pro \ proto/misc1.pro \ proto/misc2.pro \ proto/move.pro \ proto/mbyte.pro \ proto/normal.pro \ proto/ops.pro \ proto/option.pro \ proto/os_mswin.pro \ proto/os_win32.pro \ proto/popupmnu.pro \ proto/quickfix.pro \ proto/regexp.pro \ proto/screen.pro \ proto/search.pro \ proto/sha256.pro \ proto/spell.pro \ proto/syntax.pro \ proto/tag.pro \ proto/term.pro \ proto/ui.pro \ proto/undo.pro \ proto/window.pro \ $(NETBEANS_PRO) .SUFFIXES: .cod .i # Generate foo.cod (mixed source and assembly listing) from foo.c via "nmake # foo.cod" .c.cod: $(CC) $(CFLAGS) /FAcs $< # Generate foo.i (preprocessor listing) from foo.c via "nmake foo.i" .c.i: $(CC) $(CFLAGS) /P /C $< # vim: set noet sw=8 ts=8 sts=0 wm=0 tw=0:
zyz2011-vim
src/Make_mvc.mak
Makefile
gpl2
33,548
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * search.c: code for normal mode searching commands */ #include "vim.h" static void save_re_pat __ARGS((int idx, char_u *pat, int magic)); #ifdef FEAT_EVAL static void set_vv_searchforward __ARGS((void)); static int first_submatch __ARGS((regmmatch_T *rp)); #endif static int check_prevcol __ARGS((char_u *linep, int col, int ch, int *prevcol)); static int inmacro __ARGS((char_u *, char_u *)); static int check_linecomment __ARGS((char_u *line)); static int cls __ARGS((void)); static int skip_chars __ARGS((int, int)); #ifdef FEAT_TEXTOBJ static void back_in_line __ARGS((void)); static void find_first_blank __ARGS((pos_T *)); static void findsent_forward __ARGS((long count, int at_start_sent)); #endif #ifdef FEAT_FIND_ID static void show_pat_in_path __ARGS((char_u *, int, int, int, FILE *, linenr_T *, long)); #endif #ifdef FEAT_VIMINFO static void wvsp_one __ARGS((FILE *fp, int idx, char *s, int sc)); #endif /* * This file contains various searching-related routines. These fall into * three groups: * 1. string searches (for /, ?, n, and N) * 2. character searches within a single line (for f, F, t, T, etc) * 3. "other" kinds of searches like the '%' command, and 'word' searches. */ /* * String searches * * The string search functions are divided into two levels: * lowest: searchit(); uses an pos_T for starting position and found match. * Highest: do_search(); uses curwin->w_cursor; calls searchit(). * * The last search pattern is remembered for repeating the same search. * This pattern is shared between the :g, :s, ? and / commands. * This is in search_regcomp(). * * The actual string matching is done using a heavily modified version of * Henry Spencer's regular expression library. See regexp.c. */ /* The offset for a search command is store in a soff struct */ /* Note: only spats[0].off is really used */ struct soffset { int dir; /* search direction, '/' or '?' */ int line; /* search has line offset */ int end; /* search set cursor at end */ long off; /* line or char offset */ }; /* A search pattern and its attributes are stored in a spat struct */ struct spat { char_u *pat; /* the pattern (in allocated memory) or NULL */ int magic; /* magicness of the pattern */ int no_scs; /* no smarcase for this pattern */ struct soffset off; }; /* * Two search patterns are remembered: One for the :substitute command and * one for other searches. last_idx points to the one that was used the last * time. */ static struct spat spats[2] = { {NULL, TRUE, FALSE, {'/', 0, 0, 0L}}, /* last used search pat */ {NULL, TRUE, FALSE, {'/', 0, 0, 0L}} /* last used substitute pat */ }; static int last_idx = 0; /* index in spats[] for RE_LAST */ #if defined(FEAT_AUTOCMD) || defined(FEAT_EVAL) || defined(PROTO) /* copy of spats[], for keeping the search patterns while executing autocmds */ static struct spat saved_spats[2]; static int saved_last_idx = 0; # ifdef FEAT_SEARCH_EXTRA static int saved_no_hlsearch = 0; # endif #endif static char_u *mr_pattern = NULL; /* pattern used by search_regcomp() */ #ifdef FEAT_RIGHTLEFT static int mr_pattern_alloced = FALSE; /* mr_pattern was allocated */ #endif #ifdef FEAT_FIND_ID /* * Type used by find_pattern_in_path() to remember which included files have * been searched already. */ typedef struct SearchedFile { FILE *fp; /* File pointer */ char_u *name; /* Full name of file */ linenr_T lnum; /* Line we were up to in file */ int matched; /* Found a match in this file */ } SearchedFile; #endif /* * translate search pattern for vim_regcomp() * * pat_save == RE_SEARCH: save pat in spats[RE_SEARCH].pat (normal search cmd) * pat_save == RE_SUBST: save pat in spats[RE_SUBST].pat (:substitute command) * pat_save == RE_BOTH: save pat in both patterns (:global command) * pat_use == RE_SEARCH: use previous search pattern if "pat" is NULL * pat_use == RE_SUBST: use previous substitute pattern if "pat" is NULL * pat_use == RE_LAST: use last used pattern if "pat" is NULL * options & SEARCH_HIS: put search string in history * options & SEARCH_KEEP: keep previous search pattern * * returns FAIL if failed, OK otherwise. */ int search_regcomp(pat, pat_save, pat_use, options, regmatch) char_u *pat; int pat_save; int pat_use; int options; regmmatch_T *regmatch; /* return: pattern and ignore-case flag */ { int magic; int i; rc_did_emsg = FALSE; magic = p_magic; /* * If no pattern given, use a previously defined pattern. */ if (pat == NULL || *pat == NUL) { if (pat_use == RE_LAST) i = last_idx; else i = pat_use; if (spats[i].pat == NULL) /* pattern was never defined */ { if (pat_use == RE_SUBST) EMSG(_(e_nopresub)); else EMSG(_(e_noprevre)); rc_did_emsg = TRUE; return FAIL; } pat = spats[i].pat; magic = spats[i].magic; no_smartcase = spats[i].no_scs; } #ifdef FEAT_CMDHIST else if (options & SEARCH_HIS) /* put new pattern in history */ add_to_history(HIST_SEARCH, pat, TRUE, NUL); #endif #ifdef FEAT_RIGHTLEFT if (mr_pattern_alloced) { vim_free(mr_pattern); mr_pattern_alloced = FALSE; } if (curwin->w_p_rl && *curwin->w_p_rlc == 's') { char_u *rev_pattern; rev_pattern = reverse_text(pat); if (rev_pattern == NULL) mr_pattern = pat; /* out of memory, keep normal pattern. */ else { mr_pattern = rev_pattern; mr_pattern_alloced = TRUE; } } else #endif mr_pattern = pat; /* * Save the currently used pattern in the appropriate place, * unless the pattern should not be remembered. */ if (!(options & SEARCH_KEEP)) { /* search or global command */ if (pat_save == RE_SEARCH || pat_save == RE_BOTH) save_re_pat(RE_SEARCH, pat, magic); /* substitute or global command */ if (pat_save == RE_SUBST || pat_save == RE_BOTH) save_re_pat(RE_SUBST, pat, magic); } regmatch->rmm_ic = ignorecase(pat); regmatch->rmm_maxcol = 0; regmatch->regprog = vim_regcomp(pat, magic ? RE_MAGIC : 0); if (regmatch->regprog == NULL) return FAIL; return OK; } /* * Get search pattern used by search_regcomp(). */ char_u * get_search_pat() { return mr_pattern; } #if defined(FEAT_RIGHTLEFT) || defined(PROTO) /* * Reverse text into allocated memory. * Returns the allocated string, NULL when out of memory. */ char_u * reverse_text(s) char_u *s; { unsigned len; unsigned s_i, rev_i; char_u *rev; /* * Reverse the pattern. */ len = (unsigned)STRLEN(s); rev = alloc(len + 1); if (rev != NULL) { rev_i = len; for (s_i = 0; s_i < len; ++s_i) { # ifdef FEAT_MBYTE if (has_mbyte) { int mb_len; mb_len = (*mb_ptr2len)(s + s_i); rev_i -= mb_len; mch_memmove(rev + rev_i, s + s_i, mb_len); s_i += mb_len - 1; } else # endif rev[--rev_i] = s[s_i]; } rev[len] = NUL; } return rev; } #endif static void save_re_pat(idx, pat, magic) int idx; char_u *pat; int magic; { if (spats[idx].pat != pat) { vim_free(spats[idx].pat); spats[idx].pat = vim_strsave(pat); spats[idx].magic = magic; spats[idx].no_scs = no_smartcase; last_idx = idx; #ifdef FEAT_SEARCH_EXTRA /* If 'hlsearch' set and search pat changed: need redraw. */ if (p_hls) redraw_all_later(SOME_VALID); no_hlsearch = FALSE; #endif } } #if defined(FEAT_AUTOCMD) || defined(FEAT_EVAL) || defined(PROTO) /* * Save the search patterns, so they can be restored later. * Used before/after executing autocommands and user functions. */ static int save_level = 0; void save_search_patterns() { if (save_level++ == 0) { saved_spats[0] = spats[0]; if (spats[0].pat != NULL) saved_spats[0].pat = vim_strsave(spats[0].pat); saved_spats[1] = spats[1]; if (spats[1].pat != NULL) saved_spats[1].pat = vim_strsave(spats[1].pat); saved_last_idx = last_idx; # ifdef FEAT_SEARCH_EXTRA saved_no_hlsearch = no_hlsearch; # endif } } void restore_search_patterns() { if (--save_level == 0) { vim_free(spats[0].pat); spats[0] = saved_spats[0]; #if defined(FEAT_EVAL) set_vv_searchforward(); #endif vim_free(spats[1].pat); spats[1] = saved_spats[1]; last_idx = saved_last_idx; # ifdef FEAT_SEARCH_EXTRA no_hlsearch = saved_no_hlsearch; # endif } } #endif #if defined(EXITFREE) || defined(PROTO) void free_search_patterns() { vim_free(spats[0].pat); vim_free(spats[1].pat); # ifdef FEAT_RIGHTLEFT if (mr_pattern_alloced) { vim_free(mr_pattern); mr_pattern_alloced = FALSE; mr_pattern = NULL; } # endif } #endif /* * Return TRUE when case should be ignored for search pattern "pat". * Uses the 'ignorecase' and 'smartcase' options. */ int ignorecase(pat) char_u *pat; { int ic = p_ic; if (ic && !no_smartcase && p_scs #ifdef FEAT_INS_EXPAND && !(ctrl_x_mode && curbuf->b_p_inf) #endif ) ic = !pat_has_uppercase(pat); no_smartcase = FALSE; return ic; } /* * Return TRUE if patter "pat" has an uppercase character. */ int pat_has_uppercase(pat) char_u *pat; { char_u *p = pat; while (*p != NUL) { #ifdef FEAT_MBYTE int l; if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1) { if (enc_utf8 && utf_isupper(utf_ptr2char(p))) return TRUE; p += l; } else #endif if (*p == '\\') { if (p[1] == '_' && p[2] != NUL) /* skip "\_X" */ p += 3; else if (p[1] == '%' && p[2] != NUL) /* skip "\%X" */ p += 3; else if (p[1] != NUL) /* skip "\X" */ p += 2; else p += 1; } else if (MB_ISUPPER(*p)) return TRUE; else ++p; } return FALSE; } char_u * last_search_pat() { return spats[last_idx].pat; } /* * Reset search direction to forward. For "gd" and "gD" commands. */ void reset_search_dir() { spats[0].off.dir = '/'; #if defined(FEAT_EVAL) set_vv_searchforward(); #endif } #if defined(FEAT_EVAL) || defined(FEAT_VIMINFO) /* * Set the last search pattern. For ":let @/ =" and viminfo. * Also set the saved search pattern, so that this works in an autocommand. */ void set_last_search_pat(s, idx, magic, setlast) char_u *s; int idx; int magic; int setlast; { vim_free(spats[idx].pat); /* An empty string means that nothing should be matched. */ if (*s == NUL) spats[idx].pat = NULL; else spats[idx].pat = vim_strsave(s); spats[idx].magic = magic; spats[idx].no_scs = FALSE; spats[idx].off.dir = '/'; #if defined(FEAT_EVAL) set_vv_searchforward(); #endif spats[idx].off.line = FALSE; spats[idx].off.end = FALSE; spats[idx].off.off = 0; if (setlast) last_idx = idx; if (save_level) { vim_free(saved_spats[idx].pat); saved_spats[idx] = spats[0]; if (spats[idx].pat == NULL) saved_spats[idx].pat = NULL; else saved_spats[idx].pat = vim_strsave(spats[idx].pat); saved_last_idx = last_idx; } # ifdef FEAT_SEARCH_EXTRA /* If 'hlsearch' set and search pat changed: need redraw. */ if (p_hls && idx == last_idx && !no_hlsearch) redraw_all_later(SOME_VALID); # endif } #endif #ifdef FEAT_SEARCH_EXTRA /* * Get a regexp program for the last used search pattern. * This is used for highlighting all matches in a window. * Values returned in regmatch->regprog and regmatch->rmm_ic. */ void last_pat_prog(regmatch) regmmatch_T *regmatch; { if (spats[last_idx].pat == NULL) { regmatch->regprog = NULL; return; } ++emsg_off; /* So it doesn't beep if bad expr */ (void)search_regcomp((char_u *)"", 0, last_idx, SEARCH_KEEP, regmatch); --emsg_off; } #endif /* * lowest level search function. * Search for 'count'th occurrence of pattern 'pat' in direction 'dir'. * Start at position 'pos' and return the found position in 'pos'. * * if (options & SEARCH_MSG) == 0 don't give any messages * if (options & SEARCH_MSG) == SEARCH_NFMSG don't give 'notfound' messages * if (options & SEARCH_MSG) == SEARCH_MSG give all messages * if (options & SEARCH_HIS) put search pattern in history * if (options & SEARCH_END) return position at end of match * if (options & SEARCH_START) accept match at pos itself * if (options & SEARCH_KEEP) keep previous search pattern * if (options & SEARCH_FOLD) match only once in a closed fold * if (options & SEARCH_PEEK) check for typed char, cancel search * * Return FAIL (zero) for failure, non-zero for success. * When FEAT_EVAL is defined, returns the index of the first matching * subpattern plus one; one if there was none. */ int searchit(win, buf, pos, dir, pat, count, options, pat_use, stop_lnum, tm) win_T *win; /* window to search in; can be NULL for a buffer without a window! */ buf_T *buf; pos_T *pos; int dir; char_u *pat; long count; int options; int pat_use; /* which pattern to use when "pat" is empty */ linenr_T stop_lnum; /* stop after this line number when != 0 */ proftime_T *tm UNUSED; /* timeout limit or NULL */ { int found; linenr_T lnum; /* no init to shut up Apollo cc */ regmmatch_T regmatch; char_u *ptr; colnr_T matchcol; lpos_T endpos; lpos_T matchpos; int loop; pos_T start_pos; int at_first_line; int extra_col; int match_ok; long nmatched; int submatch = 0; int save_called_emsg = called_emsg; #ifdef FEAT_SEARCH_EXTRA int break_loop = FALSE; #endif if (search_regcomp(pat, RE_SEARCH, pat_use, (options & (SEARCH_HIS + SEARCH_KEEP)), &regmatch) == FAIL) { if ((options & SEARCH_MSG) && !rc_did_emsg) EMSG2(_("E383: Invalid search string: %s"), mr_pattern); return FAIL; } /* When not accepting a match at the start position set "extra_col" to a * non-zero value. Don't do that when starting at MAXCOL, since MAXCOL + * 1 is zero. */ if ((options & SEARCH_START) || pos->col == MAXCOL) extra_col = 0; #ifdef FEAT_MBYTE /* Watch out for the "col" being MAXCOL - 2, used in a closed fold. */ else if (has_mbyte && pos->lnum >= 1 && pos->lnum <= buf->b_ml.ml_line_count && pos->col < MAXCOL - 2) { ptr = ml_get_buf(buf, pos->lnum, FALSE) + pos->col; if (*ptr == NUL) extra_col = 1; else extra_col = (*mb_ptr2len)(ptr); } #endif else extra_col = 1; /* * find the string */ called_emsg = FALSE; do /* loop for count */ { start_pos = *pos; /* remember start pos for detecting no match */ found = 0; /* default: not found */ at_first_line = TRUE; /* default: start in first line */ if (pos->lnum == 0) /* correct lnum for when starting in line 0 */ { pos->lnum = 1; pos->col = 0; at_first_line = FALSE; /* not in first line now */ } /* * Start searching in current line, unless searching backwards and * we're in column 0. * If we are searching backwards, in column 0, and not including the * current position, gain some efficiency by skipping back a line. * Otherwise begin the search in the current line. */ if (dir == BACKWARD && start_pos.col == 0 && (options & SEARCH_START) == 0) { lnum = pos->lnum - 1; at_first_line = FALSE; } else lnum = pos->lnum; for (loop = 0; loop <= 1; ++loop) /* loop twice if 'wrapscan' set */ { for ( ; lnum > 0 && lnum <= buf->b_ml.ml_line_count; lnum += dir, at_first_line = FALSE) { /* Stop after checking "stop_lnum", if it's set. */ if (stop_lnum != 0 && (dir == FORWARD ? lnum > stop_lnum : lnum < stop_lnum)) break; #ifdef FEAT_RELTIME /* Stop after passing the "tm" time limit. */ if (tm != NULL && profile_passed_limit(tm)) break; #endif /* * Look for a match somewhere in line "lnum". */ nmatched = vim_regexec_multi(&regmatch, win, buf, lnum, (colnr_T)0, #ifdef FEAT_RELTIME tm #else NULL #endif ); /* Abort searching on an error (e.g., out of stack). */ if (called_emsg) break; if (nmatched > 0) { /* match may actually be in another line when using \zs */ matchpos = regmatch.startpos[0]; endpos = regmatch.endpos[0]; #ifdef FEAT_EVAL submatch = first_submatch(&regmatch); #endif /* "lnum" may be past end of buffer for "\n\zs". */ if (lnum + matchpos.lnum > buf->b_ml.ml_line_count) ptr = (char_u *)""; else ptr = ml_get_buf(buf, lnum + matchpos.lnum, FALSE); /* * Forward search in the first line: match should be after * the start position. If not, continue at the end of the * match (this is vi compatible) or on the next char. */ if (dir == FORWARD && at_first_line) { match_ok = TRUE; /* * When the match starts in a next line it's certainly * past the start position. * When match lands on a NUL the cursor will be put * one back afterwards, compare with that position, * otherwise "/$" will get stuck on end of line. */ while (matchpos.lnum == 0 && ((options & SEARCH_END) ? (nmatched == 1 && (int)endpos.col - 1 < (int)start_pos.col + extra_col) : ((int)matchpos.col - (ptr[matchpos.col] == NUL) < (int)start_pos.col + extra_col))) { /* * If vi-compatible searching, continue at the end * of the match, otherwise continue one position * forward. */ if (vim_strchr(p_cpo, CPO_SEARCH) != NULL) { if (nmatched > 1) { /* end is in next line, thus no match in * this line */ match_ok = FALSE; break; } matchcol = endpos.col; /* for empty match: advance one char */ if (matchcol == matchpos.col && ptr[matchcol] != NUL) { #ifdef FEAT_MBYTE if (has_mbyte) matchcol += (*mb_ptr2len)(ptr + matchcol); else #endif ++matchcol; } } else { matchcol = matchpos.col; if (ptr[matchcol] != NUL) { #ifdef FEAT_MBYTE if (has_mbyte) matchcol += (*mb_ptr2len)(ptr + matchcol); else #endif ++matchcol; } } if (ptr[matchcol] == NUL || (nmatched = vim_regexec_multi(&regmatch, win, buf, lnum + matchpos.lnum, matchcol, #ifdef FEAT_RELTIME tm #else NULL #endif )) == 0) { match_ok = FALSE; break; } matchpos = regmatch.startpos[0]; endpos = regmatch.endpos[0]; # ifdef FEAT_EVAL submatch = first_submatch(&regmatch); # endif /* Need to get the line pointer again, a * multi-line search may have made it invalid. */ ptr = ml_get_buf(buf, lnum + matchpos.lnum, FALSE); } if (!match_ok) continue; } if (dir == BACKWARD) { /* * Now, if there are multiple matches on this line, * we have to get the last one. Or the last one before * the cursor, if we're on that line. * When putting the new cursor at the end, compare * relative to the end of the match. */ match_ok = FALSE; for (;;) { /* Remember a position that is before the start * position, we use it if it's the last match in * the line. Always accept a position after * wrapping around. */ if (loop || ((options & SEARCH_END) ? (lnum + regmatch.endpos[0].lnum < start_pos.lnum || (lnum + regmatch.endpos[0].lnum == start_pos.lnum && (int)regmatch.endpos[0].col - 1 + extra_col <= (int)start_pos.col)) : (lnum + regmatch.startpos[0].lnum < start_pos.lnum || (lnum + regmatch.startpos[0].lnum == start_pos.lnum && (int)regmatch.startpos[0].col + extra_col <= (int)start_pos.col)))) { match_ok = TRUE; matchpos = regmatch.startpos[0]; endpos = regmatch.endpos[0]; # ifdef FEAT_EVAL submatch = first_submatch(&regmatch); # endif } else break; /* * We found a valid match, now check if there is * another one after it. * If vi-compatible searching, continue at the end * of the match, otherwise continue one position * forward. */ if (vim_strchr(p_cpo, CPO_SEARCH) != NULL) { if (nmatched > 1) break; matchcol = endpos.col; /* for empty match: advance one char */ if (matchcol == matchpos.col && ptr[matchcol] != NUL) { #ifdef FEAT_MBYTE if (has_mbyte) matchcol += (*mb_ptr2len)(ptr + matchcol); else #endif ++matchcol; } } else { /* Stop when the match is in a next line. */ if (matchpos.lnum > 0) break; matchcol = matchpos.col; if (ptr[matchcol] != NUL) { #ifdef FEAT_MBYTE if (has_mbyte) matchcol += (*mb_ptr2len)(ptr + matchcol); else #endif ++matchcol; } } if (ptr[matchcol] == NUL || (nmatched = vim_regexec_multi(&regmatch, win, buf, lnum + matchpos.lnum, matchcol, #ifdef FEAT_RELTIME tm #else NULL #endif )) == 0) break; /* Need to get the line pointer again, a * multi-line search may have made it invalid. */ ptr = ml_get_buf(buf, lnum + matchpos.lnum, FALSE); } /* * If there is only a match after the cursor, skip * this match. */ if (!match_ok) continue; } /* With the SEARCH_END option move to the last character * of the match. Don't do it for an empty match, end * should be same as start then. */ if (options & SEARCH_END && !(options & SEARCH_NOOF) && !(matchpos.lnum == endpos.lnum && matchpos.col == endpos.col)) { /* For a match in the first column, set the position * on the NUL in the previous line. */ pos->lnum = lnum + endpos.lnum; pos->col = endpos.col; if (endpos.col == 0) { if (pos->lnum > 1) /* just in case */ { --pos->lnum; pos->col = (colnr_T)STRLEN(ml_get_buf(buf, pos->lnum, FALSE)); } } else { --pos->col; #ifdef FEAT_MBYTE if (has_mbyte && pos->lnum <= buf->b_ml.ml_line_count) { ptr = ml_get_buf(buf, pos->lnum, FALSE); pos->col -= (*mb_head_off)(ptr, ptr + pos->col); } #endif } } else { pos->lnum = lnum + matchpos.lnum; pos->col = matchpos.col; } #ifdef FEAT_VIRTUALEDIT pos->coladd = 0; #endif found = 1; /* Set variables used for 'incsearch' highlighting. */ search_match_lines = endpos.lnum - matchpos.lnum; search_match_endcol = endpos.col; break; } line_breakcheck(); /* stop if ctrl-C typed */ if (got_int) break; #ifdef FEAT_SEARCH_EXTRA /* Cancel searching if a character was typed. Used for * 'incsearch'. Don't check too often, that would slowdown * searching too much. */ if ((options & SEARCH_PEEK) && ((lnum - pos->lnum) & 0x3f) == 0 && char_avail()) { break_loop = TRUE; break; } #endif if (loop && lnum == start_pos.lnum) break; /* if second loop, stop where started */ } at_first_line = FALSE; /* * Stop the search if wrapscan isn't set, "stop_lnum" is * specified, after an interrupt, after a match and after looping * twice. */ if (!p_ws || stop_lnum != 0 || got_int || called_emsg #ifdef FEAT_SEARCH_EXTRA || break_loop #endif || found || loop) break; /* * If 'wrapscan' is set we continue at the other end of the file. * If 'shortmess' does not contain 's', we give a message. * This message is also remembered in keep_msg for when the screen * is redrawn. The keep_msg is cleared whenever another message is * written. */ if (dir == BACKWARD) /* start second loop at the other end */ lnum = buf->b_ml.ml_line_count; else lnum = 1; if (!shortmess(SHM_SEARCH) && (options & SEARCH_MSG)) give_warning((char_u *)_(dir == BACKWARD ? top_bot_msg : bot_top_msg), TRUE); } if (got_int || called_emsg #ifdef FEAT_SEARCH_EXTRA || break_loop #endif ) break; } while (--count > 0 && found); /* stop after count matches or no match */ vim_free(regmatch.regprog); called_emsg |= save_called_emsg; if (!found) /* did not find it */ { if (got_int) EMSG(_(e_interr)); else if ((options & SEARCH_MSG) == SEARCH_MSG) { if (p_ws) EMSG2(_(e_patnotf2), mr_pattern); else if (lnum == 0) EMSG2(_("E384: search hit TOP without match for: %s"), mr_pattern); else EMSG2(_("E385: search hit BOTTOM without match for: %s"), mr_pattern); } return FAIL; } /* A pattern like "\n\zs" may go past the last line. */ if (pos->lnum > buf->b_ml.ml_line_count) { pos->lnum = buf->b_ml.ml_line_count; pos->col = (int)STRLEN(ml_get_buf(buf, pos->lnum, FALSE)); if (pos->col > 0) --pos->col; } return submatch + 1; } #ifdef FEAT_EVAL void set_search_direction(cdir) int cdir; { spats[0].off.dir = cdir; } static void set_vv_searchforward() { set_vim_var_nr(VV_SEARCHFORWARD, (long)(spats[0].off.dir == '/')); } /* * Return the number of the first subpat that matched. */ static int first_submatch(rp) regmmatch_T *rp; { int submatch; for (submatch = 1; ; ++submatch) { if (rp->startpos[submatch].lnum >= 0) break; if (submatch == 9) { submatch = 0; break; } } return submatch; } #endif /* * Highest level string search function. * Search for the 'count'th occurrence of pattern 'pat' in direction 'dirc' * If 'dirc' is 0: use previous dir. * If 'pat' is NULL or empty : use previous string. * If 'options & SEARCH_REV' : go in reverse of previous dir. * If 'options & SEARCH_ECHO': echo the search command and handle options * If 'options & SEARCH_MSG' : may give error message * If 'options & SEARCH_OPT' : interpret optional flags * If 'options & SEARCH_HIS' : put search pattern in history * If 'options & SEARCH_NOOF': don't add offset to position * If 'options & SEARCH_MARK': set previous context mark * If 'options & SEARCH_KEEP': keep previous search pattern * If 'options & SEARCH_START': accept match at curpos itself * If 'options & SEARCH_PEEK': check for typed char, cancel search * * Careful: If spats[0].off.line == TRUE and spats[0].off.off == 0 this * makes the movement linewise without moving the match position. * * return 0 for failure, 1 for found, 2 for found and line offset added */ int do_search(oap, dirc, pat, count, options, tm) oparg_T *oap; /* can be NULL */ int dirc; /* '/' or '?' */ char_u *pat; long count; int options; proftime_T *tm; /* timeout limit or NULL */ { pos_T pos; /* position of the last match */ char_u *searchstr; struct soffset old_off; int retval; /* Return value */ char_u *p; long c; char_u *dircp; char_u *strcopy = NULL; char_u *ps; /* * A line offset is not remembered, this is vi compatible. */ if (spats[0].off.line && vim_strchr(p_cpo, CPO_LINEOFF) != NULL) { spats[0].off.line = FALSE; spats[0].off.off = 0; } /* * Save the values for when (options & SEARCH_KEEP) is used. * (there is no "if ()" around this because gcc wants them initialized) */ old_off = spats[0].off; pos = curwin->w_cursor; /* start searching at the cursor position */ /* * Find out the direction of the search. */ if (dirc == 0) dirc = spats[0].off.dir; else { spats[0].off.dir = dirc; #if defined(FEAT_EVAL) set_vv_searchforward(); #endif } if (options & SEARCH_REV) { #ifdef WIN32 /* There is a bug in the Visual C++ 2.2 compiler which means that * dirc always ends up being '/' */ dirc = (dirc == '/') ? '?' : '/'; #else if (dirc == '/') dirc = '?'; else dirc = '/'; #endif } #ifdef FEAT_FOLDING /* If the cursor is in a closed fold, don't find another match in the same * fold. */ if (dirc == '/') { if (hasFolding(pos.lnum, NULL, &pos.lnum)) pos.col = MAXCOL - 2; /* avoid overflow when adding 1 */ } else { if (hasFolding(pos.lnum, &pos.lnum, NULL)) pos.col = 0; } #endif #ifdef FEAT_SEARCH_EXTRA /* * Turn 'hlsearch' highlighting back on. */ if (no_hlsearch && !(options & SEARCH_KEEP)) { redraw_all_later(SOME_VALID); no_hlsearch = FALSE; } #endif /* * Repeat the search when pattern followed by ';', e.g. "/foo/;?bar". */ for (;;) { searchstr = pat; dircp = NULL; /* use previous pattern */ if (pat == NULL || *pat == NUL || *pat == dirc) { if (spats[RE_SEARCH].pat == NULL) /* no previous pattern */ { pat = spats[RE_SUBST].pat; if (pat == NULL) { EMSG(_(e_noprevre)); retval = 0; goto end_do_search; } searchstr = pat; } else { /* make search_regcomp() use spats[RE_SEARCH].pat */ searchstr = (char_u *)""; } } if (pat != NULL && *pat != NUL) /* look for (new) offset */ { /* * Find end of regular expression. * If there is a matching '/' or '?', toss it. */ ps = strcopy; p = skip_regexp(pat, dirc, (int)p_magic, &strcopy); if (strcopy != ps) { /* made a copy of "pat" to change "\?" to "?" */ searchcmdlen += (int)(STRLEN(pat) - STRLEN(strcopy)); pat = strcopy; searchstr = strcopy; } if (*p == dirc) { dircp = p; /* remember where we put the NUL */ *p++ = NUL; } spats[0].off.line = FALSE; spats[0].off.end = FALSE; spats[0].off.off = 0; /* * Check for a line offset or a character offset. * For get_address (echo off) we don't check for a character * offset, because it is meaningless and the 's' could be a * substitute command. */ if (*p == '+' || *p == '-' || VIM_ISDIGIT(*p)) spats[0].off.line = TRUE; else if ((options & SEARCH_OPT) && (*p == 'e' || *p == 's' || *p == 'b')) { if (*p == 'e') /* end */ spats[0].off.end = SEARCH_END; ++p; } if (VIM_ISDIGIT(*p) || *p == '+' || *p == '-') /* got an offset */ { /* 'nr' or '+nr' or '-nr' */ if (VIM_ISDIGIT(*p) || VIM_ISDIGIT(*(p + 1))) spats[0].off.off = atol((char *)p); else if (*p == '-') /* single '-' */ spats[0].off.off = -1; else /* single '+' */ spats[0].off.off = 1; ++p; while (VIM_ISDIGIT(*p)) /* skip number */ ++p; } /* compute length of search command for get_address() */ searchcmdlen += (int)(p - pat); pat = p; /* put pat after search command */ } if ((options & SEARCH_ECHO) && messaging() && !cmd_silent && msg_silent == 0) { char_u *msgbuf; char_u *trunc; if (*searchstr == NUL) p = spats[last_idx].pat; else p = searchstr; msgbuf = alloc((unsigned)(STRLEN(p) + 40)); if (msgbuf != NULL) { msgbuf[0] = dirc; #ifdef FEAT_MBYTE if (enc_utf8 && utf_iscomposing(utf_ptr2char(p))) { /* Use a space to draw the composing char on. */ msgbuf[1] = ' '; STRCPY(msgbuf + 2, p); } else #endif STRCPY(msgbuf + 1, p); if (spats[0].off.line || spats[0].off.end || spats[0].off.off) { p = msgbuf + STRLEN(msgbuf); *p++ = dirc; if (spats[0].off.end) *p++ = 'e'; else if (!spats[0].off.line) *p++ = 's'; if (spats[0].off.off > 0 || spats[0].off.line) *p++ = '+'; if (spats[0].off.off != 0 || spats[0].off.line) sprintf((char *)p, "%ld", spats[0].off.off); else *p = NUL; } msg_start(); trunc = msg_strtrunc(msgbuf, FALSE); #ifdef FEAT_RIGHTLEFT /* The search pattern could be shown on the right in rightleft * mode, but the 'ruler' and 'showcmd' area use it too, thus * it would be blanked out again very soon. Show it on the * left, but do reverse the text. */ if (curwin->w_p_rl && *curwin->w_p_rlc == 's') { char_u *r; r = reverse_text(trunc != NULL ? trunc : msgbuf); if (r != NULL) { vim_free(trunc); trunc = r; } } #endif if (trunc != NULL) { msg_outtrans(trunc); vim_free(trunc); } else msg_outtrans(msgbuf); msg_clr_eos(); msg_check(); vim_free(msgbuf); gotocmdline(FALSE); out_flush(); msg_nowait = TRUE; /* don't wait for this message */ } } /* * If there is a character offset, subtract it from the current * position, so we don't get stuck at "?pat?e+2" or "/pat/s-2". * Skip this if pos.col is near MAXCOL (closed fold). * This is not done for a line offset, because then we would not be vi * compatible. */ if (!spats[0].off.line && spats[0].off.off && pos.col < MAXCOL - 2) { if (spats[0].off.off > 0) { for (c = spats[0].off.off; c; --c) if (decl(&pos) == -1) break; if (c) /* at start of buffer */ { pos.lnum = 0; /* allow lnum == 0 here */ pos.col = MAXCOL; } } else { for (c = spats[0].off.off; c; ++c) if (incl(&pos) == -1) break; if (c) /* at end of buffer */ { pos.lnum = curbuf->b_ml.ml_line_count + 1; pos.col = 0; } } } #ifdef FEAT_FKMAP /* when in Farsi mode, reverse the character flow */ if (p_altkeymap && curwin->w_p_rl) lrFswap(searchstr,0); #endif c = searchit(curwin, curbuf, &pos, dirc == '/' ? FORWARD : BACKWARD, searchstr, count, spats[0].off.end + (options & (SEARCH_KEEP + SEARCH_PEEK + SEARCH_HIS + SEARCH_MSG + SEARCH_START + ((pat != NULL && *pat == ';') ? 0 : SEARCH_NOOF))), RE_LAST, (linenr_T)0, tm); if (dircp != NULL) *dircp = dirc; /* restore second '/' or '?' for normal_cmd() */ if (c == FAIL) { retval = 0; goto end_do_search; } if (spats[0].off.end && oap != NULL) oap->inclusive = TRUE; /* 'e' includes last character */ retval = 1; /* pattern found */ /* * Add character and/or line offset */ if (!(options & SEARCH_NOOF) || (pat != NULL && *pat == ';')) { if (spats[0].off.line) /* Add the offset to the line number. */ { c = pos.lnum + spats[0].off.off; if (c < 1) pos.lnum = 1; else if (c > curbuf->b_ml.ml_line_count) pos.lnum = curbuf->b_ml.ml_line_count; else pos.lnum = c; pos.col = 0; retval = 2; /* pattern found, line offset added */ } else if (pos.col < MAXCOL - 2) /* just in case */ { /* to the right, check for end of file */ c = spats[0].off.off; if (c > 0) { while (c-- > 0) if (incl(&pos) == -1) break; } /* to the left, check for start of file */ else { while (c++ < 0) if (decl(&pos) == -1) break; } } } /* * The search command can be followed by a ';' to do another search. * For example: "/pat/;/foo/+3;?bar" * This is like doing another search command, except: * - The remembered direction '/' or '?' is from the first search. * - When an error happens the cursor isn't moved at all. * Don't do this when called by get_address() (it handles ';' itself). */ if (!(options & SEARCH_OPT) || pat == NULL || *pat != ';') break; dirc = *++pat; if (dirc != '?' && dirc != '/') { retval = 0; EMSG(_("E386: Expected '?' or '/' after ';'")); goto end_do_search; } ++pat; } if (options & SEARCH_MARK) setpcmark(); curwin->w_cursor = pos; curwin->w_set_curswant = TRUE; end_do_search: if (options & SEARCH_KEEP) spats[0].off = old_off; vim_free(strcopy); return retval; } #if defined(FEAT_INS_EXPAND) || defined(PROTO) /* * search_for_exact_line(buf, pos, dir, pat) * * Search for a line starting with the given pattern (ignoring leading * white-space), starting from pos and going in direction dir. pos will * contain the position of the match found. Blank lines match only if * ADDING is set. if p_ic is set then the pattern must be in lowercase. * Return OK for success, or FAIL if no line found. */ int search_for_exact_line(buf, pos, dir, pat) buf_T *buf; pos_T *pos; int dir; char_u *pat; { linenr_T start = 0; char_u *ptr; char_u *p; if (buf->b_ml.ml_line_count == 0) return FAIL; for (;;) { pos->lnum += dir; if (pos->lnum < 1) { if (p_ws) { pos->lnum = buf->b_ml.ml_line_count; if (!shortmess(SHM_SEARCH)) give_warning((char_u *)_(top_bot_msg), TRUE); } else { pos->lnum = 1; break; } } else if (pos->lnum > buf->b_ml.ml_line_count) { if (p_ws) { pos->lnum = 1; if (!shortmess(SHM_SEARCH)) give_warning((char_u *)_(bot_top_msg), TRUE); } else { pos->lnum = 1; break; } } if (pos->lnum == start) break; if (start == 0) start = pos->lnum; ptr = ml_get_buf(buf, pos->lnum, FALSE); p = skipwhite(ptr); pos->col = (colnr_T) (p - ptr); /* when adding lines the matching line may be empty but it is not * ignored because we are interested in the next line -- Acevedo */ if ((compl_cont_status & CONT_ADDING) && !(compl_cont_status & CONT_SOL)) { if ((p_ic ? MB_STRICMP(p, pat) : STRCMP(p, pat)) == 0) return OK; } else if (*p != NUL) /* ignore empty lines */ { /* expanding lines or words */ if ((p_ic ? MB_STRNICMP(p, pat, compl_length) : STRNCMP(p, pat, compl_length)) == 0) return OK; } } return FAIL; } #endif /* FEAT_INS_EXPAND */ /* * Character Searches */ /* * Search for a character in a line. If "t_cmd" is FALSE, move to the * position of the character, otherwise move to just before the char. * Do this "cap->count1" times. * Return FAIL or OK. */ int searchc(cap, t_cmd) cmdarg_T *cap; int t_cmd; { int c = cap->nchar; /* char to search for */ int dir = cap->arg; /* TRUE for searching forward */ long count = cap->count1; /* repeat count */ static int lastc = NUL; /* last character searched for */ static int lastcdir; /* last direction of character search */ static int last_t_cmd; /* last search t_cmd */ int col; char_u *p; int len; int stop = TRUE; #ifdef FEAT_MBYTE static char_u bytes[MB_MAXBYTES + 1]; static int bytelen = 1; /* >1 for multi-byte char */ #endif if (c != NUL) /* normal search: remember args for repeat */ { if (!KeyStuffed) /* don't remember when redoing */ { lastc = c; lastcdir = dir; last_t_cmd = t_cmd; #ifdef FEAT_MBYTE bytelen = (*mb_char2bytes)(c, bytes); if (cap->ncharC1 != 0) { bytelen += (*mb_char2bytes)(cap->ncharC1, bytes + bytelen); if (cap->ncharC2 != 0) bytelen += (*mb_char2bytes)(cap->ncharC2, bytes + bytelen); } #endif } } else /* repeat previous search */ { if (lastc == NUL) return FAIL; if (dir) /* repeat in opposite direction */ dir = -lastcdir; else dir = lastcdir; t_cmd = last_t_cmd; c = lastc; /* For multi-byte re-use last bytes[] and bytelen. */ /* Force a move of at least one char, so ";" and "," will move the * cursor, even if the cursor is right in front of char we are looking * at. */ if (vim_strchr(p_cpo, CPO_SCOLON) == NULL && count == 1 && t_cmd) stop = FALSE; } if (dir == BACKWARD) cap->oap->inclusive = FALSE; else cap->oap->inclusive = TRUE; p = ml_get_curline(); col = curwin->w_cursor.col; len = (int)STRLEN(p); while (count--) { #ifdef FEAT_MBYTE if (has_mbyte) { for (;;) { if (dir > 0) { col += (*mb_ptr2len)(p + col); if (col >= len) return FAIL; } else { if (col == 0) return FAIL; col -= (*mb_head_off)(p, p + col - 1) + 1; } if (bytelen == 1) { if (p[col] == c && stop) break; } else { if (vim_memcmp(p + col, bytes, bytelen) == 0 && stop) break; } stop = TRUE; } } else #endif { for (;;) { if ((col += dir) < 0 || col >= len) return FAIL; if (p[col] == c && stop) break; stop = TRUE; } } } if (t_cmd) { /* backup to before the character (possibly double-byte) */ col -= dir; #ifdef FEAT_MBYTE if (has_mbyte) { if (dir < 0) /* Landed on the search char which is bytelen long */ col += bytelen - 1; else /* To previous char, which may be multi-byte. */ col -= (*mb_head_off)(p, p + col); } #endif } curwin->w_cursor.col = col; return OK; } /* * "Other" Searches */ /* * findmatch - find the matching paren or brace * * Improvement over vi: Braces inside quotes are ignored. */ pos_T * findmatch(oap, initc) oparg_T *oap; int initc; { return findmatchlimit(oap, initc, 0, 0); } /* * Return TRUE if the character before "linep[col]" equals "ch". * Return FALSE if "col" is zero. * Update "*prevcol" to the column of the previous character, unless "prevcol" * is NULL. * Handles multibyte string correctly. */ static int check_prevcol(linep, col, ch, prevcol) char_u *linep; int col; int ch; int *prevcol; { --col; #ifdef FEAT_MBYTE if (col > 0 && has_mbyte) col -= (*mb_head_off)(linep, linep + col); #endif if (prevcol) *prevcol = col; return (col >= 0 && linep[col] == ch) ? TRUE : FALSE; } /* * findmatchlimit -- find the matching paren or brace, if it exists within * maxtravel lines of here. A maxtravel of 0 means search until falling off * the edge of the file. * * "initc" is the character to find a match for. NUL means to find the * character at or after the cursor. * * flags: FM_BACKWARD search backwards (when initc is '/', '*' or '#') * FM_FORWARD search forwards (when initc is '/', '*' or '#') * FM_BLOCKSTOP stop at start/end of block ({ or } in column 0) * FM_SKIPCOMM skip comments (not implemented yet!) * * "oap" is only used to set oap->motion_type for a linewise motion, it be * NULL */ pos_T * findmatchlimit(oap, initc, flags, maxtravel) oparg_T *oap; int initc; int flags; int maxtravel; { static pos_T pos; /* current search position */ int findc = 0; /* matching brace */ int c; int count = 0; /* cumulative number of braces */ int backwards = FALSE; /* init for gcc */ int inquote = FALSE; /* TRUE when inside quotes */ char_u *linep; /* pointer to current line */ char_u *ptr; int do_quotes; /* check for quotes in current line */ int at_start; /* do_quotes value at start position */ int hash_dir = 0; /* Direction searched for # things */ int comment_dir = 0; /* Direction searched for comments */ pos_T match_pos; /* Where last slash-star was found */ int start_in_quotes; /* start position is in quotes */ int traveled = 0; /* how far we've searched so far */ int ignore_cend = FALSE; /* ignore comment end */ int cpo_match; /* vi compatible matching */ int cpo_bsl; /* don't recognize backslashes */ int match_escaped = 0; /* search for escaped match */ int dir; /* Direction to search */ int comment_col = MAXCOL; /* start of / / comment */ #ifdef FEAT_LISP int lispcomm = FALSE; /* inside of Lisp-style comment */ int lisp = curbuf->b_p_lisp; /* engage Lisp-specific hacks ;) */ #endif pos = curwin->w_cursor; linep = ml_get(pos.lnum); cpo_match = (vim_strchr(p_cpo, CPO_MATCH) != NULL); cpo_bsl = (vim_strchr(p_cpo, CPO_MATCHBSL) != NULL); /* Direction to search when initc is '/', '*' or '#' */ if (flags & FM_BACKWARD) dir = BACKWARD; else if (flags & FM_FORWARD) dir = FORWARD; else dir = 0; /* * if initc given, look in the table for the matching character * '/' and '*' are special cases: look for start or end of comment. * When '/' is used, we ignore running backwards into an star-slash, for * "[*" command, we just want to find any comment. */ if (initc == '/' || initc == '*') { comment_dir = dir; if (initc == '/') ignore_cend = TRUE; backwards = (dir == FORWARD) ? FALSE : TRUE; initc = NUL; } else if (initc != '#' && initc != NUL) { /* 'matchpairs' is "x:y,x:y" */ for (ptr = curbuf->b_p_mps; *ptr; ptr += 2) { if (*ptr == initc) { findc = initc; initc = ptr[2]; backwards = TRUE; break; } ptr += 2; if (*ptr == initc) { findc = initc; initc = ptr[-2]; backwards = FALSE; break; } if (ptr[1] != ',') break; } if (!findc) /* invalid initc! */ return NULL; } /* * Either initc is '#', or no initc was given and we need to look under the * cursor. */ else { if (initc == '#') { hash_dir = dir; } else { /* * initc was not given, must look for something to match under * or near the cursor. * Only check for special things when 'cpo' doesn't have '%'. */ if (!cpo_match) { /* Are we before or at #if, #else etc.? */ ptr = skipwhite(linep); if (*ptr == '#' && pos.col <= (colnr_T)(ptr - linep)) { ptr = skipwhite(ptr + 1); if ( STRNCMP(ptr, "if", 2) == 0 || STRNCMP(ptr, "endif", 5) == 0 || STRNCMP(ptr, "el", 2) == 0) hash_dir = 1; } /* Are we on a comment? */ else if (linep[pos.col] == '/') { if (linep[pos.col + 1] == '*') { comment_dir = FORWARD; backwards = FALSE; pos.col++; } else if (pos.col > 0 && linep[pos.col - 1] == '*') { comment_dir = BACKWARD; backwards = TRUE; pos.col--; } } else if (linep[pos.col] == '*') { if (linep[pos.col + 1] == '/') { comment_dir = BACKWARD; backwards = TRUE; } else if (pos.col > 0 && linep[pos.col - 1] == '/') { comment_dir = FORWARD; backwards = FALSE; } } } /* * If we are not on a comment or the # at the start of a line, then * look for brace anywhere on this line after the cursor. */ if (!hash_dir && !comment_dir) { /* * Find the brace under or after the cursor. * If beyond the end of the line, use the last character in * the line. */ if (linep[pos.col] == NUL && pos.col) --pos.col; for (;;) { initc = linep[pos.col]; if (initc == NUL) break; for (ptr = curbuf->b_p_mps; *ptr; ++ptr) { if (*ptr == initc) { findc = ptr[2]; backwards = FALSE; break; } ptr += 2; if (*ptr == initc) { findc = ptr[-2]; backwards = TRUE; break; } if (!*++ptr) break; } if (findc) break; #ifdef FEAT_MBYTE if (has_mbyte) pos.col += (*mb_ptr2len)(linep + pos.col); else #endif ++pos.col; } if (!findc) { /* no brace in the line, maybe use " #if" then */ if (!cpo_match && *skipwhite(linep) == '#') hash_dir = 1; else return NULL; } else if (!cpo_bsl) { int col, bslcnt = 0; /* Set "match_escaped" if there are an odd number of * backslashes. */ for (col = pos.col; check_prevcol(linep, col, '\\', &col);) bslcnt++; match_escaped = (bslcnt & 1); } } } if (hash_dir) { /* * Look for matching #if, #else, #elif, or #endif */ if (oap != NULL) oap->motion_type = MLINE; /* Linewise for this case only */ if (initc != '#') { ptr = skipwhite(skipwhite(linep) + 1); if (STRNCMP(ptr, "if", 2) == 0 || STRNCMP(ptr, "el", 2) == 0) hash_dir = 1; else if (STRNCMP(ptr, "endif", 5) == 0) hash_dir = -1; else return NULL; } pos.col = 0; while (!got_int) { if (hash_dir > 0) { if (pos.lnum == curbuf->b_ml.ml_line_count) break; } else if (pos.lnum == 1) break; pos.lnum += hash_dir; linep = ml_get(pos.lnum); line_breakcheck(); /* check for CTRL-C typed */ ptr = skipwhite(linep); if (*ptr != '#') continue; pos.col = (colnr_T) (ptr - linep); ptr = skipwhite(ptr + 1); if (hash_dir > 0) { if (STRNCMP(ptr, "if", 2) == 0) count++; else if (STRNCMP(ptr, "el", 2) == 0) { if (count == 0) return &pos; } else if (STRNCMP(ptr, "endif", 5) == 0) { if (count == 0) return &pos; count--; } } else { if (STRNCMP(ptr, "if", 2) == 0) { if (count == 0) return &pos; count--; } else if (initc == '#' && STRNCMP(ptr, "el", 2) == 0) { if (count == 0) return &pos; } else if (STRNCMP(ptr, "endif", 5) == 0) count++; } } return NULL; } } #ifdef FEAT_RIGHTLEFT /* This is just guessing: when 'rightleft' is set, search for a matching * paren/brace in the other direction. */ if (curwin->w_p_rl && vim_strchr((char_u *)"()[]{}<>", initc) != NULL) backwards = !backwards; #endif do_quotes = -1; start_in_quotes = MAYBE; clearpos(&match_pos); /* backward search: Check if this line contains a single-line comment */ if ((backwards && comment_dir) #ifdef FEAT_LISP || lisp #endif ) comment_col = check_linecomment(linep); #ifdef FEAT_LISP if (lisp && comment_col != MAXCOL && pos.col > (colnr_T)comment_col) lispcomm = TRUE; /* find match inside this comment */ #endif while (!got_int) { /* * Go to the next position, forward or backward. We could use * inc() and dec() here, but that is much slower */ if (backwards) { #ifdef FEAT_LISP /* char to match is inside of comment, don't search outside */ if (lispcomm && pos.col < (colnr_T)comment_col) break; #endif if (pos.col == 0) /* at start of line, go to prev. one */ { if (pos.lnum == 1) /* start of file */ break; --pos.lnum; if (maxtravel > 0 && ++traveled > maxtravel) break; linep = ml_get(pos.lnum); pos.col = (colnr_T)STRLEN(linep); /* pos.col on trailing NUL */ do_quotes = -1; line_breakcheck(); /* Check if this line contains a single-line comment */ if (comment_dir #ifdef FEAT_LISP || lisp #endif ) comment_col = check_linecomment(linep); #ifdef FEAT_LISP /* skip comment */ if (lisp && comment_col != MAXCOL) pos.col = comment_col; #endif } else { --pos.col; #ifdef FEAT_MBYTE if (has_mbyte) pos.col -= (*mb_head_off)(linep, linep + pos.col); #endif } } else /* forward search */ { if (linep[pos.col] == NUL /* at end of line, go to next one */ #ifdef FEAT_LISP /* don't search for match in comment */ || (lisp && comment_col != MAXCOL && pos.col == (colnr_T)comment_col) #endif ) { if (pos.lnum == curbuf->b_ml.ml_line_count /* end of file */ #ifdef FEAT_LISP /* line is exhausted and comment with it, * don't search for match in code */ || lispcomm #endif ) break; ++pos.lnum; if (maxtravel && traveled++ > maxtravel) break; linep = ml_get(pos.lnum); pos.col = 0; do_quotes = -1; line_breakcheck(); #ifdef FEAT_LISP if (lisp) /* find comment pos in new line */ comment_col = check_linecomment(linep); #endif } else { #ifdef FEAT_MBYTE if (has_mbyte) pos.col += (*mb_ptr2len)(linep + pos.col); else #endif ++pos.col; } } /* * If FM_BLOCKSTOP given, stop at a '{' or '}' in column 0. */ if (pos.col == 0 && (flags & FM_BLOCKSTOP) && (linep[0] == '{' || linep[0] == '}')) { if (linep[0] == findc && count == 0) /* match! */ return &pos; break; /* out of scope */ } if (comment_dir) { /* Note: comments do not nest, and we ignore quotes in them */ /* TODO: ignore comment brackets inside strings */ if (comment_dir == FORWARD) { if (linep[pos.col] == '*' && linep[pos.col + 1] == '/') { pos.col++; return &pos; } } else /* Searching backwards */ { /* * A comment may contain / * or / /, it may also start or end * with / * /. Ignore a / * after / /. */ if (pos.col == 0) continue; else if ( linep[pos.col - 1] == '/' && linep[pos.col] == '*' && (int)pos.col < comment_col) { count++; match_pos = pos; match_pos.col--; } else if (linep[pos.col - 1] == '*' && linep[pos.col] == '/') { if (count > 0) pos = match_pos; else if (pos.col > 1 && linep[pos.col - 2] == '/' && (int)pos.col <= comment_col) pos.col -= 2; else if (ignore_cend) continue; else return NULL; return &pos; } } continue; } /* * If smart matching ('cpoptions' does not contain '%'), braces inside * of quotes are ignored, but only if there is an even number of * quotes in the line. */ if (cpo_match) do_quotes = 0; else if (do_quotes == -1) { /* * Count the number of quotes in the line, skipping \" and '"'. * Watch out for "\\". */ at_start = do_quotes; for (ptr = linep; *ptr; ++ptr) { if (ptr == linep + pos.col + backwards) at_start = (do_quotes & 1); if (*ptr == '"' && (ptr == linep || ptr[-1] != '\'' || ptr[1] != '\'')) ++do_quotes; if (*ptr == '\\' && ptr[1] != NUL) ++ptr; } do_quotes &= 1; /* result is 1 with even number of quotes */ /* * If we find an uneven count, check current line and previous * one for a '\' at the end. */ if (!do_quotes) { inquote = FALSE; if (ptr[-1] == '\\') { do_quotes = 1; if (start_in_quotes == MAYBE) { /* Do we need to use at_start here? */ inquote = TRUE; start_in_quotes = TRUE; } else if (backwards) inquote = TRUE; } if (pos.lnum > 1) { ptr = ml_get(pos.lnum - 1); if (*ptr && *(ptr + STRLEN(ptr) - 1) == '\\') { do_quotes = 1; if (start_in_quotes == MAYBE) { inquote = at_start; if (inquote) start_in_quotes = TRUE; } else if (!backwards) inquote = TRUE; } /* ml_get() only keeps one line, need to get linep again */ linep = ml_get(pos.lnum); } } } if (start_in_quotes == MAYBE) start_in_quotes = FALSE; /* * If 'smartmatch' is set: * Things inside quotes are ignored by setting 'inquote'. If we * find a quote without a preceding '\' invert 'inquote'. At the * end of a line not ending in '\' we reset 'inquote'. * * In lines with an uneven number of quotes (without preceding '\') * we do not know which part to ignore. Therefore we only set * inquote if the number of quotes in a line is even, unless this * line or the previous one ends in a '\'. Complicated, isn't it? */ switch (c = linep[pos.col]) { case NUL: /* at end of line without trailing backslash, reset inquote */ if (pos.col == 0 || linep[pos.col - 1] != '\\') { inquote = FALSE; start_in_quotes = FALSE; } break; case '"': /* a quote that is preceded with an odd number of backslashes is * ignored */ if (do_quotes) { int col; for (col = pos.col - 1; col >= 0; --col) if (linep[col] != '\\') break; if ((((int)pos.col - 1 - col) & 1) == 0) { inquote = !inquote; start_in_quotes = FALSE; } } break; /* * If smart matching ('cpoptions' does not contain '%'): * Skip things in single quotes: 'x' or '\x'. Be careful for single * single quotes, eg jon's. Things like '\233' or '\x3f' are not * skipped, there is never a brace in them. * Ignore this when finding matches for `'. */ case '\'': if (!cpo_match && initc != '\'' && findc != '\'') { if (backwards) { if (pos.col > 1) { if (linep[pos.col - 2] == '\'') { pos.col -= 2; break; } else if (linep[pos.col - 2] == '\\' && pos.col > 2 && linep[pos.col - 3] == '\'') { pos.col -= 3; break; } } } else if (linep[pos.col + 1]) /* forward search */ { if (linep[pos.col + 1] == '\\' && linep[pos.col + 2] && linep[pos.col + 3] == '\'') { pos.col += 3; break; } else if (linep[pos.col + 2] == '\'') { pos.col += 2; break; } } } /* FALLTHROUGH */ default: #ifdef FEAT_LISP /* * For Lisp skip over backslashed (), {} and []. * (actually, we skip #\( et al) */ if (curbuf->b_p_lisp && vim_strchr((char_u *)"(){}[]", c) != NULL && pos.col > 1 && check_prevcol(linep, pos.col, '\\', NULL) && check_prevcol(linep, pos.col - 1, '#', NULL)) break; #endif /* Check for match outside of quotes, and inside of * quotes when the start is also inside of quotes. */ if ((!inquote || start_in_quotes == TRUE) && (c == initc || c == findc)) { int col, bslcnt = 0; if (!cpo_bsl) { for (col = pos.col; check_prevcol(linep, col, '\\', &col);) bslcnt++; } /* Only accept a match when 'M' is in 'cpo' or when escaping * is what we expect. */ if (cpo_bsl || (bslcnt & 1) == match_escaped) { if (c == initc) count++; else { if (count == 0) return &pos; count--; } } } } } if (comment_dir == BACKWARD && count > 0) { pos = match_pos; return &pos; } return (pos_T *)NULL; /* never found it */ } /* * Check if line[] contains a / / comment. * Return MAXCOL if not, otherwise return the column. * TODO: skip strings. */ static int check_linecomment(line) char_u *line; { char_u *p; p = line; #ifdef FEAT_LISP /* skip Lispish one-line comments */ if (curbuf->b_p_lisp) { if (vim_strchr(p, ';') != NULL) /* there may be comments */ { int in_str = FALSE; /* inside of string */ p = line; /* scan from start */ while ((p = vim_strpbrk(p, (char_u *)"\";")) != NULL) { if (*p == '"') { if (in_str) { if (*(p - 1) != '\\') /* skip escaped quote */ in_str = FALSE; } else if (p == line || ((p - line) >= 2 /* skip #\" form */ && *(p - 1) != '\\' && *(p - 2) != '#')) in_str = TRUE; } else if (!in_str && ((p - line) < 2 || (*(p - 1) != '\\' && *(p - 2) != '#'))) break; /* found! */ ++p; } } else p = NULL; } else #endif while ((p = vim_strchr(p, '/')) != NULL) { /* accept a double /, unless it's preceded with * and followed by *, * because * / / * is an end and start of a C comment */ if (p[1] == '/' && (p == line || p[-1] != '*' || p[2] != '*')) break; ++p; } if (p == NULL) return MAXCOL; return (int)(p - line); } /* * Move cursor briefly to character matching the one under the cursor. * Used for Insert mode and "r" command. * Show the match only if it is visible on the screen. * If there isn't a match, then beep. */ void showmatch(c) int c; /* char to show match for */ { pos_T *lpos, save_cursor; pos_T mpos; colnr_T vcol; long save_so; long save_siso; #ifdef CURSOR_SHAPE int save_state; #endif colnr_T save_dollar_vcol; char_u *p; /* * Only show match for chars in the 'matchpairs' option. */ /* 'matchpairs' is "x:y,x:y" */ for (p = curbuf->b_p_mps; *p != NUL; p += 2) { #ifdef FEAT_RIGHTLEFT if (*p == c && (curwin->w_p_rl ^ p_ri)) break; #endif p += 2; if (*p == c #ifdef FEAT_RIGHTLEFT && !(curwin->w_p_rl ^ p_ri) #endif ) break; if (p[1] != ',') return; } if ((lpos = findmatch(NULL, NUL)) == NULL) /* no match, so beep */ vim_beep(); else if (lpos->lnum >= curwin->w_topline) { if (!curwin->w_p_wrap) getvcol(curwin, lpos, NULL, &vcol, NULL); if (curwin->w_p_wrap || (vcol >= curwin->w_leftcol && vcol < curwin->w_leftcol + W_WIDTH(curwin))) { mpos = *lpos; /* save the pos, update_screen() may change it */ save_cursor = curwin->w_cursor; save_so = p_so; save_siso = p_siso; /* Handle "$" in 'cpo': If the ')' is typed on top of the "$", * stop displaying the "$". */ if (dollar_vcol >= 0 && dollar_vcol == curwin->w_virtcol) dollar_vcol = -1; ++curwin->w_virtcol; /* do display ')' just before "$" */ update_screen(VALID); /* show the new char first */ save_dollar_vcol = dollar_vcol; #ifdef CURSOR_SHAPE save_state = State; State = SHOWMATCH; ui_cursor_shape(); /* may show different cursor shape */ #endif curwin->w_cursor = mpos; /* move to matching char */ p_so = 0; /* don't use 'scrolloff' here */ p_siso = 0; /* don't use 'sidescrolloff' here */ showruler(FALSE); setcursor(); cursor_on(); /* make sure that the cursor is shown */ out_flush(); #ifdef FEAT_GUI if (gui.in_use) { gui_update_cursor(TRUE, FALSE); gui_mch_flush(); } #endif /* Restore dollar_vcol(), because setcursor() may call curs_rows() * which resets it if the matching position is in a previous line * and has a higher column number. */ dollar_vcol = save_dollar_vcol; /* * brief pause, unless 'm' is present in 'cpo' and a character is * available. */ if (vim_strchr(p_cpo, CPO_SHOWMATCH) != NULL) ui_delay(p_mat * 100L, TRUE); else if (!char_avail()) ui_delay(p_mat * 100L, FALSE); curwin->w_cursor = save_cursor; /* restore cursor position */ p_so = save_so; p_siso = save_siso; #ifdef CURSOR_SHAPE State = save_state; ui_cursor_shape(); /* may show different cursor shape */ #endif } } } /* * findsent(dir, count) - Find the start of the next sentence in direction * "dir" Sentences are supposed to end in ".", "!" or "?" followed by white * space or a line break. Also stop at an empty line. * Return OK if the next sentence was found. */ int findsent(dir, count) int dir; long count; { pos_T pos, tpos; int c; int (*func) __ARGS((pos_T *)); int startlnum; int noskip = FALSE; /* do not skip blanks */ int cpo_J; int found_dot; pos = curwin->w_cursor; if (dir == FORWARD) func = incl; else func = decl; while (count--) { /* * if on an empty line, skip upto a non-empty line */ if (gchar_pos(&pos) == NUL) { do if ((*func)(&pos) == -1) break; while (gchar_pos(&pos) == NUL); if (dir == FORWARD) goto found; } /* * if on the start of a paragraph or a section and searching forward, * go to the next line */ else if (dir == FORWARD && pos.col == 0 && startPS(pos.lnum, NUL, FALSE)) { if (pos.lnum == curbuf->b_ml.ml_line_count) return FAIL; ++pos.lnum; goto found; } else if (dir == BACKWARD) decl(&pos); /* go back to the previous non-blank char */ found_dot = FALSE; while ((c = gchar_pos(&pos)) == ' ' || c == '\t' || (dir == BACKWARD && vim_strchr((char_u *)".!?)]\"'", c) != NULL)) { if (vim_strchr((char_u *)".!?", c) != NULL) { /* Only skip over a '.', '!' and '?' once. */ if (found_dot) break; found_dot = TRUE; } if (decl(&pos) == -1) break; /* when going forward: Stop in front of empty line */ if (lineempty(pos.lnum) && dir == FORWARD) { incl(&pos); goto found; } } /* remember the line where the search started */ startlnum = pos.lnum; cpo_J = vim_strchr(p_cpo, CPO_ENDOFSENT) != NULL; for (;;) /* find end of sentence */ { c = gchar_pos(&pos); if (c == NUL || (pos.col == 0 && startPS(pos.lnum, NUL, FALSE))) { if (dir == BACKWARD && pos.lnum != startlnum) ++pos.lnum; break; } if (c == '.' || c == '!' || c == '?') { tpos = pos; do if ((c = inc(&tpos)) == -1) break; while (vim_strchr((char_u *)")]\"'", c = gchar_pos(&tpos)) != NULL); if (c == -1 || (!cpo_J && (c == ' ' || c == '\t')) || c == NUL || (cpo_J && (c == ' ' && inc(&tpos) >= 0 && gchar_pos(&tpos) == ' '))) { pos = tpos; if (gchar_pos(&pos) == NUL) /* skip NUL at EOL */ inc(&pos); break; } } if ((*func)(&pos) == -1) { if (count) return FAIL; noskip = TRUE; break; } } found: /* skip white space */ while (!noskip && ((c = gchar_pos(&pos)) == ' ' || c == '\t')) if (incl(&pos) == -1) break; } setpcmark(); curwin->w_cursor = pos; return OK; } /* * Find the next paragraph or section in direction 'dir'. * Paragraphs are currently supposed to be separated by empty lines. * If 'what' is NUL we go to the next paragraph. * If 'what' is '{' or '}' we go to the next section. * If 'both' is TRUE also stop at '}'. * Return TRUE if the next paragraph or section was found. */ int findpar(pincl, dir, count, what, both) int *pincl; /* Return: TRUE if last char is to be included */ int dir; long count; int what; int both; { linenr_T curr; int did_skip; /* TRUE after separating lines have been skipped */ int first; /* TRUE on first line */ int posix = (vim_strchr(p_cpo, CPO_PARA) != NULL); #ifdef FEAT_FOLDING linenr_T fold_first; /* first line of a closed fold */ linenr_T fold_last; /* last line of a closed fold */ int fold_skipped; /* TRUE if a closed fold was skipped this iteration */ #endif curr = curwin->w_cursor.lnum; while (count--) { did_skip = FALSE; for (first = TRUE; ; first = FALSE) { if (*ml_get(curr) != NUL) did_skip = TRUE; #ifdef FEAT_FOLDING /* skip folded lines */ fold_skipped = FALSE; if (first && hasFolding(curr, &fold_first, &fold_last)) { curr = ((dir > 0) ? fold_last : fold_first) + dir; fold_skipped = TRUE; } #endif /* POSIX has it's own ideas of what a paragraph boundary is and it * doesn't match historical Vi: It also stops at a "{" in the * first column and at an empty line. */ if (!first && did_skip && (startPS(curr, what, both) || (posix && what == NUL && *ml_get(curr) == '{'))) break; #ifdef FEAT_FOLDING if (fold_skipped) curr -= dir; #endif if ((curr += dir) < 1 || curr > curbuf->b_ml.ml_line_count) { if (count) return FALSE; curr -= dir; break; } } } setpcmark(); if (both && *ml_get(curr) == '}') /* include line with '}' */ ++curr; curwin->w_cursor.lnum = curr; if (curr == curbuf->b_ml.ml_line_count && what != '}') { if ((curwin->w_cursor.col = (colnr_T)STRLEN(ml_get(curr))) != 0) { --curwin->w_cursor.col; *pincl = TRUE; } } else curwin->w_cursor.col = 0; return TRUE; } /* * check if the string 's' is a nroff macro that is in option 'opt' */ static int inmacro(opt, s) char_u *opt; char_u *s; { char_u *macro; for (macro = opt; macro[0]; ++macro) { /* Accept two characters in the option being equal to two characters * in the line. A space in the option matches with a space in the * line or the line having ended. */ if ( (macro[0] == s[0] || (macro[0] == ' ' && (s[0] == NUL || s[0] == ' '))) && (macro[1] == s[1] || ((macro[1] == NUL || macro[1] == ' ') && (s[0] == NUL || s[1] == NUL || s[1] == ' ')))) break; ++macro; if (macro[0] == NUL) break; } return (macro[0] != NUL); } /* * startPS: return TRUE if line 'lnum' is the start of a section or paragraph. * If 'para' is '{' or '}' only check for sections. * If 'both' is TRUE also stop at '}' */ int startPS(lnum, para, both) linenr_T lnum; int para; int both; { char_u *s; s = ml_get(lnum); if (*s == para || *s == '\f' || (both && *s == '}')) return TRUE; if (*s == '.' && (inmacro(p_sections, s + 1) || (!para && inmacro(p_para, s + 1)))) return TRUE; return FALSE; } /* * The following routines do the word searches performed by the 'w', 'W', * 'b', 'B', 'e', and 'E' commands. */ /* * To perform these searches, characters are placed into one of three * classes, and transitions between classes determine word boundaries. * * The classes are: * * 0 - white space * 1 - punctuation * 2 or higher - keyword characters (letters, digits and underscore) */ static int cls_bigword; /* TRUE for "W", "B" or "E" */ /* * cls() - returns the class of character at curwin->w_cursor * * If a 'W', 'B', or 'E' motion is being done (cls_bigword == TRUE), chars * from class 2 and higher are reported as class 1 since only white space * boundaries are of interest. */ static int cls() { int c; c = gchar_cursor(); #ifdef FEAT_FKMAP /* when 'akm' (Farsi mode), take care of Farsi blank */ if (p_altkeymap && c == F_BLANK) return 0; #endif if (c == ' ' || c == '\t' || c == NUL) return 0; #ifdef FEAT_MBYTE if (enc_dbcs != 0 && c > 0xFF) { /* If cls_bigword, report multi-byte chars as class 1. */ if (enc_dbcs == DBCS_KOR && cls_bigword) return 1; /* process code leading/trailing bytes */ return dbcs_class(((unsigned)c >> 8), (c & 0xFF)); } if (enc_utf8) { c = utf_class(c); if (c != 0 && cls_bigword) return 1; return c; } #endif /* If cls_bigword is TRUE, report all non-blanks as class 1. */ if (cls_bigword) return 1; if (vim_iswordc(c)) return 2; return 1; } /* * fwd_word(count, type, eol) - move forward one word * * Returns FAIL if the cursor was already at the end of the file. * If eol is TRUE, last word stops at end of line (for operators). */ int fwd_word(count, bigword, eol) long count; int bigword; /* "W", "E" or "B" */ int eol; { int sclass; /* starting class */ int i; int last_line; #ifdef FEAT_VIRTUALEDIT curwin->w_cursor.coladd = 0; #endif cls_bigword = bigword; while (--count >= 0) { #ifdef FEAT_FOLDING /* When inside a range of folded lines, move to the last char of the * last line. */ if (hasFolding(curwin->w_cursor.lnum, NULL, &curwin->w_cursor.lnum)) coladvance((colnr_T)MAXCOL); #endif sclass = cls(); /* * We always move at least one character, unless on the last * character in the buffer. */ last_line = (curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count); i = inc_cursor(); if (i == -1 || (i >= 1 && last_line)) /* started at last char in file */ return FAIL; if (i >= 1 && eol && count == 0) /* started at last char in line */ return OK; /* * Go one char past end of current word (if any) */ if (sclass != 0) while (cls() == sclass) { i = inc_cursor(); if (i == -1 || (i >= 1 && eol && count == 0)) return OK; } /* * go to next non-white */ while (cls() == 0) { /* * We'll stop if we land on a blank line */ if (curwin->w_cursor.col == 0 && *ml_get_curline() == NUL) break; i = inc_cursor(); if (i == -1 || (i >= 1 && eol && count == 0)) return OK; } } return OK; } /* * bck_word() - move backward 'count' words * * If stop is TRUE and we are already on the start of a word, move one less. * * Returns FAIL if top of the file was reached. */ int bck_word(count, bigword, stop) long count; int bigword; int stop; { int sclass; /* starting class */ #ifdef FEAT_VIRTUALEDIT curwin->w_cursor.coladd = 0; #endif cls_bigword = bigword; while (--count >= 0) { #ifdef FEAT_FOLDING /* When inside a range of folded lines, move to the first char of the * first line. */ if (hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum, NULL)) curwin->w_cursor.col = 0; #endif sclass = cls(); if (dec_cursor() == -1) /* started at start of file */ return FAIL; if (!stop || sclass == cls() || sclass == 0) { /* * Skip white space before the word. * Stop on an empty line. */ while (cls() == 0) { if (curwin->w_cursor.col == 0 && lineempty(curwin->w_cursor.lnum)) goto finished; if (dec_cursor() == -1) /* hit start of file, stop here */ return OK; } /* * Move backward to start of this word. */ if (skip_chars(cls(), BACKWARD)) return OK; } inc_cursor(); /* overshot - forward one */ finished: stop = FALSE; } return OK; } /* * end_word() - move to the end of the word * * There is an apparent bug in the 'e' motion of the real vi. At least on the * System V Release 3 version for the 80386. Unlike 'b' and 'w', the 'e' * motion crosses blank lines. When the real vi crosses a blank line in an * 'e' motion, the cursor is placed on the FIRST character of the next * non-blank line. The 'E' command, however, works correctly. Since this * appears to be a bug, I have not duplicated it here. * * Returns FAIL if end of the file was reached. * * If stop is TRUE and we are already on the end of a word, move one less. * If empty is TRUE stop on an empty line. */ int end_word(count, bigword, stop, empty) long count; int bigword; int stop; int empty; { int sclass; /* starting class */ #ifdef FEAT_VIRTUALEDIT curwin->w_cursor.coladd = 0; #endif cls_bigword = bigword; while (--count >= 0) { #ifdef FEAT_FOLDING /* When inside a range of folded lines, move to the last char of the * last line. */ if (hasFolding(curwin->w_cursor.lnum, NULL, &curwin->w_cursor.lnum)) coladvance((colnr_T)MAXCOL); #endif sclass = cls(); if (inc_cursor() == -1) return FAIL; /* * If we're in the middle of a word, we just have to move to the end * of it. */ if (cls() == sclass && sclass != 0) { /* * Move forward to end of the current word */ if (skip_chars(sclass, FORWARD)) return FAIL; } else if (!stop || sclass == 0) { /* * We were at the end of a word. Go to the end of the next word. * First skip white space, if 'empty' is TRUE, stop at empty line. */ while (cls() == 0) { if (empty && curwin->w_cursor.col == 0 && lineempty(curwin->w_cursor.lnum)) goto finished; if (inc_cursor() == -1) /* hit end of file, stop here */ return FAIL; } /* * Move forward to the end of this word. */ if (skip_chars(cls(), FORWARD)) return FAIL; } dec_cursor(); /* overshot - one char backward */ finished: stop = FALSE; /* we move only one word less */ } return OK; } /* * Move back to the end of the word. * * Returns FAIL if start of the file was reached. */ int bckend_word(count, bigword, eol) long count; int bigword; /* TRUE for "B" */ int eol; /* TRUE: stop at end of line. */ { int sclass; /* starting class */ int i; #ifdef FEAT_VIRTUALEDIT curwin->w_cursor.coladd = 0; #endif cls_bigword = bigword; while (--count >= 0) { sclass = cls(); if ((i = dec_cursor()) == -1) return FAIL; if (eol && i == 1) return OK; /* * Move backward to before the start of this word. */ if (sclass != 0) { while (cls() == sclass) if ((i = dec_cursor()) == -1 || (eol && i == 1)) return OK; } /* * Move backward to end of the previous word */ while (cls() == 0) { if (curwin->w_cursor.col == 0 && lineempty(curwin->w_cursor.lnum)) break; if ((i = dec_cursor()) == -1 || (eol && i == 1)) return OK; } } return OK; } /* * Skip a row of characters of the same class. * Return TRUE when end-of-file reached, FALSE otherwise. */ static int skip_chars(cclass, dir) int cclass; int dir; { while (cls() == cclass) if ((dir == FORWARD ? inc_cursor() : dec_cursor()) == -1) return TRUE; return FALSE; } #ifdef FEAT_TEXTOBJ /* * Go back to the start of the word or the start of white space */ static void back_in_line() { int sclass; /* starting class */ sclass = cls(); for (;;) { if (curwin->w_cursor.col == 0) /* stop at start of line */ break; dec_cursor(); if (cls() != sclass) /* stop at start of word */ { inc_cursor(); break; } } } static void find_first_blank(posp) pos_T *posp; { int c; while (decl(posp) != -1) { c = gchar_pos(posp); if (!vim_iswhite(c)) { incl(posp); break; } } } /* * Skip count/2 sentences and count/2 separating white spaces. */ static void findsent_forward(count, at_start_sent) long count; int at_start_sent; /* cursor is at start of sentence */ { while (count--) { findsent(FORWARD, 1L); if (at_start_sent) find_first_blank(&curwin->w_cursor); if (count == 0 || at_start_sent) decl(&curwin->w_cursor); at_start_sent = !at_start_sent; } } /* * Find word under cursor, cursor at end. * Used while an operator is pending, and in Visual mode. */ int current_word(oap, count, include, bigword) oparg_T *oap; long count; int include; /* TRUE: include word and white space */ int bigword; /* FALSE == word, TRUE == WORD */ { pos_T start_pos; pos_T pos; int inclusive = TRUE; int include_white = FALSE; cls_bigword = bigword; clearpos(&start_pos); #ifdef FEAT_VISUAL /* Correct cursor when 'selection' is exclusive */ if (VIsual_active && *p_sel == 'e' && lt(VIsual, curwin->w_cursor)) dec_cursor(); /* * When Visual mode is not active, or when the VIsual area is only one * character, select the word and/or white space under the cursor. */ if (!VIsual_active || equalpos(curwin->w_cursor, VIsual)) #endif { /* * Go to start of current word or white space. */ back_in_line(); start_pos = curwin->w_cursor; /* * If the start is on white space, and white space should be included * (" word"), or start is not on white space, and white space should * not be included ("word"), find end of word. */ if ((cls() == 0) == include) { if (end_word(1L, bigword, TRUE, TRUE) == FAIL) return FAIL; } else { /* * If the start is not on white space, and white space should be * included ("word "), or start is on white space and white * space should not be included (" "), find start of word. * If we end up in the first column of the next line (single char * word) back up to end of the line. */ fwd_word(1L, bigword, TRUE); if (curwin->w_cursor.col == 0) decl(&curwin->w_cursor); else oneleft(); if (include) include_white = TRUE; } #ifdef FEAT_VISUAL if (VIsual_active) { /* should do something when inclusive == FALSE ! */ VIsual = start_pos; redraw_curbuf_later(INVERTED); /* update the inversion */ } else #endif { oap->start = start_pos; oap->motion_type = MCHAR; } --count; } /* * When count is still > 0, extend with more objects. */ while (count > 0) { inclusive = TRUE; #ifdef FEAT_VISUAL if (VIsual_active && lt(curwin->w_cursor, VIsual)) { /* * In Visual mode, with cursor at start: move cursor back. */ if (decl(&curwin->w_cursor) == -1) return FAIL; if (include != (cls() != 0)) { if (bck_word(1L, bigword, TRUE) == FAIL) return FAIL; } else { if (bckend_word(1L, bigword, TRUE) == FAIL) return FAIL; (void)incl(&curwin->w_cursor); } } else #endif { /* * Move cursor forward one word and/or white area. */ if (incl(&curwin->w_cursor) == -1) return FAIL; if (include != (cls() == 0)) { if (fwd_word(1L, bigword, TRUE) == FAIL && count > 1) return FAIL; /* * If end is just past a new-line, we don't want to include * the first character on the line. * Put cursor on last char of white. */ if (oneleft() == FAIL) inclusive = FALSE; } else { if (end_word(1L, bigword, TRUE, TRUE) == FAIL) return FAIL; } } --count; } if (include_white && (cls() != 0 || (curwin->w_cursor.col == 0 && !inclusive))) { /* * If we don't include white space at the end, move the start * to include some white space there. This makes "daw" work * better on the last word in a sentence (and "2daw" on last-but-one * word). Also when "2daw" deletes "word." at the end of the line * (cursor is at start of next line). * But don't delete white space at start of line (indent). */ pos = curwin->w_cursor; /* save cursor position */ curwin->w_cursor = start_pos; if (oneleft() == OK) { back_in_line(); if (cls() == 0 && curwin->w_cursor.col > 0) { #ifdef FEAT_VISUAL if (VIsual_active) VIsual = curwin->w_cursor; else #endif oap->start = curwin->w_cursor; } } curwin->w_cursor = pos; /* put cursor back at end */ } #ifdef FEAT_VISUAL if (VIsual_active) { if (*p_sel == 'e' && inclusive && ltoreq(VIsual, curwin->w_cursor)) inc_cursor(); if (VIsual_mode == 'V') { VIsual_mode = 'v'; redraw_cmdline = TRUE; /* show mode later */ } } else #endif oap->inclusive = inclusive; return OK; } /* * Find sentence(s) under the cursor, cursor at end. * When Visual active, extend it by one or more sentences. */ int current_sent(oap, count, include) oparg_T *oap; long count; int include; { pos_T start_pos; pos_T pos; int start_blank; int c; int at_start_sent; long ncount; start_pos = curwin->w_cursor; pos = start_pos; findsent(FORWARD, 1L); /* Find start of next sentence. */ #ifdef FEAT_VISUAL /* * When visual area is bigger than one character: Extend it. */ if (VIsual_active && !equalpos(start_pos, VIsual)) { extend: if (lt(start_pos, VIsual)) { /* * Cursor at start of Visual area. * Find out where we are: * - in the white space before a sentence * - in a sentence or just after it * - at the start of a sentence */ at_start_sent = TRUE; decl(&pos); while (lt(pos, curwin->w_cursor)) { c = gchar_pos(&pos); if (!vim_iswhite(c)) { at_start_sent = FALSE; break; } incl(&pos); } if (!at_start_sent) { findsent(BACKWARD, 1L); if (equalpos(curwin->w_cursor, start_pos)) at_start_sent = TRUE; /* exactly at start of sentence */ else /* inside a sentence, go to its end (start of next) */ findsent(FORWARD, 1L); } if (include) /* "as" gets twice as much as "is" */ count *= 2; while (count--) { if (at_start_sent) find_first_blank(&curwin->w_cursor); c = gchar_cursor(); if (!at_start_sent || (!include && !vim_iswhite(c))) findsent(BACKWARD, 1L); at_start_sent = !at_start_sent; } } else { /* * Cursor at end of Visual area. * Find out where we are: * - just before a sentence * - just before or in the white space before a sentence * - in a sentence */ incl(&pos); at_start_sent = TRUE; if (!equalpos(pos, curwin->w_cursor)) /* not just before a sentence */ { at_start_sent = FALSE; while (lt(pos, curwin->w_cursor)) { c = gchar_pos(&pos); if (!vim_iswhite(c)) { at_start_sent = TRUE; break; } incl(&pos); } if (at_start_sent) /* in the sentence */ findsent(BACKWARD, 1L); else /* in/before white before a sentence */ curwin->w_cursor = start_pos; } if (include) /* "as" gets twice as much as "is" */ count *= 2; findsent_forward(count, at_start_sent); if (*p_sel == 'e') ++curwin->w_cursor.col; } return OK; } #endif /* * If cursor started on blank, check if it is just before the start of the * next sentence. */ while (c = gchar_pos(&pos), vim_iswhite(c)) /* vim_iswhite() is a macro */ incl(&pos); if (equalpos(pos, curwin->w_cursor)) { start_blank = TRUE; find_first_blank(&start_pos); /* go back to first blank */ } else { start_blank = FALSE; findsent(BACKWARD, 1L); start_pos = curwin->w_cursor; } if (include) ncount = count * 2; else { ncount = count; if (start_blank) --ncount; } if (ncount > 0) findsent_forward(ncount, TRUE); else decl(&curwin->w_cursor); if (include) { /* * If the blank in front of the sentence is included, exclude the * blanks at the end of the sentence, go back to the first blank. * If there are no trailing blanks, try to include leading blanks. */ if (start_blank) { find_first_blank(&curwin->w_cursor); c = gchar_pos(&curwin->w_cursor); /* vim_iswhite() is a macro */ if (vim_iswhite(c)) decl(&curwin->w_cursor); } else if (c = gchar_cursor(), !vim_iswhite(c)) find_first_blank(&start_pos); } #ifdef FEAT_VISUAL if (VIsual_active) { /* avoid getting stuck with "is" on a single space before a sent. */ if (equalpos(start_pos, curwin->w_cursor)) goto extend; if (*p_sel == 'e') ++curwin->w_cursor.col; VIsual = start_pos; VIsual_mode = 'v'; redraw_curbuf_later(INVERTED); /* update the inversion */ } else #endif { /* include a newline after the sentence, if there is one */ if (incl(&curwin->w_cursor) == -1) oap->inclusive = TRUE; else oap->inclusive = FALSE; oap->start = start_pos; oap->motion_type = MCHAR; } return OK; } /* * Find block under the cursor, cursor at end. * "what" and "other" are two matching parenthesis/paren/etc. */ int current_block(oap, count, include, what, other) oparg_T *oap; long count; int include; /* TRUE == include white space */ int what; /* '(', '{', etc. */ int other; /* ')', '}', etc. */ { pos_T old_pos; pos_T *pos = NULL; pos_T start_pos; pos_T *end_pos; pos_T old_start, old_end; char_u *save_cpo; int sol = FALSE; /* '{' at start of line */ old_pos = curwin->w_cursor; old_end = curwin->w_cursor; /* remember where we started */ old_start = old_end; /* * If we start on '(', '{', ')', '}', etc., use the whole block inclusive. */ #ifdef FEAT_VISUAL if (!VIsual_active || equalpos(VIsual, curwin->w_cursor)) #endif { setpcmark(); if (what == '{') /* ignore indent */ while (inindent(1)) if (inc_cursor() != 0) break; if (gchar_cursor() == what) /* cursor on '(' or '{', move cursor just after it */ ++curwin->w_cursor.col; } #ifdef FEAT_VISUAL else if (lt(VIsual, curwin->w_cursor)) { old_start = VIsual; curwin->w_cursor = VIsual; /* cursor at low end of Visual */ } else old_end = VIsual; #endif /* * Search backwards for unclosed '(', '{', etc.. * Put this position in start_pos. * Ignore quotes here. */ save_cpo = p_cpo; p_cpo = (char_u *)"%"; while (count-- > 0) { if ((pos = findmatch(NULL, what)) == NULL) break; curwin->w_cursor = *pos; start_pos = *pos; /* the findmatch for end_pos will overwrite *pos */ } p_cpo = save_cpo; /* * Search for matching ')', '}', etc. * Put this position in curwin->w_cursor. */ if (pos == NULL || (end_pos = findmatch(NULL, other)) == NULL) { curwin->w_cursor = old_pos; return FAIL; } curwin->w_cursor = *end_pos; /* * Try to exclude the '(', '{', ')', '}', etc. when "include" is FALSE. * If the ending '}' is only preceded by indent, skip that indent. * But only if the resulting area is not smaller than what we started with. */ while (!include) { incl(&start_pos); sol = (curwin->w_cursor.col == 0); decl(&curwin->w_cursor); if (what == '{') while (inindent(1)) { sol = TRUE; if (decl(&curwin->w_cursor) != 0) break; } #ifdef FEAT_VISUAL /* * In Visual mode, when the resulting area is not bigger than what we * started with, extend it to the next block, and then exclude again. */ if (!lt(start_pos, old_start) && !lt(old_end, curwin->w_cursor) && VIsual_active) { curwin->w_cursor = old_start; decl(&curwin->w_cursor); if ((pos = findmatch(NULL, what)) == NULL) { curwin->w_cursor = old_pos; return FAIL; } start_pos = *pos; curwin->w_cursor = *pos; if ((end_pos = findmatch(NULL, other)) == NULL) { curwin->w_cursor = old_pos; return FAIL; } curwin->w_cursor = *end_pos; } else #endif break; } #ifdef FEAT_VISUAL if (VIsual_active) { if (*p_sel == 'e') ++curwin->w_cursor.col; if (sol && gchar_cursor() != NUL) inc(&curwin->w_cursor); /* include the line break */ VIsual = start_pos; VIsual_mode = 'v'; redraw_curbuf_later(INVERTED); /* update the inversion */ showmode(); } else #endif { oap->start = start_pos; oap->motion_type = MCHAR; oap->inclusive = FALSE; if (sol) incl(&curwin->w_cursor); else if (ltoreq(start_pos, curwin->w_cursor)) /* Include the character under the cursor. */ oap->inclusive = TRUE; else /* End is before the start (no text in between <>, [], etc.): don't * operate on any text. */ curwin->w_cursor = start_pos; } return OK; } static int in_html_tag __ARGS((int)); /* * Return TRUE if the cursor is on a "<aaa>" tag. Ignore "<aaa/>". * When "end_tag" is TRUE return TRUE if the cursor is on "</aaa>". */ static int in_html_tag(end_tag) int end_tag; { char_u *line = ml_get_curline(); char_u *p; int c; int lc = NUL; pos_T pos; #ifdef FEAT_MBYTE if (enc_dbcs) { char_u *lp = NULL; /* We search forward until the cursor, because searching backwards is * very slow for DBCS encodings. */ for (p = line; p < line + curwin->w_cursor.col; mb_ptr_adv(p)) if (*p == '>' || *p == '<') { lc = *p; lp = p; } if (*p != '<') /* check for '<' under cursor */ { if (lc != '<') return FALSE; p = lp; } } else #endif { for (p = line + curwin->w_cursor.col; p > line; ) { if (*p == '<') /* find '<' under/before cursor */ break; mb_ptr_back(line, p); if (*p == '>') /* find '>' before cursor */ break; } if (*p != '<') return FALSE; } pos.lnum = curwin->w_cursor.lnum; pos.col = (colnr_T)(p - line); mb_ptr_adv(p); if (end_tag) /* check that there is a '/' after the '<' */ return *p == '/'; /* check that there is no '/' after the '<' */ if (*p == '/') return FALSE; /* check that the matching '>' is not preceded by '/' */ for (;;) { if (inc(&pos) < 0) return FALSE; c = *ml_get_pos(&pos); if (c == '>') break; lc = c; } return lc != '/'; } /* * Find tag block under the cursor, cursor at end. */ int current_tagblock(oap, count_arg, include) oparg_T *oap; long count_arg; int include; /* TRUE == include white space */ { long count = count_arg; long n; pos_T old_pos; pos_T start_pos; pos_T end_pos; pos_T old_start, old_end; char_u *spat, *epat; char_u *p; char_u *cp; int len; int r; int do_include = include; int save_p_ws = p_ws; int retval = FAIL; p_ws = FALSE; old_pos = curwin->w_cursor; old_end = curwin->w_cursor; /* remember where we started */ old_start = old_end; #ifdef FEAT_VISUAL if (!VIsual_active || *p_sel == 'e') #endif decl(&old_end); /* old_end is inclusive */ /* * If we start on "<aaa>" select that block. */ #ifdef FEAT_VISUAL if (!VIsual_active || equalpos(VIsual, curwin->w_cursor)) #endif { setpcmark(); /* ignore indent */ while (inindent(1)) if (inc_cursor() != 0) break; if (in_html_tag(FALSE)) { /* cursor on start tag, move to its '>' */ while (*ml_get_cursor() != '>') if (inc_cursor() < 0) break; } else if (in_html_tag(TRUE)) { /* cursor on end tag, move to just before it */ while (*ml_get_cursor() != '<') if (dec_cursor() < 0) break; dec_cursor(); old_end = curwin->w_cursor; } } #ifdef FEAT_VISUAL else if (lt(VIsual, curwin->w_cursor)) { old_start = VIsual; curwin->w_cursor = VIsual; /* cursor at low end of Visual */ } else old_end = VIsual; #endif again: /* * Search backwards for unclosed "<aaa>". * Put this position in start_pos. */ for (n = 0; n < count; ++n) { if (do_searchpair((char_u *)"<[^ \t>/!]\\+\\%(\\_s\\_[^>]\\{-}[^/]>\\|$\\|\\_s\\=>\\)", (char_u *)"", (char_u *)"</[^>]*>", BACKWARD, (char_u *)"", 0, NULL, (linenr_T)0, 0L) <= 0) { curwin->w_cursor = old_pos; goto theend; } } start_pos = curwin->w_cursor; /* * Search for matching "</aaa>". First isolate the "aaa". */ inc_cursor(); p = ml_get_cursor(); for (cp = p; *cp != NUL && *cp != '>' && !vim_iswhite(*cp); mb_ptr_adv(cp)) ; len = (int)(cp - p); if (len == 0) { curwin->w_cursor = old_pos; goto theend; } spat = alloc(len + 31); epat = alloc(len + 9); if (spat == NULL || epat == NULL) { vim_free(spat); vim_free(epat); curwin->w_cursor = old_pos; goto theend; } sprintf((char *)spat, "<%.*s\\>\\%%(\\s\\_[^>]\\{-}[^/]>\\|>\\)\\c", len, p); sprintf((char *)epat, "</%.*s>\\c", len, p); r = do_searchpair(spat, (char_u *)"", epat, FORWARD, (char_u *)"", 0, NULL, (linenr_T)0, 0L); vim_free(spat); vim_free(epat); if (r < 1 || lt(curwin->w_cursor, old_end)) { /* Can't find other end or it's before the previous end. Could be a * HTML tag that doesn't have a matching end. Search backwards for * another starting tag. */ count = 1; curwin->w_cursor = start_pos; goto again; } if (do_include || r < 1) { /* Include up to the '>'. */ while (*ml_get_cursor() != '>') if (inc_cursor() < 0) break; } else { /* Exclude the '<' of the end tag. */ if (*ml_get_cursor() == '<') dec_cursor(); } end_pos = curwin->w_cursor; if (!do_include) { /* Exclude the start tag. */ curwin->w_cursor = start_pos; while (inc_cursor() >= 0) if (*ml_get_cursor() == '>') { inc_cursor(); start_pos = curwin->w_cursor; break; } curwin->w_cursor = end_pos; /* If we now have the same text as before reset "do_include" and try * again. */ if (equalpos(start_pos, old_start) && equalpos(end_pos, old_end)) { do_include = TRUE; curwin->w_cursor = old_start; count = count_arg; goto again; } } #ifdef FEAT_VISUAL if (VIsual_active) { /* If the end is before the start there is no text between tags, select * the char under the cursor. */ if (lt(end_pos, start_pos)) curwin->w_cursor = start_pos; else if (*p_sel == 'e') ++curwin->w_cursor.col; VIsual = start_pos; VIsual_mode = 'v'; redraw_curbuf_later(INVERTED); /* update the inversion */ showmode(); } else #endif { oap->start = start_pos; oap->motion_type = MCHAR; if (lt(end_pos, start_pos)) { /* End is before the start: there is no text between tags; operate * on an empty area. */ curwin->w_cursor = start_pos; oap->inclusive = FALSE; } else oap->inclusive = TRUE; } retval = OK; theend: p_ws = save_p_ws; return retval; } int current_par(oap, count, include, type) oparg_T *oap; long count; int include; /* TRUE == include white space */ int type; /* 'p' for paragraph, 'S' for section */ { linenr_T start_lnum; linenr_T end_lnum; int white_in_front; int dir; int start_is_white; int prev_start_is_white; int retval = OK; int do_white = FALSE; int t; int i; if (type == 'S') /* not implemented yet */ return FAIL; start_lnum = curwin->w_cursor.lnum; #ifdef FEAT_VISUAL /* * When visual area is more than one line: extend it. */ if (VIsual_active && start_lnum != VIsual.lnum) { extend: if (start_lnum < VIsual.lnum) dir = BACKWARD; else dir = FORWARD; for (i = count; --i >= 0; ) { if (start_lnum == (dir == BACKWARD ? 1 : curbuf->b_ml.ml_line_count)) { retval = FAIL; break; } prev_start_is_white = -1; for (t = 0; t < 2; ++t) { start_lnum += dir; start_is_white = linewhite(start_lnum); if (prev_start_is_white == start_is_white) { start_lnum -= dir; break; } for (;;) { if (start_lnum == (dir == BACKWARD ? 1 : curbuf->b_ml.ml_line_count)) break; if (start_is_white != linewhite(start_lnum + dir) || (!start_is_white && startPS(start_lnum + (dir > 0 ? 1 : 0), 0, 0))) break; start_lnum += dir; } if (!include) break; if (start_lnum == (dir == BACKWARD ? 1 : curbuf->b_ml.ml_line_count)) break; prev_start_is_white = start_is_white; } } curwin->w_cursor.lnum = start_lnum; curwin->w_cursor.col = 0; return retval; } #endif /* * First move back to the start_lnum of the paragraph or white lines */ white_in_front = linewhite(start_lnum); while (start_lnum > 1) { if (white_in_front) /* stop at first white line */ { if (!linewhite(start_lnum - 1)) break; } else /* stop at first non-white line of start of paragraph */ { if (linewhite(start_lnum - 1) || startPS(start_lnum, 0, 0)) break; } --start_lnum; } /* * Move past the end of any white lines. */ end_lnum = start_lnum; while (end_lnum <= curbuf->b_ml.ml_line_count && linewhite(end_lnum)) ++end_lnum; --end_lnum; i = count; if (!include && white_in_front) --i; while (i--) { if (end_lnum == curbuf->b_ml.ml_line_count) return FAIL; if (!include) do_white = linewhite(end_lnum + 1); if (include || !do_white) { ++end_lnum; /* * skip to end of paragraph */ while (end_lnum < curbuf->b_ml.ml_line_count && !linewhite(end_lnum + 1) && !startPS(end_lnum + 1, 0, 0)) ++end_lnum; } if (i == 0 && white_in_front && include) break; /* * skip to end of white lines after paragraph */ if (include || do_white) while (end_lnum < curbuf->b_ml.ml_line_count && linewhite(end_lnum + 1)) ++end_lnum; } /* * If there are no empty lines at the end, try to find some empty lines at * the start (unless that has been done already). */ if (!white_in_front && !linewhite(end_lnum) && include) while (start_lnum > 1 && linewhite(start_lnum - 1)) --start_lnum; #ifdef FEAT_VISUAL if (VIsual_active) { /* Problem: when doing "Vipipip" nothing happens in a single white * line, we get stuck there. Trap this here. */ if (VIsual_mode == 'V' && start_lnum == curwin->w_cursor.lnum) goto extend; VIsual.lnum = start_lnum; VIsual_mode = 'V'; redraw_curbuf_later(INVERTED); /* update the inversion */ showmode(); } else #endif { oap->start.lnum = start_lnum; oap->start.col = 0; oap->motion_type = MLINE; } curwin->w_cursor.lnum = end_lnum; curwin->w_cursor.col = 0; return OK; } static int find_next_quote __ARGS((char_u *top_ptr, int col, int quotechar, char_u *escape)); static int find_prev_quote __ARGS((char_u *line, int col_start, int quotechar, char_u *escape)); /* * Search quote char from string line[col]. * Quote character escaped by one of the characters in "escape" is not counted * as a quote. * Returns column number of "quotechar" or -1 when not found. */ static int find_next_quote(line, col, quotechar, escape) char_u *line; int col; int quotechar; char_u *escape; /* escape characters, can be NULL */ { int c; for (;;) { c = line[col]; if (c == NUL) return -1; else if (escape != NULL && vim_strchr(escape, c)) ++col; else if (c == quotechar) break; #ifdef FEAT_MBYTE if (has_mbyte) col += (*mb_ptr2len)(line + col); else #endif ++col; } return col; } /* * Search backwards in "line" from column "col_start" to find "quotechar". * Quote character escaped by one of the characters in "escape" is not counted * as a quote. * Return the found column or zero. */ static int find_prev_quote(line, col_start, quotechar, escape) char_u *line; int col_start; int quotechar; char_u *escape; /* escape characters, can be NULL */ { int n; while (col_start > 0) { --col_start; #ifdef FEAT_MBYTE col_start -= (*mb_head_off)(line, line + col_start); #endif n = 0; if (escape != NULL) while (col_start - n > 0 && vim_strchr(escape, line[col_start - n - 1]) != NULL) ++n; if (n & 1) col_start -= n; /* uneven number of escape chars, skip it */ else if (line[col_start] == quotechar) break; } return col_start; } /* * Find quote under the cursor, cursor at end. * Returns TRUE if found, else FALSE. */ int current_quote(oap, count, include, quotechar) oparg_T *oap; long count; int include; /* TRUE == include quote char */ int quotechar; /* Quote character */ { char_u *line = ml_get_curline(); int col_end; int col_start = curwin->w_cursor.col; int inclusive = FALSE; #ifdef FEAT_VISUAL int vis_empty = TRUE; /* Visual selection <= 1 char */ int vis_bef_curs = FALSE; /* Visual starts before cursor */ int inside_quotes = FALSE; /* Looks like "i'" done before */ int selected_quote = FALSE; /* Has quote inside selection */ int i; /* Correct cursor when 'selection' is exclusive */ if (VIsual_active) { vis_bef_curs = lt(VIsual, curwin->w_cursor); if (*p_sel == 'e' && vis_bef_curs) dec_cursor(); vis_empty = equalpos(VIsual, curwin->w_cursor); } if (!vis_empty) { /* Check if the existing selection exactly spans the text inside * quotes. */ if (vis_bef_curs) { inside_quotes = VIsual.col > 0 && line[VIsual.col - 1] == quotechar && line[curwin->w_cursor.col] != NUL && line[curwin->w_cursor.col + 1] == quotechar; i = VIsual.col; col_end = curwin->w_cursor.col; } else { inside_quotes = curwin->w_cursor.col > 0 && line[curwin->w_cursor.col - 1] == quotechar && line[VIsual.col] != NUL && line[VIsual.col + 1] == quotechar; i = curwin->w_cursor.col; col_end = VIsual.col; } /* Find out if we have a quote in the selection. */ while (i <= col_end) if (line[i++] == quotechar) { selected_quote = TRUE; break; } } if (!vis_empty && line[col_start] == quotechar) { /* Already selecting something and on a quote character. Find the * next quoted string. */ if (vis_bef_curs) { /* Assume we are on a closing quote: move to after the next * opening quote. */ col_start = find_next_quote(line, col_start + 1, quotechar, NULL); if (col_start < 0) return FALSE; col_end = find_next_quote(line, col_start + 1, quotechar, curbuf->b_p_qe); if (col_end < 0) { /* We were on a starting quote perhaps? */ col_end = col_start; col_start = curwin->w_cursor.col; } } else { col_end = find_prev_quote(line, col_start, quotechar, NULL); if (line[col_end] != quotechar) return FALSE; col_start = find_prev_quote(line, col_end, quotechar, curbuf->b_p_qe); if (line[col_start] != quotechar) { /* We were on an ending quote perhaps? */ col_start = col_end; col_end = curwin->w_cursor.col; } } } else #endif if (line[col_start] == quotechar #ifdef FEAT_VISUAL || !vis_empty #endif ) { int first_col = col_start; #ifdef FEAT_VISUAL if (!vis_empty) { if (vis_bef_curs) first_col = find_next_quote(line, col_start, quotechar, NULL); else first_col = find_prev_quote(line, col_start, quotechar, NULL); } #endif /* The cursor is on a quote, we don't know if it's the opening or * closing quote. Search from the start of the line to find out. * Also do this when there is a Visual area, a' may leave the cursor * in between two strings. */ col_start = 0; for (;;) { /* Find open quote character. */ col_start = find_next_quote(line, col_start, quotechar, NULL); if (col_start < 0 || col_start > first_col) return FALSE; /* Find close quote character. */ col_end = find_next_quote(line, col_start + 1, quotechar, curbuf->b_p_qe); if (col_end < 0) return FALSE; /* If is cursor between start and end quote character, it is * target text object. */ if (col_start <= first_col && first_col <= col_end) break; col_start = col_end + 1; } } else { /* Search backward for a starting quote. */ col_start = find_prev_quote(line, col_start, quotechar, curbuf->b_p_qe); if (line[col_start] != quotechar) { /* No quote before the cursor, look after the cursor. */ col_start = find_next_quote(line, col_start, quotechar, NULL); if (col_start < 0) return FALSE; } /* Find close quote character. */ col_end = find_next_quote(line, col_start + 1, quotechar, curbuf->b_p_qe); if (col_end < 0) return FALSE; } /* When "include" is TRUE, include spaces after closing quote or before * the starting quote. */ if (include) { if (vim_iswhite(line[col_end + 1])) while (vim_iswhite(line[col_end + 1])) ++col_end; else while (col_start > 0 && vim_iswhite(line[col_start - 1])) --col_start; } /* Set start position. After vi" another i" must include the ". * For v2i" include the quotes. */ if (!include && count < 2 #ifdef FEAT_VISUAL && (vis_empty || !inside_quotes) #endif ) ++col_start; curwin->w_cursor.col = col_start; #ifdef FEAT_VISUAL if (VIsual_active) { /* Set the start of the Visual area when the Visual area was empty, we * were just inside quotes or the Visual area didn't start at a quote * and didn't include a quote. */ if (vis_empty || (vis_bef_curs && !selected_quote && (inside_quotes || (line[VIsual.col] != quotechar && (VIsual.col == 0 || line[VIsual.col - 1] != quotechar))))) { VIsual = curwin->w_cursor; redraw_curbuf_later(INVERTED); } } else #endif { oap->start = curwin->w_cursor; oap->motion_type = MCHAR; } /* Set end position. */ curwin->w_cursor.col = col_end; if ((include || count > 1 #ifdef FEAT_VISUAL /* After vi" another i" must include the ". */ || (!vis_empty && inside_quotes) #endif ) && inc_cursor() == 2) inclusive = TRUE; #ifdef FEAT_VISUAL if (VIsual_active) { if (vis_empty || vis_bef_curs) { /* decrement cursor when 'selection' is not exclusive */ if (*p_sel != 'e') dec_cursor(); } else { /* Cursor is at start of Visual area. Set the end of the Visual * area when it was just inside quotes or it didn't end at a * quote. */ if (inside_quotes || (!selected_quote && line[VIsual.col] != quotechar && (line[VIsual.col] == NUL || line[VIsual.col + 1] != quotechar))) { dec_cursor(); VIsual = curwin->w_cursor; } curwin->w_cursor.col = col_start; } if (VIsual_mode == 'V') { VIsual_mode = 'v'; redraw_cmdline = TRUE; /* show mode later */ } } else #endif { /* Set inclusive and other oap's flags. */ oap->inclusive = inclusive; } return OK; } #endif /* FEAT_TEXTOBJ */ #if defined(FEAT_LISP) || defined(FEAT_CINDENT) || defined(FEAT_TEXTOBJ) \ || defined(PROTO) /* * return TRUE if line 'lnum' is empty or has white chars only. */ int linewhite(lnum) linenr_T lnum; { char_u *p; p = skipwhite(ml_get(lnum)); return (*p == NUL); } #endif #if defined(FEAT_FIND_ID) || defined(PROTO) /* * Find identifiers or defines in included files. * If p_ic && (compl_cont_status & CONT_SOL) then ptr must be in lowercase. */ void find_pattern_in_path(ptr, dir, len, whole, skip_comments, type, count, action, start_lnum, end_lnum) char_u *ptr; /* pointer to search pattern */ int dir UNUSED; /* direction of expansion */ int len; /* length of search pattern */ int whole; /* match whole words only */ int skip_comments; /* don't match inside comments */ int type; /* Type of search; are we looking for a type? a macro? */ long count; int action; /* What to do when we find it */ linenr_T start_lnum; /* first line to start searching */ linenr_T end_lnum; /* last line for searching */ { SearchedFile *files; /* Stack of included files */ SearchedFile *bigger; /* When we need more space */ int max_path_depth = 50; long match_count = 1; char_u *pat; char_u *new_fname; char_u *curr_fname = curbuf->b_fname; char_u *prev_fname = NULL; linenr_T lnum; int depth; int depth_displayed; /* For type==CHECK_PATH */ int old_files; int already_searched; char_u *file_line; char_u *line; char_u *p; char_u save_char; int define_matched; regmatch_T regmatch; regmatch_T incl_regmatch; regmatch_T def_regmatch; int matched = FALSE; int did_show = FALSE; int found = FALSE; int i; char_u *already = NULL; char_u *startp = NULL; char_u *inc_opt = NULL; #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX) win_T *curwin_save = NULL; #endif regmatch.regprog = NULL; incl_regmatch.regprog = NULL; def_regmatch.regprog = NULL; file_line = alloc(LSIZE); if (file_line == NULL) return; if (type != CHECK_PATH && type != FIND_DEFINE #ifdef FEAT_INS_EXPAND /* when CONT_SOL is set compare "ptr" with the beginning of the line * is faster than quote_meta/regcomp/regexec "ptr" -- Acevedo */ && !(compl_cont_status & CONT_SOL) #endif ) { pat = alloc(len + 5); if (pat == NULL) goto fpip_end; sprintf((char *)pat, whole ? "\\<%.*s\\>" : "%.*s", len, ptr); /* ignore case according to p_ic, p_scs and pat */ regmatch.rm_ic = ignorecase(pat); regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0); vim_free(pat); if (regmatch.regprog == NULL) goto fpip_end; } inc_opt = (*curbuf->b_p_inc == NUL) ? p_inc : curbuf->b_p_inc; if (*inc_opt != NUL) { incl_regmatch.regprog = vim_regcomp(inc_opt, p_magic ? RE_MAGIC : 0); if (incl_regmatch.regprog == NULL) goto fpip_end; incl_regmatch.rm_ic = FALSE; /* don't ignore case in incl. pat. */ } if (type == FIND_DEFINE && (*curbuf->b_p_def != NUL || *p_def != NUL)) { def_regmatch.regprog = vim_regcomp(*curbuf->b_p_def == NUL ? p_def : curbuf->b_p_def, p_magic ? RE_MAGIC : 0); if (def_regmatch.regprog == NULL) goto fpip_end; def_regmatch.rm_ic = FALSE; /* don't ignore case in define pat. */ } files = (SearchedFile *)lalloc_clear((long_u) (max_path_depth * sizeof(SearchedFile)), TRUE); if (files == NULL) goto fpip_end; old_files = max_path_depth; depth = depth_displayed = -1; lnum = start_lnum; if (end_lnum > curbuf->b_ml.ml_line_count) end_lnum = curbuf->b_ml.ml_line_count; if (lnum > end_lnum) /* do at least one line */ lnum = end_lnum; line = ml_get(lnum); for (;;) { if (incl_regmatch.regprog != NULL && vim_regexec(&incl_regmatch, line, (colnr_T)0)) { char_u *p_fname = (curr_fname == curbuf->b_fname) ? curbuf->b_ffname : curr_fname; if (inc_opt != NULL && strstr((char *)inc_opt, "\\zs") != NULL) /* Use text from '\zs' to '\ze' (or end) of 'include'. */ new_fname = find_file_name_in_path(incl_regmatch.startp[0], (int)(incl_regmatch.endp[0] - incl_regmatch.startp[0]), FNAME_EXP|FNAME_INCL|FNAME_REL, 1L, p_fname); else /* Use text after match with 'include'. */ new_fname = file_name_in_line(incl_regmatch.endp[0], 0, FNAME_EXP|FNAME_INCL|FNAME_REL, 1L, p_fname, NULL); already_searched = FALSE; if (new_fname != NULL) { /* Check whether we have already searched in this file */ for (i = 0;; i++) { if (i == depth + 1) i = old_files; if (i == max_path_depth) break; if (fullpathcmp(new_fname, files[i].name, TRUE) & FPC_SAME) { if (type != CHECK_PATH && action == ACTION_SHOW_ALL && files[i].matched) { msg_putchar('\n'); /* cursor below last one */ if (!got_int) /* don't display if 'q' typed at "--more--" message */ { msg_home_replace_hl(new_fname); MSG_PUTS(_(" (includes previously listed match)")); prev_fname = NULL; } } vim_free(new_fname); new_fname = NULL; already_searched = TRUE; break; } } } if (type == CHECK_PATH && (action == ACTION_SHOW_ALL || (new_fname == NULL && !already_searched))) { if (did_show) msg_putchar('\n'); /* cursor below last one */ else { gotocmdline(TRUE); /* cursor at status line */ MSG_PUTS_TITLE(_("--- Included files ")); if (action != ACTION_SHOW_ALL) MSG_PUTS_TITLE(_("not found ")); MSG_PUTS_TITLE(_("in path ---\n")); } did_show = TRUE; while (depth_displayed < depth && !got_int) { ++depth_displayed; for (i = 0; i < depth_displayed; i++) MSG_PUTS(" "); msg_home_replace(files[depth_displayed].name); MSG_PUTS(" -->\n"); } if (!got_int) /* don't display if 'q' typed for "--more--" message */ { for (i = 0; i <= depth_displayed; i++) MSG_PUTS(" "); if (new_fname != NULL) { /* using "new_fname" is more reliable, e.g., when * 'includeexpr' is set. */ msg_outtrans_attr(new_fname, hl_attr(HLF_D)); } else { /* * Isolate the file name. * Include the surrounding "" or <> if present. */ for (p = incl_regmatch.endp[0]; !vim_isfilec(*p); p++) ; for (i = 0; vim_isfilec(p[i]); i++) ; if (i == 0) { /* Nothing found, use the rest of the line. */ p = incl_regmatch.endp[0]; i = (int)STRLEN(p); } else { if (p[-1] == '"' || p[-1] == '<') { --p; ++i; } if (p[i] == '"' || p[i] == '>') ++i; } save_char = p[i]; p[i] = NUL; msg_outtrans_attr(p, hl_attr(HLF_D)); p[i] = save_char; } if (new_fname == NULL && action == ACTION_SHOW_ALL) { if (already_searched) MSG_PUTS(_(" (Already listed)")); else MSG_PUTS(_(" NOT FOUND")); } } out_flush(); /* output each line directly */ } if (new_fname != NULL) { /* Push the new file onto the file stack */ if (depth + 1 == old_files) { bigger = (SearchedFile *)lalloc((long_u)( max_path_depth * 2 * sizeof(SearchedFile)), TRUE); if (bigger != NULL) { for (i = 0; i <= depth; i++) bigger[i] = files[i]; for (i = depth + 1; i < old_files + max_path_depth; i++) { bigger[i].fp = NULL; bigger[i].name = NULL; bigger[i].lnum = 0; bigger[i].matched = FALSE; } for (i = old_files; i < max_path_depth; i++) bigger[i + max_path_depth] = files[i]; old_files += max_path_depth; max_path_depth *= 2; vim_free(files); files = bigger; } } if ((files[depth + 1].fp = mch_fopen((char *)new_fname, "r")) == NULL) vim_free(new_fname); else { if (++depth == old_files) { /* * lalloc() for 'bigger' must have failed above. We * will forget one of our already visited files now. */ vim_free(files[old_files].name); ++old_files; } files[depth].name = curr_fname = new_fname; files[depth].lnum = 0; files[depth].matched = FALSE; #ifdef FEAT_INS_EXPAND if (action == ACTION_EXPAND) { msg_hist_off = TRUE; /* reset in msg_trunc_attr() */ vim_snprintf((char*)IObuff, IOSIZE, _("Scanning included file: %s"), (char *)new_fname); msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R)); } else #endif if (p_verbose >= 5) { verbose_enter(); smsg((char_u *)_("Searching included file %s"), (char *)new_fname); verbose_leave(); } } } } else { /* * Check if the line is a define (type == FIND_DEFINE) */ p = line; search_line: define_matched = FALSE; if (def_regmatch.regprog != NULL && vim_regexec(&def_regmatch, line, (colnr_T)0)) { /* * Pattern must be first identifier after 'define', so skip * to that position before checking for match of pattern. Also * don't let it match beyond the end of this identifier. */ p = def_regmatch.endp[0]; while (*p && !vim_iswordc(*p)) p++; define_matched = TRUE; } /* * Look for a match. Don't do this if we are looking for a * define and this line didn't match define_prog above. */ if (def_regmatch.regprog == NULL || define_matched) { if (define_matched #ifdef FEAT_INS_EXPAND || (compl_cont_status & CONT_SOL) #endif ) { /* compare the first "len" chars from "ptr" */ startp = skipwhite(p); if (p_ic) matched = !MB_STRNICMP(startp, ptr, len); else matched = !STRNCMP(startp, ptr, len); if (matched && define_matched && whole && vim_iswordc(startp[len])) matched = FALSE; } else if (regmatch.regprog != NULL && vim_regexec(&regmatch, line, (colnr_T)(p - line))) { matched = TRUE; startp = regmatch.startp[0]; /* * Check if the line is not a comment line (unless we are * looking for a define). A line starting with "# define" * is not considered to be a comment line. */ if (!define_matched && skip_comments) { #ifdef FEAT_COMMENTS if ((*line != '#' || STRNCMP(skipwhite(line + 1), "define", 6) != 0) && get_leader_len(line, NULL, FALSE, TRUE)) matched = FALSE; /* * Also check for a "/ *" or "/ /" before the match. * Skips lines like "int backwards; / * normal index * * /" when looking for "normal". * Note: Doesn't skip "/ *" in comments. */ p = skipwhite(line); if (matched || (p[0] == '/' && p[1] == '*') || p[0] == '*') #endif for (p = line; *p && p < startp; ++p) { if (matched && p[0] == '/' && (p[1] == '*' || p[1] == '/')) { matched = FALSE; /* After "//" all text is comment */ if (p[1] == '/') break; ++p; } else if (!matched && p[0] == '*' && p[1] == '/') { /* Can find match after "* /". */ matched = TRUE; ++p; } } } } } } if (matched) { #ifdef FEAT_INS_EXPAND if (action == ACTION_EXPAND) { int reuse = 0; int add_r; char_u *aux; if (depth == -1 && lnum == curwin->w_cursor.lnum) break; found = TRUE; aux = p = startp; if (compl_cont_status & CONT_ADDING) { p += compl_length; if (vim_iswordp(p)) goto exit_matched; p = find_word_start(p); } p = find_word_end(p); i = (int)(p - aux); if ((compl_cont_status & CONT_ADDING) && i == compl_length) { /* IOSIZE > compl_length, so the STRNCPY works */ STRNCPY(IObuff, aux, i); /* Get the next line: when "depth" < 0 from the current * buffer, otherwise from the included file. Jump to * exit_matched when past the last line. */ if (depth < 0) { if (lnum >= end_lnum) goto exit_matched; line = ml_get(++lnum); } else if (vim_fgets(line = file_line, LSIZE, files[depth].fp)) goto exit_matched; /* we read a line, set "already" to check this "line" later * if depth >= 0 we'll increase files[depth].lnum far * bellow -- Acevedo */ already = aux = p = skipwhite(line); p = find_word_start(p); p = find_word_end(p); if (p > aux) { if (*aux != ')' && IObuff[i-1] != TAB) { if (IObuff[i-1] != ' ') IObuff[i++] = ' '; /* IObuf =~ "\(\k\|\i\).* ", thus i >= 2*/ if (p_js && (IObuff[i-2] == '.' || (vim_strchr(p_cpo, CPO_JOINSP) == NULL && (IObuff[i-2] == '?' || IObuff[i-2] == '!')))) IObuff[i++] = ' '; } /* copy as much as possible of the new word */ if (p - aux >= IOSIZE - i) p = aux + IOSIZE - i - 1; STRNCPY(IObuff + i, aux, p - aux); i += (int)(p - aux); reuse |= CONT_S_IPOS; } IObuff[i] = NUL; aux = IObuff; if (i == compl_length) goto exit_matched; } add_r = ins_compl_add_infercase(aux, i, p_ic, curr_fname == curbuf->b_fname ? NULL : curr_fname, dir, reuse); if (add_r == OK) /* if dir was BACKWARD then honor it just once */ dir = FORWARD; else if (add_r == FAIL) break; } else #endif if (action == ACTION_SHOW_ALL) { found = TRUE; if (!did_show) gotocmdline(TRUE); /* cursor at status line */ if (curr_fname != prev_fname) { if (did_show) msg_putchar('\n'); /* cursor below last one */ if (!got_int) /* don't display if 'q' typed at "--more--" message */ msg_home_replace_hl(curr_fname); prev_fname = curr_fname; } did_show = TRUE; if (!got_int) show_pat_in_path(line, type, TRUE, action, (depth == -1) ? NULL : files[depth].fp, (depth == -1) ? &lnum : &files[depth].lnum, match_count++); /* Set matched flag for this file and all the ones that * include it */ for (i = 0; i <= depth; ++i) files[i].matched = TRUE; } else if (--count <= 0) { found = TRUE; if (depth == -1 && lnum == curwin->w_cursor.lnum #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX) && g_do_tagpreview == 0 #endif ) EMSG(_("E387: Match is on current line")); else if (action == ACTION_SHOW) { show_pat_in_path(line, type, did_show, action, (depth == -1) ? NULL : files[depth].fp, (depth == -1) ? &lnum : &files[depth].lnum, 1L); did_show = TRUE; } else { #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX) /* ":psearch" uses the preview window */ if (g_do_tagpreview != 0) { curwin_save = curwin; prepare_tagpreview(TRUE); } #endif if (action == ACTION_SPLIT) { #ifdef FEAT_WINDOWS if (win_split(0, 0) == FAIL) #endif break; RESET_BINDING(curwin); } if (depth == -1) { /* match in current file */ #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { if (getfile(0, curwin_save->w_buffer->b_fname, NULL, TRUE, lnum, FALSE) > 0) break; /* failed to jump to file */ } else #endif setpcmark(); curwin->w_cursor.lnum = lnum; } else { if (getfile(0, files[depth].name, NULL, TRUE, files[depth].lnum, FALSE) > 0) break; /* failed to jump to file */ /* autocommands may have changed the lnum, we don't * want that here */ curwin->w_cursor.lnum = files[depth].lnum; } } if (action != ACTION_SHOW) { curwin->w_cursor.col = (colnr_T)(startp - line); curwin->w_set_curswant = TRUE; } #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0 && curwin != curwin_save && win_valid(curwin_save)) { /* Return cursor to where we were */ validate_cursor(); redraw_later(VALID); win_enter(curwin_save, TRUE); } #endif break; } #ifdef FEAT_INS_EXPAND exit_matched: #endif matched = FALSE; /* look for other matches in the rest of the line if we * are not at the end of it already */ if (def_regmatch.regprog == NULL #ifdef FEAT_INS_EXPAND && action == ACTION_EXPAND && !(compl_cont_status & CONT_SOL) #endif && *startp != NUL && *(p = startp + 1) != NUL) goto search_line; } line_breakcheck(); #ifdef FEAT_INS_EXPAND if (action == ACTION_EXPAND) ins_compl_check_keys(30); if (got_int || compl_interrupted) #else if (got_int) #endif break; /* * Read the next line. When reading an included file and encountering * end-of-file, close the file and continue in the file that included * it. */ while (depth >= 0 && !already && vim_fgets(line = file_line, LSIZE, files[depth].fp)) { fclose(files[depth].fp); --old_files; files[old_files].name = files[depth].name; files[old_files].matched = files[depth].matched; --depth; curr_fname = (depth == -1) ? curbuf->b_fname : files[depth].name; if (depth < depth_displayed) depth_displayed = depth; } if (depth >= 0) /* we could read the line */ files[depth].lnum++; else if (!already) { if (++lnum > end_lnum) break; line = ml_get(lnum); } already = NULL; } /* End of big for (;;) loop. */ /* Close any files that are still open. */ for (i = 0; i <= depth; i++) { fclose(files[i].fp); vim_free(files[i].name); } for (i = old_files; i < max_path_depth; i++) vim_free(files[i].name); vim_free(files); if (type == CHECK_PATH) { if (!did_show) { if (action != ACTION_SHOW_ALL) MSG(_("All included files were found")); else MSG(_("No included files")); } } else if (!found #ifdef FEAT_INS_EXPAND && action != ACTION_EXPAND #endif ) { #ifdef FEAT_INS_EXPAND if (got_int || compl_interrupted) #else if (got_int) #endif EMSG(_(e_interr)); else if (type == FIND_DEFINE) EMSG(_("E388: Couldn't find definition")); else EMSG(_("E389: Couldn't find pattern")); } if (action == ACTION_SHOW || action == ACTION_SHOW_ALL) msg_end(); fpip_end: vim_free(file_line); vim_free(regmatch.regprog); vim_free(incl_regmatch.regprog); vim_free(def_regmatch.regprog); } static void show_pat_in_path(line, type, did_show, action, fp, lnum, count) char_u *line; int type; int did_show; int action; FILE *fp; linenr_T *lnum; long count; { char_u *p; if (did_show) msg_putchar('\n'); /* cursor below last one */ else if (!msg_silent) gotocmdline(TRUE); /* cursor at status line */ if (got_int) /* 'q' typed at "--more--" message */ return; for (;;) { p = line + STRLEN(line) - 1; if (fp != NULL) { /* We used fgets(), so get rid of newline at end */ if (p >= line && *p == '\n') --p; if (p >= line && *p == '\r') --p; *(p + 1) = NUL; } if (action == ACTION_SHOW_ALL) { sprintf((char *)IObuff, "%3ld: ", count); /* show match nr */ msg_puts(IObuff); sprintf((char *)IObuff, "%4ld", *lnum); /* show line nr */ /* Highlight line numbers */ msg_puts_attr(IObuff, hl_attr(HLF_N)); MSG_PUTS(" "); } msg_prt_line(line, FALSE); out_flush(); /* show one line at a time */ /* Definition continues until line that doesn't end with '\' */ if (got_int || type != FIND_DEFINE || p < line || *p != '\\') break; if (fp != NULL) { if (vim_fgets(line, LSIZE, fp)) /* end of file */ break; ++*lnum; } else { if (++*lnum > curbuf->b_ml.ml_line_count) break; line = ml_get(*lnum); } msg_putchar('\n'); } } #endif #ifdef FEAT_VIMINFO int read_viminfo_search_pattern(virp, force) vir_T *virp; int force; { char_u *lp; int idx = -1; int magic = FALSE; int no_scs = FALSE; int off_line = FALSE; int off_end = 0; long off = 0; int setlast = FALSE; #ifdef FEAT_SEARCH_EXTRA static int hlsearch_on = FALSE; #endif char_u *val; /* * Old line types: * "/pat", "&pat": search/subst. pat * "~/pat", "~&pat": last used search/subst. pat * New line types: * "~h", "~H": hlsearch highlighting off/on * "~<magic><smartcase><line><end><off><last><which>pat" * <magic>: 'm' off, 'M' on * <smartcase>: 's' off, 'S' on * <line>: 'L' line offset, 'l' char offset * <end>: 'E' from end, 'e' from start * <off>: decimal, offset * <last>: '~' last used pattern * <which>: '/' search pat, '&' subst. pat */ lp = virp->vir_line; if (lp[0] == '~' && (lp[1] == 'm' || lp[1] == 'M')) /* new line type */ { if (lp[1] == 'M') /* magic on */ magic = TRUE; if (lp[2] == 's') no_scs = TRUE; if (lp[3] == 'L') off_line = TRUE; if (lp[4] == 'E') off_end = SEARCH_END; lp += 5; off = getdigits(&lp); } if (lp[0] == '~') /* use this pattern for last-used pattern */ { setlast = TRUE; lp++; } if (lp[0] == '/') idx = RE_SEARCH; else if (lp[0] == '&') idx = RE_SUBST; #ifdef FEAT_SEARCH_EXTRA else if (lp[0] == 'h') /* ~h: 'hlsearch' highlighting off */ hlsearch_on = FALSE; else if (lp[0] == 'H') /* ~H: 'hlsearch' highlighting on */ hlsearch_on = TRUE; #endif if (idx >= 0) { if (force || spats[idx].pat == NULL) { val = viminfo_readstring(virp, (int)(lp - virp->vir_line + 1), TRUE); if (val != NULL) { set_last_search_pat(val, idx, magic, setlast); vim_free(val); spats[idx].no_scs = no_scs; spats[idx].off.line = off_line; spats[idx].off.end = off_end; spats[idx].off.off = off; #ifdef FEAT_SEARCH_EXTRA if (setlast) no_hlsearch = !hlsearch_on; #endif } } } return viminfo_readline(virp); } void write_viminfo_search_pattern(fp) FILE *fp; { if (get_viminfo_parameter('/') != 0) { #ifdef FEAT_SEARCH_EXTRA fprintf(fp, "\n# hlsearch on (H) or off (h):\n~%c", (no_hlsearch || find_viminfo_parameter('h') != NULL) ? 'h' : 'H'); #endif wvsp_one(fp, RE_SEARCH, "", '/'); wvsp_one(fp, RE_SUBST, _("Substitute "), '&'); } } static void wvsp_one(fp, idx, s, sc) FILE *fp; /* file to write to */ int idx; /* spats[] index */ char *s; /* search pat */ int sc; /* dir char */ { if (spats[idx].pat != NULL) { fprintf(fp, _("\n# Last %sSearch Pattern:\n~"), s); /* off.dir is not stored, it's reset to forward */ fprintf(fp, "%c%c%c%c%ld%s%c", spats[idx].magic ? 'M' : 'm', /* magic */ spats[idx].no_scs ? 's' : 'S', /* smartcase */ spats[idx].off.line ? 'L' : 'l', /* line offset */ spats[idx].off.end ? 'E' : 'e', /* offset from end */ spats[idx].off.off, /* offset */ last_idx == idx ? "~" : "", /* last used pat */ sc); viminfo_writestring(fp, spats[idx].pat); } } #endif /* FEAT_VIMINFO */
zyz2011-vim
src/search.c
C
gpl2
131,423
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. */ /* * This file contains various definitions of structures that are used by Vim */ /* * There is something wrong in the SAS compiler that makes typedefs not * valid in include files. Has been fixed in version 6.58. */ #if defined(SASC) && SASC < 658 typedef long linenr_T; typedef int colnr_T; typedef unsigned short short_u; #endif /* * position in file or buffer */ typedef struct { linenr_T lnum; /* line number */ colnr_T col; /* column number */ #ifdef FEAT_VIRTUALEDIT colnr_T coladd; #endif } pos_T; #ifdef FEAT_VIRTUALEDIT # define INIT_POS_T(l, c, ca) {l, c, ca} #else # define INIT_POS_T(l, c, ca) {l, c} #endif /* * Same, but without coladd. */ typedef struct { linenr_T lnum; /* line number */ colnr_T col; /* column number */ } lpos_T; /* * Structure used for growing arrays. * This is used to store information that only grows, is deleted all at * once, and needs to be accessed by index. See ga_clear() and ga_grow(). */ typedef struct growarray { int ga_len; /* current number of items used */ int ga_maxlen; /* maximum number of items possible */ int ga_itemsize; /* sizeof(item) */ int ga_growsize; /* number of items to grow each time */ void *ga_data; /* pointer to the first item */ } garray_T; #define GA_EMPTY {0, 0, 0, 0, NULL} /* * This is here because regexp.h needs pos_T and below regprog_T is used. */ #include "regexp.h" typedef struct window_S win_T; typedef struct wininfo_S wininfo_T; typedef struct frame_S frame_T; typedef int scid_T; /* script ID */ /* * This is here because gui.h needs the pos_T and win_T, and win_T needs gui.h * for scrollbar_T. */ #ifdef FEAT_GUI # include "gui.h" #else # ifdef FEAT_XCLIPBOARD # include <X11/Intrinsic.h> # endif # define guicolor_T int /* avoid error in prototypes */ #endif /* * marks: positions in a file * (a normal mark is a lnum/col pair, the same as a file position) */ /* (Note: for EBCDIC there are more than 26, because there are gaps in the * alphabet coding. To minimize changes to the code, I decided to just * increase the number of possible marks. */ #define NMARKS ('z' - 'a' + 1) /* max. # of named marks */ #define JUMPLISTSIZE 100 /* max. # of marks in jump list */ #define TAGSTACKSIZE 20 /* max. # of tags in tag stack */ typedef struct filemark { pos_T mark; /* cursor position */ int fnum; /* file number */ } fmark_T; /* Xtended file mark: also has a file name */ typedef struct xfilemark { fmark_T fmark; char_u *fname; /* file name, used when fnum == 0 */ } xfmark_T; /* * The taggy struct is used to store the information about a :tag command. */ typedef struct taggy { char_u *tagname; /* tag name */ fmark_T fmark; /* cursor position BEFORE ":tag" */ int cur_match; /* match number */ int cur_fnum; /* buffer number used for cur_match */ } taggy_T; /* * Structure that contains all options that are local to a window. * Used twice in a window: for the current buffer and for all buffers. * Also used in wininfo_T. */ typedef struct { #ifdef FEAT_ARABIC int wo_arab; # define w_p_arab w_onebuf_opt.wo_arab /* 'arabic' */ #endif #ifdef FEAT_DIFF int wo_diff; # define w_p_diff w_onebuf_opt.wo_diff /* 'diff' */ #endif #ifdef FEAT_FOLDING long wo_fdc; # define w_p_fdc w_onebuf_opt.wo_fdc /* 'foldcolumn' */ int wo_fen; # define w_p_fen w_onebuf_opt.wo_fen /* 'foldenable' */ char_u *wo_fdi; # define w_p_fdi w_onebuf_opt.wo_fdi /* 'foldignore' */ long wo_fdl; # define w_p_fdl w_onebuf_opt.wo_fdl /* 'foldlevel' */ char_u *wo_fdm; # define w_p_fdm w_onebuf_opt.wo_fdm /* 'foldmethod' */ long wo_fml; # define w_p_fml w_onebuf_opt.wo_fml /* 'foldminlines' */ long wo_fdn; # define w_p_fdn w_onebuf_opt.wo_fdn /* 'foldnestmax' */ # ifdef FEAT_EVAL char_u *wo_fde; # define w_p_fde w_onebuf_opt.wo_fde /* 'foldexpr' */ char_u *wo_fdt; # define w_p_fdt w_onebuf_opt.wo_fdt /* 'foldtext' */ # endif char_u *wo_fmr; # define w_p_fmr w_onebuf_opt.wo_fmr /* 'foldmarker' */ #endif #ifdef FEAT_LINEBREAK int wo_lbr; # define w_p_lbr w_onebuf_opt.wo_lbr /* 'linebreak' */ #endif int wo_list; #define w_p_list w_onebuf_opt.wo_list /* 'list' */ int wo_nu; #define w_p_nu w_onebuf_opt.wo_nu /* 'number' */ int wo_rnu; #define w_p_rnu w_onebuf_opt.wo_rnu /* 'relativenumber' */ #ifdef FEAT_LINEBREAK long wo_nuw; # define w_p_nuw w_onebuf_opt.wo_nuw /* 'numberwidth' */ #endif #if defined(FEAT_WINDOWS) int wo_wfh; # define w_p_wfh w_onebuf_opt.wo_wfh /* 'winfixheight' */ int wo_wfw; # define w_p_wfw w_onebuf_opt.wo_wfw /* 'winfixwidth' */ #endif #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX) int wo_pvw; # define w_p_pvw w_onebuf_opt.wo_pvw /* 'previewwindow' */ #endif #ifdef FEAT_RIGHTLEFT int wo_rl; # define w_p_rl w_onebuf_opt.wo_rl /* 'rightleft' */ char_u *wo_rlc; # define w_p_rlc w_onebuf_opt.wo_rlc /* 'rightleftcmd' */ #endif long wo_scr; #define w_p_scr w_onebuf_opt.wo_scr /* 'scroll' */ #ifdef FEAT_SPELL int wo_spell; # define w_p_spell w_onebuf_opt.wo_spell /* 'spell' */ #endif #ifdef FEAT_SYN_HL int wo_cuc; # define w_p_cuc w_onebuf_opt.wo_cuc /* 'cursorcolumn' */ int wo_cul; # define w_p_cul w_onebuf_opt.wo_cul /* 'cursorline' */ char_u *wo_cc; # define w_p_cc w_onebuf_opt.wo_cc /* 'colorcolumn' */ #endif #ifdef FEAT_STL_OPT char_u *wo_stl; #define w_p_stl w_onebuf_opt.wo_stl /* 'statusline' */ #endif #ifdef FEAT_SCROLLBIND int wo_scb; # define w_p_scb w_onebuf_opt.wo_scb /* 'scrollbind' */ #endif int wo_wrap; #define w_p_wrap w_onebuf_opt.wo_wrap /* 'wrap' */ #ifdef FEAT_CONCEAL char_u *wo_cocu; /* 'concealcursor' */ # define w_p_cocu w_onebuf_opt.wo_cocu long wo_cole; /* 'conceallevel' */ # define w_p_cole w_onebuf_opt.wo_cole #endif #ifdef FEAT_CURSORBIND int wo_crb; # define w_p_crb w_onebuf_opt.wo_crb /* 'cursorbind' */ #endif #ifdef FEAT_EVAL int wo_scriptID[WV_COUNT]; /* SIDs for window-local options */ # define w_p_scriptID w_onebuf_opt.wo_scriptID #endif } winopt_T; /* * Window info stored with a buffer. * * Two types of info are kept for a buffer which are associated with a * specific window: * 1. Each window can have a different line number associated with a buffer. * 2. The window-local options for a buffer work in a similar way. * The window-info is kept in a list at b_wininfo. It is kept in * most-recently-used order. */ struct wininfo_S { wininfo_T *wi_next; /* next entry or NULL for last entry */ wininfo_T *wi_prev; /* previous entry or NULL for first entry */ win_T *wi_win; /* pointer to window that did set wi_fpos */ pos_T wi_fpos; /* last cursor position in the file */ int wi_optset; /* TRUE when wi_opt has useful values */ winopt_T wi_opt; /* local window options */ #ifdef FEAT_FOLDING int wi_fold_manual; /* copy of w_fold_manual */ garray_T wi_folds; /* clone of w_folds */ #endif }; /* * Info used to pass info about a fold from the fold-detection code to the * code that displays the foldcolumn. */ typedef struct foldinfo { int fi_level; /* level of the fold; when this is zero the other fields are invalid */ int fi_lnum; /* line number where fold starts */ int fi_low_level; /* lowest fold level that starts in the same line */ } foldinfo_T; /* Structure to store info about the Visual area. */ typedef struct { pos_T vi_start; /* start pos of last VIsual */ pos_T vi_end; /* end position of last VIsual */ int vi_mode; /* VIsual_mode of last VIsual */ colnr_T vi_curswant; /* MAXCOL from w_curswant */ } visualinfo_T; /* * structures used for undo */ typedef struct u_entry u_entry_T; typedef struct u_header u_header_T; struct u_entry { u_entry_T *ue_next; /* pointer to next entry in list */ linenr_T ue_top; /* number of line above undo block */ linenr_T ue_bot; /* number of line below undo block */ linenr_T ue_lcount; /* linecount when u_save called */ char_u **ue_array; /* array of lines in undo block */ long ue_size; /* number of lines in ue_array */ #ifdef U_DEBUG int ue_magic; /* magic number to check allocation */ #endif }; struct u_header { /* The following have a pointer and a number. The number is used when * reading the undo file in u_read_undo() */ union { u_header_T *ptr; /* pointer to next undo header in list */ long seq; } uh_next; union { u_header_T *ptr; /* pointer to previous header in list */ long seq; } uh_prev; union { u_header_T *ptr; /* pointer to next header for alt. redo */ long seq; } uh_alt_next; union { u_header_T *ptr; /* pointer to previous header for alt. redo */ long seq; } uh_alt_prev; long uh_seq; /* sequence number, higher == newer undo */ int uh_walk; /* used by undo_time() */ u_entry_T *uh_entry; /* pointer to first entry */ u_entry_T *uh_getbot_entry; /* pointer to where ue_bot must be set */ pos_T uh_cursor; /* cursor position before saving */ #ifdef FEAT_VIRTUALEDIT long uh_cursor_vcol; #endif int uh_flags; /* see below */ pos_T uh_namedm[NMARKS]; /* marks before undo/after redo */ #ifdef FEAT_VISUAL visualinfo_T uh_visual; /* Visual areas before undo/after redo */ #endif time_t uh_time; /* timestamp when the change was made */ long uh_save_nr; /* set when the file was saved after the changes in this block */ #ifdef U_DEBUG int uh_magic; /* magic number to check allocation */ #endif }; /* values for uh_flags */ #define UH_CHANGED 0x01 /* b_changed flag before undo/after redo */ #define UH_EMPTYBUF 0x02 /* buffer was empty */ /* * structures used in undo.c */ #if SIZEOF_INT > 2 # define ALIGN_LONG /* longword alignment and use filler byte */ # define ALIGN_SIZE (sizeof(long)) #else # define ALIGN_SIZE (sizeof(short)) #endif #define ALIGN_MASK (ALIGN_SIZE - 1) typedef struct m_info minfo_T; /* * structure used to link chunks in one of the free chunk lists. */ struct m_info { #ifdef ALIGN_LONG long_u m_size; /* size of the chunk (including m_info) */ #else short_u m_size; /* size of the chunk (including m_info) */ #endif minfo_T *m_next; /* pointer to next free chunk in the list */ }; /* * things used in memfile.c */ typedef struct block_hdr bhdr_T; typedef struct memfile memfile_T; typedef long blocknr_T; /* * mf_hashtab_T is a chained hashtable with blocknr_T key and arbitrary * structures as items. This is an intrusive data structure: we require * that items begin with mf_hashitem_T which contains the key and linked * list pointers. List of items in each bucket is doubly-linked. */ typedef struct mf_hashitem_S mf_hashitem_T; struct mf_hashitem_S { mf_hashitem_T *mhi_next; mf_hashitem_T *mhi_prev; blocknr_T mhi_key; }; #define MHT_INIT_SIZE 64 typedef struct mf_hashtab_S { long_u mht_mask; /* mask used for hash value (nr of items * in array is "mht_mask" + 1) */ long_u mht_count; /* nr of items inserted into hashtable */ mf_hashitem_T **mht_buckets; /* points to mht_small_buckets or *dynamically allocated array */ mf_hashitem_T *mht_small_buckets[MHT_INIT_SIZE]; /* initial buckets */ char mht_fixed; /* non-zero value forbids growth */ } mf_hashtab_T; /* * for each (previously) used block in the memfile there is one block header. * * The block may be linked in the used list OR in the free list. * The used blocks are also kept in hash lists. * * The used list is a doubly linked list, most recently used block first. * The blocks in the used list have a block of memory allocated. * mf_used_count is the number of pages in the used list. * The hash lists are used to quickly find a block in the used list. * The free list is a single linked list, not sorted. * The blocks in the free list have no block of memory allocated and * the contents of the block in the file (if any) is irrelevant. */ struct block_hdr { mf_hashitem_T bh_hashitem; /* header for hash table and key */ #define bh_bnum bh_hashitem.mhi_key /* block number, part of bh_hashitem */ bhdr_T *bh_next; /* next block_hdr in free or used list */ bhdr_T *bh_prev; /* previous block_hdr in used list */ char_u *bh_data; /* pointer to memory (for used block) */ int bh_page_count; /* number of pages in this block */ #define BH_DIRTY 1 #define BH_LOCKED 2 char bh_flags; /* BH_DIRTY or BH_LOCKED */ }; /* * when a block with a negative number is flushed to the file, it gets * a positive number. Because the reference to the block is still the negative * number, we remember the translation to the new positive number in the * double linked trans lists. The structure is the same as the hash lists. */ typedef struct nr_trans NR_TRANS; struct nr_trans { mf_hashitem_T nt_hashitem; /* header for hash table and key */ #define nt_old_bnum nt_hashitem.mhi_key /* old, negative, number */ blocknr_T nt_new_bnum; /* new, positive, number */ }; /* * structure used to store one block of the stuff/redo/recording buffers */ struct buffblock { struct buffblock *b_next; /* pointer to next buffblock */ char_u b_str[1]; /* contents (actually longer) */ }; /* * header used for the stuff buffer and the redo buffer */ struct buffheader { struct buffblock bh_first; /* first (dummy) block of list */ struct buffblock *bh_curr; /* buffblock for appending */ int bh_index; /* index for reading */ int bh_space; /* space in bh_curr for appending */ }; /* * used for completion on the command line */ typedef struct expand { int xp_context; /* type of expansion */ char_u *xp_pattern; /* start of item to expand */ int xp_pattern_len; /* bytes in xp_pattern before cursor */ #if defined(FEAT_USR_CMDS) && defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL) char_u *xp_arg; /* completion function */ int xp_scriptID; /* SID for completion function */ #endif int xp_backslash; /* one of the XP_BS_ values */ #ifndef BACKSLASH_IN_FILENAME int xp_shell; /* TRUE for a shell command, more characters need to be escaped */ #endif int xp_numfiles; /* number of files found by file name completion */ char_u **xp_files; /* list of files */ } expand_T; /* values for xp_backslash */ #define XP_BS_NONE 0 /* nothing special for backslashes */ #define XP_BS_ONE 1 /* uses one backslash before a space */ #define XP_BS_THREE 2 /* uses three backslashes before a space */ /* * Command modifiers ":vertical", ":browse", ":confirm" and ":hide" set a flag. * This needs to be saved for recursive commands, put them in a structure for * easy manipulation. */ typedef struct { int hide; /* TRUE when ":hide" was used */ # ifdef FEAT_BROWSE_CMD int browse; /* TRUE to invoke file dialog */ # endif # ifdef FEAT_WINDOWS int split; /* flags for win_split() */ int tab; /* > 0 when ":tab" was used */ # endif # if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) int confirm; /* TRUE to invoke yes/no dialog */ # endif int keepalt; /* TRUE when ":keepalt" was used */ int keepmarks; /* TRUE when ":keepmarks" was used */ int keepjumps; /* TRUE when ":keepjumps" was used */ int lockmarks; /* TRUE when ":lockmarks" was used */ # ifdef FEAT_AUTOCMD char_u *save_ei; /* saved value of 'eventignore' */ # endif } cmdmod_T; typedef struct file_buffer buf_T; /* forward declaration */ #define MF_SEED_LEN 8 struct memfile { char_u *mf_fname; /* name of the file */ char_u *mf_ffname; /* idem, full path */ int mf_fd; /* file descriptor */ bhdr_T *mf_free_first; /* first block_hdr in free list */ bhdr_T *mf_used_first; /* mru block_hdr in used list */ bhdr_T *mf_used_last; /* lru block_hdr in used list */ unsigned mf_used_count; /* number of pages in used list */ unsigned mf_used_count_max; /* maximum number of pages in memory */ mf_hashtab_T mf_hash; /* hash lists */ mf_hashtab_T mf_trans; /* trans lists */ blocknr_T mf_blocknr_max; /* highest positive block number + 1*/ blocknr_T mf_blocknr_min; /* lowest negative block number - 1 */ blocknr_T mf_neg_count; /* number of negative blocks numbers */ blocknr_T mf_infile_count; /* number of pages in the file */ unsigned mf_page_size; /* number of bytes in a page */ int mf_dirty; /* TRUE if there are dirty blocks */ #ifdef FEAT_CRYPT buf_T *mf_buffer; /* bufer this memfile is for */ char_u mf_seed[MF_SEED_LEN]; /* seed for encryption */ /* Values for key, method and seed used for reading data blocks when * updating for a newly set key or method. Only when mf_old_key != NULL. */ char_u *mf_old_key; int mf_old_cm; char_u mf_old_seed[MF_SEED_LEN]; #endif }; /* * things used in memline.c */ /* * When searching for a specific line, we remember what blocks in the tree * are the branches leading to that block. This is stored in ml_stack. Each * entry is a pointer to info in a block (may be data block or pointer block) */ typedef struct info_pointer { blocknr_T ip_bnum; /* block number */ linenr_T ip_low; /* lowest lnum in this block */ linenr_T ip_high; /* highest lnum in this block */ int ip_index; /* index for block with current lnum */ } infoptr_T; /* block/index pair */ #ifdef FEAT_BYTEOFF typedef struct ml_chunksize { int mlcs_numlines; long mlcs_totalsize; } chunksize_T; /* Flags when calling ml_updatechunk() */ #define ML_CHNK_ADDLINE 1 #define ML_CHNK_DELLINE 2 #define ML_CHNK_UPDLINE 3 #endif /* * the memline structure holds all the information about a memline */ typedef struct memline { linenr_T ml_line_count; /* number of lines in the buffer */ memfile_T *ml_mfp; /* pointer to associated memfile */ #define ML_EMPTY 1 /* empty buffer */ #define ML_LINE_DIRTY 2 /* cached line was changed and allocated */ #define ML_LOCKED_DIRTY 4 /* ml_locked was changed */ #define ML_LOCKED_POS 8 /* ml_locked needs positive block number */ int ml_flags; infoptr_T *ml_stack; /* stack of pointer blocks (array of IPTRs) */ int ml_stack_top; /* current top if ml_stack */ int ml_stack_size; /* total number of entries in ml_stack */ linenr_T ml_line_lnum; /* line number of cached line, 0 if not valid */ char_u *ml_line_ptr; /* pointer to cached line */ bhdr_T *ml_locked; /* block used by last ml_get */ linenr_T ml_locked_low; /* first line in ml_locked */ linenr_T ml_locked_high; /* last line in ml_locked */ int ml_locked_lineadd; /* number of lines inserted in ml_locked */ #ifdef FEAT_BYTEOFF chunksize_T *ml_chunksize; int ml_numchunks; int ml_usedchunks; #endif } memline_T; #if defined(FEAT_SIGNS) || defined(PROTO) typedef struct signlist signlist_T; struct signlist { int id; /* unique identifier for each placed sign */ linenr_T lnum; /* line number which has this sign */ int typenr; /* typenr of sign */ signlist_T *next; /* next signlist entry */ # ifdef FEAT_NETBEANS_INTG signlist_T *prev; /* previous entry -- for easy reordering */ # endif }; /* type argument for buf_getsigntype() */ #define SIGN_ANY 0 #define SIGN_LINEHL 1 #define SIGN_ICON 2 #define SIGN_TEXT 3 #endif /* * Argument list: Array of file names. * Used for the global argument list and the argument lists local to a window. */ typedef struct arglist { garray_T al_ga; /* growarray with the array of file names */ int al_refcount; /* number of windows using this arglist */ } alist_T; /* * For each argument remember the file name as it was given, and the buffer * number that contains the expanded file name (required for when ":cd" is * used. */ typedef struct argentry { char_u *ae_fname; /* file name as specified */ int ae_fnum; /* buffer number with expanded file name */ } aentry_T; #ifdef FEAT_WINDOWS # define ALIST(win) (win)->w_alist #else # define ALIST(win) (&global_alist) #endif #define GARGLIST ((aentry_T *)global_alist.al_ga.ga_data) #define ARGLIST ((aentry_T *)ALIST(curwin)->al_ga.ga_data) #define WARGLIST(wp) ((aentry_T *)ALIST(wp)->al_ga.ga_data) #define AARGLIST(al) ((aentry_T *)((al)->al_ga.ga_data)) #define GARGCOUNT (global_alist.al_ga.ga_len) #define ARGCOUNT (ALIST(curwin)->al_ga.ga_len) #define WARGCOUNT(wp) (ALIST(wp)->al_ga.ga_len) /* * A list used for saving values of "emsg_silent". Used by ex_try() to save the * value of "emsg_silent" if it was non-zero. When this is done, the CSF_SILENT * flag below is set. */ typedef struct eslist_elem eslist_T; struct eslist_elem { int saved_emsg_silent; /* saved value of "emsg_silent" */ eslist_T *next; /* next element on the list */ }; /* * For conditional commands a stack is kept of nested conditionals. * When cs_idx < 0, there is no conditional command. */ #define CSTACK_LEN 50 struct condstack { short cs_flags[CSTACK_LEN]; /* CSF_ flags */ char cs_pending[CSTACK_LEN]; /* CSTP_: what's pending in ":finally"*/ union { void *csp_rv[CSTACK_LEN]; /* return typeval for pending return */ void *csp_ex[CSTACK_LEN]; /* exception for pending throw */ } cs_pend; void *cs_forinfo[CSTACK_LEN]; /* info used by ":for" */ int cs_line[CSTACK_LEN]; /* line nr of ":while"/":for" line */ int cs_idx; /* current entry, or -1 if none */ int cs_looplevel; /* nr of nested ":while"s and ":for"s */ int cs_trylevel; /* nr of nested ":try"s */ eslist_T *cs_emsg_silent_list; /* saved values of "emsg_silent" */ char cs_lflags; /* loop flags: CSL_ flags */ }; # define cs_rettv cs_pend.csp_rv # define cs_exception cs_pend.csp_ex /* There is no CSF_IF, the lack of CSF_WHILE, CSF_FOR and CSF_TRY means ":if" * was used. */ # define CSF_TRUE 0x0001 /* condition was TRUE */ # define CSF_ACTIVE 0x0002 /* current state is active */ # define CSF_ELSE 0x0004 /* ":else" has been passed */ # define CSF_WHILE 0x0008 /* is a ":while" */ # define CSF_FOR 0x0010 /* is a ":for" */ # define CSF_TRY 0x0100 /* is a ":try" */ # define CSF_FINALLY 0x0200 /* ":finally" has been passed */ # define CSF_THROWN 0x0400 /* exception thrown to this try conditional */ # define CSF_CAUGHT 0x0800 /* exception caught by this try conditional */ # define CSF_SILENT 0x1000 /* "emsg_silent" reset by ":try" */ /* Note that CSF_ELSE is only used when CSF_TRY and CSF_WHILE are unset * (an ":if"), and CSF_SILENT is only used when CSF_TRY is set. */ /* * What's pending for being reactivated at the ":endtry" of this try * conditional: */ # define CSTP_NONE 0 /* nothing pending in ":finally" clause */ # define CSTP_ERROR 1 /* an error is pending */ # define CSTP_INTERRUPT 2 /* an interrupt is pending */ # define CSTP_THROW 4 /* a throw is pending */ # define CSTP_BREAK 8 /* ":break" is pending */ # define CSTP_CONTINUE 16 /* ":continue" is pending */ # define CSTP_RETURN 24 /* ":return" is pending */ # define CSTP_FINISH 32 /* ":finish" is pending */ /* * Flags for the cs_lflags item in struct condstack. */ # define CSL_HAD_LOOP 1 /* just found ":while" or ":for" */ # define CSL_HAD_ENDLOOP 2 /* just found ":endwhile" or ":endfor" */ # define CSL_HAD_CONT 4 /* just found ":continue" */ # define CSL_HAD_FINA 8 /* just found ":finally" */ /* * A list of error messages that can be converted to an exception. "throw_msg" * is only set in the first element of the list. Usually, it points to the * original message stored in that element, but sometimes it points to a later * message in the list. See cause_errthrow() below. */ struct msglist { char_u *msg; /* original message */ char_u *throw_msg; /* msg to throw: usually original one */ struct msglist *next; /* next of several messages in a row */ }; /* * Structure describing an exception. * (don't use "struct exception", it's used by the math library). */ typedef struct vim_exception except_T; struct vim_exception { int type; /* exception type */ char_u *value; /* exception value */ struct msglist *messages; /* message(s) causing error exception */ char_u *throw_name; /* name of the throw point */ linenr_T throw_lnum; /* line number of the throw point */ except_T *caught; /* next exception on the caught stack */ }; /* * The exception types. */ #define ET_USER 0 /* exception caused by ":throw" command */ #define ET_ERROR 1 /* error exception */ #define ET_INTERRUPT 2 /* interrupt exception triggered by Ctrl-C */ /* * Structure to save the error/interrupt/exception state between calls to * enter_cleanup() and leave_cleanup(). Must be allocated as an automatic * variable by the (common) caller of these functions. */ typedef struct cleanup_stuff cleanup_T; struct cleanup_stuff { int pending; /* error/interrupt/exception state */ except_T *exception; /* exception value */ }; #ifdef FEAT_SYN_HL /* struct passed to in_id_list() */ struct sp_syn { int inc_tag; /* ":syn include" unique tag */ short id; /* highlight group ID of item */ short *cont_in_list; /* cont.in group IDs, if non-zero */ }; /* * Each keyword has one keyentry, which is linked in a hash list. */ typedef struct keyentry keyentry_T; struct keyentry { keyentry_T *ke_next; /* next entry with identical "keyword[]" */ struct sp_syn k_syn; /* struct passed to in_id_list() */ short *next_list; /* ID list for next match (if non-zero) */ int flags; int k_char; /* conceal substitute character */ char_u keyword[1]; /* actually longer */ }; /* * Struct used to store one state of the state stack. */ typedef struct buf_state { int bs_idx; /* index of pattern */ int bs_flags; /* flags for pattern */ #ifdef FEAT_CONCEAL int bs_seqnr; /* stores si_seqnr */ int bs_cchar; /* stores si_cchar */ #endif reg_extmatch_T *bs_extmatch; /* external matches from start pattern */ } bufstate_T; /* * syn_state contains the syntax state stack for the start of one line. * Used by b_sst_array[]. */ typedef struct syn_state synstate_T; struct syn_state { synstate_T *sst_next; /* next entry in used or free list */ linenr_T sst_lnum; /* line number for this state */ union { bufstate_T sst_stack[SST_FIX_STATES]; /* short state stack */ garray_T sst_ga; /* growarray for long state stack */ } sst_union; int sst_next_flags; /* flags for sst_next_list */ int sst_stacksize; /* number of states on the stack */ short *sst_next_list; /* "nextgroup" list in this state * (this is a copy, don't free it! */ disptick_T sst_tick; /* tick when last displayed */ linenr_T sst_change_lnum;/* when non-zero, change in this line * may have made the state invalid */ }; #endif /* FEAT_SYN_HL */ /* * Structure shared between syntax.c, screen.c and gui_x11.c. */ typedef struct attr_entry { short ae_attr; /* HL_BOLD, etc. */ union { struct { char_u *start; /* start escape sequence */ char_u *stop; /* stop escape sequence */ } term; struct { /* These colors need to be > 8 bits to hold 256. */ short_u fg_color; /* foreground color number */ short_u bg_color; /* background color number */ } cterm; # ifdef FEAT_GUI struct { guicolor_T fg_color; /* foreground color handle */ guicolor_T bg_color; /* background color handle */ guicolor_T sp_color; /* special color handle */ GuiFont font; /* font handle */ # ifdef FEAT_XFONTSET GuiFontset fontset; /* fontset handle */ # endif } gui; # endif } ae_u; } attrentry_T; #ifdef USE_ICONV # ifdef HAVE_ICONV_H # include <iconv.h> # else # if defined(MACOS_X) # include <sys/errno.h> # define EILSEQ ENOENT /* MacOS X does not have EILSEQ */ typedef struct _iconv_t *iconv_t; # else # if defined(MACOS_CLASSIC) typedef struct _iconv_t *iconv_t; # define EINVAL 22 # define E2BIG 7 # define ENOENT 2 # define EFAULT 14 # define EILSEQ 123 # else # include <errno.h> # endif # endif typedef void *iconv_t; # endif #endif /* * Used for the typeahead buffer: typebuf. */ typedef struct { char_u *tb_buf; /* buffer for typed characters */ char_u *tb_noremap; /* mapping flags for characters in tb_buf[] */ int tb_buflen; /* size of tb_buf[] */ int tb_off; /* current position in tb_buf[] */ int tb_len; /* number of valid bytes in tb_buf[] */ int tb_maplen; /* nr of mapped bytes in tb_buf[] */ int tb_silent; /* nr of silently mapped bytes in tb_buf[] */ int tb_no_abbr_cnt; /* nr of bytes without abbrev. in tb_buf[] */ int tb_change_cnt; /* nr of time tb_buf was changed; never zero */ } typebuf_T; /* Struct to hold the saved typeahead for save_typeahead(). */ typedef struct { typebuf_T save_typebuf; int typebuf_valid; /* TRUE when save_typebuf valid */ int old_char; int old_mod_mask; struct buffheader save_stuffbuff; #ifdef USE_INPUT_BUF char_u *save_inputbuf; #endif } tasave_T; /* * Used for conversion of terminal I/O and script files. */ typedef struct { int vc_type; /* zero or one of the CONV_ values */ int vc_factor; /* max. expansion factor */ # ifdef WIN3264 int vc_cpfrom; /* codepage to convert from (CONV_CODEPAGE) */ int vc_cpto; /* codepage to convert to (CONV_CODEPAGE) */ # endif # ifdef USE_ICONV iconv_t vc_fd; /* for CONV_ICONV */ # endif int vc_fail; /* fail for invalid char, don't use '?' */ } vimconv_T; /* * Structure used for reading from the viminfo file. */ typedef struct { char_u *vir_line; /* text of the current line */ FILE *vir_fd; /* file descriptor */ #ifdef FEAT_MBYTE vimconv_T vir_conv; /* encoding conversion */ #endif } vir_T; #define CONV_NONE 0 #define CONV_TO_UTF8 1 #define CONV_9_TO_UTF8 2 #define CONV_TO_LATIN1 3 #define CONV_TO_LATIN9 4 #define CONV_ICONV 5 #ifdef WIN3264 # define CONV_CODEPAGE 10 /* codepage -> codepage */ #endif #ifdef MACOS_X # define CONV_MAC_LATIN1 20 # define CONV_LATIN1_MAC 21 # define CONV_MAC_UTF8 22 # define CONV_UTF8_MAC 23 #endif /* * Structure used for mappings and abbreviations. */ typedef struct mapblock mapblock_T; struct mapblock { mapblock_T *m_next; /* next mapblock in list */ char_u *m_keys; /* mapped from, lhs */ int m_keylen; /* strlen(m_keys) */ char_u *m_str; /* mapped to, rhs */ char_u *m_orig_str; /* rhs as entered by the user */ int m_mode; /* valid mode */ int m_noremap; /* if non-zero no re-mapping for m_str */ char m_silent; /* <silent> used, don't echo commands */ #ifdef FEAT_EVAL char m_expr; /* <expr> used, m_str is an expression */ scid_T m_script_ID; /* ID of script where map was defined */ #endif }; /* * Used for highlighting in the status line. */ struct stl_hlrec { char_u *start; int userhl; /* 0: no HL, 1-9: User HL, < 0 for syn ID */ }; /* * Syntax items - usually buffer-specific. */ /* Item for a hashtable. "hi_key" can be one of three values: * NULL: Never been used * HI_KEY_REMOVED: Entry was removed * Otherwise: Used item, pointer to the actual key; this usually is * inside the item, subtract an offset to locate the item. * This reduces the size of hashitem by 1/3. */ typedef struct hashitem_S { long_u hi_hash; /* cached hash number of hi_key */ char_u *hi_key; } hashitem_T; /* The address of "hash_removed" is used as a magic number for hi_key to * indicate a removed item. */ #define HI_KEY_REMOVED &hash_removed #define HASHITEM_EMPTY(hi) ((hi)->hi_key == NULL || (hi)->hi_key == &hash_removed) /* Initial size for a hashtable. Our items are relatively small and growing * is expensive, thus use 16 as a start. Must be a power of 2. */ #define HT_INIT_SIZE 16 typedef struct hashtable_S { long_u ht_mask; /* mask used for hash value (nr of items in * array is "ht_mask" + 1) */ long_u ht_used; /* number of items used */ long_u ht_filled; /* number of items used + removed */ int ht_locked; /* counter for hash_lock() */ int ht_error; /* when set growing failed, can't add more items before growing works */ hashitem_T *ht_array; /* points to the array, allocated when it's not "ht_smallarray" */ hashitem_T ht_smallarray[HT_INIT_SIZE]; /* initial array */ } hashtab_T; typedef long_u hash_T; /* Type for hi_hash */ #if SIZEOF_INT <= 3 /* use long if int is smaller than 32 bits */ typedef long varnumber_T; #else typedef int varnumber_T; #endif typedef double float_T; typedef struct listvar_S list_T; typedef struct dictvar_S dict_T; /* * Structure to hold an internal variable without a name. */ typedef struct { char v_type; /* see below: VAR_NUMBER, VAR_STRING, etc. */ char v_lock; /* see below: VAR_LOCKED, VAR_FIXED */ union { varnumber_T v_number; /* number value */ #ifdef FEAT_FLOAT float_T v_float; /* floating number value */ #endif char_u *v_string; /* string value (can be NULL!) */ list_T *v_list; /* list value (can be NULL!) */ dict_T *v_dict; /* dict value (can be NULL!) */ } vval; } typval_T; /* Values for "v_type". */ #define VAR_UNKNOWN 0 #define VAR_NUMBER 1 /* "v_number" is used */ #define VAR_STRING 2 /* "v_string" is used */ #define VAR_FUNC 3 /* "v_string" is function name */ #define VAR_LIST 4 /* "v_list" is used */ #define VAR_DICT 5 /* "v_dict" is used */ #define VAR_FLOAT 6 /* "v_float" is used */ /* Values for "v_lock". */ #define VAR_LOCKED 1 /* locked with lock(), can use unlock() */ #define VAR_FIXED 2 /* locked forever */ /* * Structure to hold an item of a list: an internal variable without a name. */ typedef struct listitem_S listitem_T; struct listitem_S { listitem_T *li_next; /* next item in list */ listitem_T *li_prev; /* previous item in list */ typval_T li_tv; /* type and value of the variable */ }; /* * Struct used by those that are using an item in a list. */ typedef struct listwatch_S listwatch_T; struct listwatch_S { listitem_T *lw_item; /* item being watched */ listwatch_T *lw_next; /* next watcher */ }; /* * Structure to hold info about a list. */ struct listvar_S { listitem_T *lv_first; /* first item, NULL if none */ listitem_T *lv_last; /* last item, NULL if none */ int lv_refcount; /* reference count */ int lv_len; /* number of items */ listwatch_T *lv_watch; /* first watcher, NULL if none */ int lv_idx; /* cached index of an item */ listitem_T *lv_idx_item; /* when not NULL item at index "lv_idx" */ int lv_copyID; /* ID used by deepcopy() */ list_T *lv_copylist; /* copied list used by deepcopy() */ char lv_lock; /* zero, VAR_LOCKED, VAR_FIXED */ list_T *lv_used_next; /* next list in used lists list */ list_T *lv_used_prev; /* previous list in used lists list */ }; /* * Structure to hold an item of a Dictionary. * Also used for a variable. * The key is copied into "di_key" to avoid an extra alloc/free for it. */ struct dictitem_S { typval_T di_tv; /* type and value of the variable */ char_u di_flags; /* flags (only used for variable) */ char_u di_key[1]; /* key (actually longer!) */ }; typedef struct dictitem_S dictitem_T; #define DI_FLAGS_RO 1 /* "di_flags" value: read-only variable */ #define DI_FLAGS_RO_SBX 2 /* "di_flags" value: read-only in the sandbox */ #define DI_FLAGS_FIX 4 /* "di_flags" value: fixed variable, not allocated */ #define DI_FLAGS_LOCK 8 /* "di_flags" value: locked variable */ /* * Structure to hold info about a Dictionary. */ struct dictvar_S { int dv_refcount; /* reference count */ hashtab_T dv_hashtab; /* hashtab that refers to the items */ int dv_copyID; /* ID used by deepcopy() */ dict_T *dv_copydict; /* copied dict used by deepcopy() */ char dv_lock; /* zero, VAR_LOCKED, VAR_FIXED */ dict_T *dv_used_next; /* next dict in used dicts list */ dict_T *dv_used_prev; /* previous dict in used dicts list */ }; /* values for b_syn_spell: what to do with toplevel text */ #define SYNSPL_DEFAULT 0 /* spell check if @Spell not defined */ #define SYNSPL_TOP 1 /* spell check toplevel text */ #define SYNSPL_NOTOP 2 /* don't spell check toplevel text */ /* avoid #ifdefs for when b_spell is not available */ #ifdef FEAT_SPELL # define B_SPELL(buf) ((buf)->b_spell) #else # define B_SPELL(buf) (0) #endif #ifdef FEAT_QUICKFIX typedef struct qf_info_S qf_info_T; #endif /* * These are items normally related to a buffer. But when using ":ownsyntax" * a window may have its own instance. */ typedef struct { #ifdef FEAT_SYN_HL hashtab_T b_keywtab; /* syntax keywords hash table */ hashtab_T b_keywtab_ic; /* idem, ignore case */ int b_syn_error; /* TRUE when error occured in HL */ int b_syn_ic; /* ignore case for :syn cmds */ int b_syn_spell; /* SYNSPL_ values */ garray_T b_syn_patterns; /* table for syntax patterns */ garray_T b_syn_clusters; /* table for syntax clusters */ int b_spell_cluster_id; /* @Spell cluster ID or 0 */ int b_nospell_cluster_id; /* @NoSpell cluster ID or 0 */ int b_syn_containedin; /* TRUE when there is an item with a "containedin" argument */ int b_syn_sync_flags; /* flags about how to sync */ short b_syn_sync_id; /* group to sync on */ long b_syn_sync_minlines; /* minimal sync lines offset */ long b_syn_sync_maxlines; /* maximal sync lines offset */ long b_syn_sync_linebreaks; /* offset for multi-line pattern */ char_u *b_syn_linecont_pat; /* line continuation pattern */ regprog_T *b_syn_linecont_prog; /* line continuation program */ int b_syn_linecont_ic; /* ignore-case flag for above */ int b_syn_topgrp; /* for ":syntax include" */ # ifdef FEAT_CONCEAL int b_syn_conceal; /* auto-conceal for :syn cmds */ # endif # ifdef FEAT_FOLDING int b_syn_folditems; /* number of patterns with the HL_FOLD flag set */ # endif /* * b_sst_array[] contains the state stack for a number of lines, for the * start of that line (col == 0). This avoids having to recompute the * syntax state too often. * b_sst_array[] is allocated to hold the state for all displayed lines, * and states for 1 out of about 20 other lines. * b_sst_array pointer to an array of synstate_T * b_sst_len number of entries in b_sst_array[] * b_sst_first pointer to first used entry in b_sst_array[] or NULL * b_sst_firstfree pointer to first free entry in b_sst_array[] or NULL * b_sst_freecount number of free entries in b_sst_array[] * b_sst_check_lnum entries after this lnum need to be checked for * validity (MAXLNUM means no check needed) */ synstate_T *b_sst_array; int b_sst_len; synstate_T *b_sst_first; synstate_T *b_sst_firstfree; int b_sst_freecount; linenr_T b_sst_check_lnum; short_u b_sst_lasttick; /* last display tick */ #endif /* FEAT_SYN_HL */ #ifdef FEAT_SPELL /* for spell checking */ garray_T b_langp; /* list of pointers to slang_T, see spell.c */ char_u b_spell_ismw[256];/* flags: is midword char */ # ifdef FEAT_MBYTE char_u *b_spell_ismw_mb; /* multi-byte midword chars */ # endif char_u *b_p_spc; /* 'spellcapcheck' */ regprog_T *b_cap_prog; /* program for 'spellcapcheck' */ char_u *b_p_spf; /* 'spellfile' */ char_u *b_p_spl; /* 'spelllang' */ #endif #if !defined(FEAT_SYN_HL) && !defined(FEAT_SPELL) int dummy; #endif } synblock_T; /* * buffer: structure that holds information about one file * * Several windows can share a single Buffer * A buffer is unallocated if there is no memfile for it. * A buffer is new if the associated file has never been loaded yet. */ struct file_buffer { memline_T b_ml; /* associated memline (also contains line count) */ buf_T *b_next; /* links in list of buffers */ buf_T *b_prev; int b_nwindows; /* nr of windows open on this buffer */ int b_flags; /* various BF_ flags */ #ifdef FEAT_AUTOCMD int b_closing; /* buffer is being closed, don't let autocommands close it too. */ #endif /* * b_ffname has the full path of the file (NULL for no name). * b_sfname is the name as the user typed it (or NULL). * b_fname is the same as b_sfname, unless ":cd" has been done, * then it is the same as b_ffname (NULL for no name). */ char_u *b_ffname; /* full path file name */ char_u *b_sfname; /* short file name */ char_u *b_fname; /* current file name */ #ifdef UNIX int b_dev_valid; /* TRUE when b_dev has a valid number */ dev_t b_dev; /* device number */ ino_t b_ino; /* inode number */ #endif #ifdef FEAT_CW_EDITOR FSSpec b_FSSpec; /* MacOS File Identification */ #endif #ifdef VMS char b_fab_rfm; /* Record format */ char b_fab_rat; /* Record attribute */ unsigned int b_fab_mrs; /* Max record size */ #endif #ifdef FEAT_SNIFF int b_sniff; /* file was loaded through Sniff */ #endif int b_fnum; /* buffer number for this file. */ int b_changed; /* 'modified': Set to TRUE if something in the file has been changed and not written out. */ int b_changedtick; /* incremented for each change, also for undo */ int b_saving; /* Set to TRUE if we are in the middle of saving the buffer. */ /* * Changes to a buffer require updating of the display. To minimize the * work, remember changes made and update everything at once. */ int b_mod_set; /* TRUE when there are changes since the last time the display was updated */ linenr_T b_mod_top; /* topmost lnum that was changed */ linenr_T b_mod_bot; /* lnum below last changed line, AFTER the change */ long b_mod_xlines; /* number of extra buffer lines inserted; negative when lines were deleted */ wininfo_T *b_wininfo; /* list of last used info for each window */ long b_mtime; /* last change time of original file */ long b_mtime_read; /* last change time when reading */ off_t b_orig_size; /* size of original file in bytes */ int b_orig_mode; /* mode of original file */ pos_T b_namedm[NMARKS]; /* current named marks (mark.c) */ #ifdef FEAT_VISUAL /* These variables are set when VIsual_active becomes FALSE */ visualinfo_T b_visual; # ifdef FEAT_EVAL int b_visual_mode_eval; /* b_visual.vi_mode for visualmode() */ # endif #endif pos_T b_last_cursor; /* cursor position when last unloading this buffer */ pos_T b_last_insert; /* where Insert mode was left */ pos_T b_last_change; /* position of last change: '. mark */ #ifdef FEAT_JUMPLIST /* * the changelist contains old change positions */ pos_T b_changelist[JUMPLISTSIZE]; int b_changelistlen; /* number of active entries */ int b_new_change; /* set by u_savecommon() */ #endif /* * Character table, only used in charset.c for 'iskeyword' * 32 bytes of 8 bits: 1 bit per character 0-255. */ char_u b_chartab[32]; #ifdef FEAT_LOCALMAP /* Table used for mappings local to a buffer. */ mapblock_T *(b_maphash[256]); /* First abbreviation local to a buffer. */ mapblock_T *b_first_abbr; #endif #ifdef FEAT_USR_CMDS /* User commands local to the buffer. */ garray_T b_ucmds; #endif /* * start and end of an operator, also used for '[ and '] */ pos_T b_op_start; pos_T b_op_end; #ifdef FEAT_VIMINFO int b_marks_read; /* Have we read viminfo marks yet? */ #endif /* * The following only used in undo.c. */ u_header_T *b_u_oldhead; /* pointer to oldest header */ u_header_T *b_u_newhead; /* pointer to newest header; may not be valid if b_u_curhead is not NULL */ u_header_T *b_u_curhead; /* pointer to current header */ int b_u_numhead; /* current number of headers */ int b_u_synced; /* entry lists are synced */ long b_u_seq_last; /* last used undo sequence number */ long b_u_save_nr_last; /* counter for last file write */ long b_u_seq_cur; /* hu_seq of header below which we are now */ time_t b_u_time_cur; /* uh_time of header below which we are now */ long b_u_save_nr_cur; /* file write nr after which we are now */ /* * variables for "U" command in undo.c */ char_u *b_u_line_ptr; /* saved line for "U" command */ linenr_T b_u_line_lnum; /* line number of line in u_line */ colnr_T b_u_line_colnr; /* optional column number */ #ifdef FEAT_INS_EXPAND int b_scanned; /* ^N/^P have scanned this buffer */ #endif /* flags for use of ":lmap" and IM control */ long b_p_iminsert; /* input mode for insert */ long b_p_imsearch; /* input mode for search */ #define B_IMODE_USE_INSERT -1 /* Use b_p_iminsert value for search */ #define B_IMODE_NONE 0 /* Input via none */ #define B_IMODE_LMAP 1 /* Input via langmap */ #ifndef USE_IM_CONTROL # define B_IMODE_LAST 1 #else # define B_IMODE_IM 2 /* Input via input method */ # define B_IMODE_LAST 2 #endif #ifdef FEAT_KEYMAP short b_kmap_state; /* using "lmap" mappings */ # define KEYMAP_INIT 1 /* 'keymap' was set, call keymap_init() */ # define KEYMAP_LOADED 2 /* 'keymap' mappings have been loaded */ garray_T b_kmap_ga; /* the keymap table */ #endif /* * Options local to a buffer. * They are here because their value depends on the type of file * or contents of the file being edited. */ int b_p_initialized; /* set when options initialized */ #ifdef FEAT_EVAL int b_p_scriptID[BV_COUNT]; /* SIDs for buffer-local options */ #endif int b_p_ai; /* 'autoindent' */ int b_p_ai_nopaste; /* b_p_ai saved for paste mode */ int b_p_ci; /* 'copyindent' */ int b_p_bin; /* 'binary' */ #ifdef FEAT_MBYTE int b_p_bomb; /* 'bomb' */ #endif #if defined(FEAT_QUICKFIX) char_u *b_p_bh; /* 'bufhidden' */ char_u *b_p_bt; /* 'buftype' */ #endif int b_p_bl; /* 'buflisted' */ #ifdef FEAT_CINDENT int b_p_cin; /* 'cindent' */ char_u *b_p_cino; /* 'cinoptions' */ char_u *b_p_cink; /* 'cinkeys' */ #endif #if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT) char_u *b_p_cinw; /* 'cinwords' */ #endif #ifdef FEAT_COMMENTS char_u *b_p_com; /* 'comments' */ #endif #ifdef FEAT_FOLDING char_u *b_p_cms; /* 'commentstring' */ #endif #ifdef FEAT_INS_EXPAND char_u *b_p_cpt; /* 'complete' */ #endif #ifdef FEAT_COMPL_FUNC char_u *b_p_cfu; /* 'completefunc' */ char_u *b_p_ofu; /* 'omnifunc' */ #endif int b_p_eol; /* 'endofline' */ int b_p_et; /* 'expandtab' */ int b_p_et_nobin; /* b_p_et saved for binary mode */ #ifdef FEAT_MBYTE char_u *b_p_fenc; /* 'fileencoding' */ #endif char_u *b_p_ff; /* 'fileformat' */ #ifdef FEAT_AUTOCMD char_u *b_p_ft; /* 'filetype' */ #endif char_u *b_p_fo; /* 'formatoptions' */ char_u *b_p_flp; /* 'formatlistpat' */ int b_p_inf; /* 'infercase' */ char_u *b_p_isk; /* 'iskeyword' */ #ifdef FEAT_FIND_ID char_u *b_p_def; /* 'define' local value */ char_u *b_p_inc; /* 'include' */ # ifdef FEAT_EVAL char_u *b_p_inex; /* 'includeexpr' */ long_u b_p_inex_flags; /* flags for 'includeexpr' */ # endif #endif #if defined(FEAT_CINDENT) && defined(FEAT_EVAL) char_u *b_p_inde; /* 'indentexpr' */ long_u b_p_inde_flags; /* flags for 'indentexpr' */ char_u *b_p_indk; /* 'indentkeys' */ #endif #if defined(FEAT_EVAL) char_u *b_p_fex; /* 'formatexpr' */ long_u b_p_fex_flags; /* flags for 'formatexpr' */ #endif #ifdef FEAT_CRYPT char_u *b_p_key; /* 'key' */ #endif char_u *b_p_kp; /* 'keywordprg' */ #ifdef FEAT_LISP int b_p_lisp; /* 'lisp' */ #endif char_u *b_p_mps; /* 'matchpairs' */ int b_p_ml; /* 'modeline' */ int b_p_ml_nobin; /* b_p_ml saved for binary mode */ int b_p_ma; /* 'modifiable' */ char_u *b_p_nf; /* 'nrformats' */ int b_p_pi; /* 'preserveindent' */ #ifdef FEAT_TEXTOBJ char_u *b_p_qe; /* 'quoteescape' */ #endif int b_p_ro; /* 'readonly' */ long b_p_sw; /* 'shiftwidth' */ #ifndef SHORT_FNAME int b_p_sn; /* 'shortname' */ #endif #ifdef FEAT_SMARTINDENT int b_p_si; /* 'smartindent' */ #endif long b_p_sts; /* 'softtabstop' */ long b_p_sts_nopaste; /* b_p_sts saved for paste mode */ #ifdef FEAT_SEARCHPATH char_u *b_p_sua; /* 'suffixesadd' */ #endif int b_p_swf; /* 'swapfile' */ #ifdef FEAT_SYN_HL long b_p_smc; /* 'synmaxcol' */ char_u *b_p_syn; /* 'syntax' */ #endif long b_p_ts; /* 'tabstop' */ int b_p_tx; /* 'textmode' */ long b_p_tw; /* 'textwidth' */ long b_p_tw_nobin; /* b_p_tw saved for binary mode */ long b_p_tw_nopaste; /* b_p_tw saved for paste mode */ long b_p_wm; /* 'wrapmargin' */ long b_p_wm_nobin; /* b_p_wm saved for binary mode */ long b_p_wm_nopaste; /* b_p_wm saved for paste mode */ #ifdef FEAT_KEYMAP char_u *b_p_keymap; /* 'keymap' */ #endif /* local values for options which are normally global */ #ifdef FEAT_QUICKFIX char_u *b_p_gp; /* 'grepprg' local value */ char_u *b_p_mp; /* 'makeprg' local value */ char_u *b_p_efm; /* 'errorformat' local value */ #endif char_u *b_p_ep; /* 'equalprg' local value */ char_u *b_p_path; /* 'path' local value */ int b_p_ar; /* 'autoread' local value */ char_u *b_p_tags; /* 'tags' local value */ #ifdef FEAT_INS_EXPAND char_u *b_p_dict; /* 'dictionary' local value */ char_u *b_p_tsr; /* 'thesaurus' local value */ #endif #ifdef FEAT_PERSISTENT_UNDO int b_p_udf; /* 'undofile' */ #endif /* end of buffer options */ linenr_T b_no_eol_lnum; /* non-zero lnum when last line of next binary * write should not have an end-of-line */ int b_start_eol; /* last line had eol when it was read */ int b_start_ffc; /* first char of 'ff' when edit started */ #ifdef FEAT_MBYTE char_u *b_start_fenc; /* 'fileencoding' when edit started or NULL */ int b_bad_char; /* "++bad=" argument when edit started or 0 */ int b_start_bomb; /* 'bomb' when it was read */ #endif #ifdef FEAT_EVAL dictitem_T b_bufvar; /* variable for "b:" Dictionary */ dict_T b_vars; /* internal variables, local to buffer */ #endif #if defined(FEAT_BEVAL) && defined(FEAT_EVAL) char_u *b_p_bexpr; /* 'balloonexpr' local value */ long_u b_p_bexpr_flags;/* flags for 'balloonexpr' */ #endif #ifdef FEAT_CRYPT char_u *b_p_cm; /* 'cryptmethod' */ #endif /* When a buffer is created, it starts without a swap file. b_may_swap is * then set to indicate that a swap file may be opened later. It is reset * if a swap file could not be opened. */ int b_may_swap; int b_did_warn; /* Set to 1 if user has been warned on first change of a read-only file */ /* Two special kinds of buffers: * help buffer - used for help files, won't use a swap file. * spell buffer - used for spell info, never displayed and doesn't have a * file name. */ int b_help; /* TRUE for help file buffer (when set b_p_bt is "help") */ #ifdef FEAT_SPELL int b_spell; /* TRUE for a spell file buffer, most fields are not used! Use the B_SPELL macro to access b_spell without #ifdef. */ #endif #ifndef SHORT_FNAME int b_shortname; /* this file has an 8.3 file name */ #endif #ifdef FEAT_MZSCHEME void *b_mzscheme_ref; /* The MzScheme reference to this buffer */ #endif #ifdef FEAT_PERL void *b_perl_private; #endif #ifdef FEAT_PYTHON void *b_python_ref; /* The Python reference to this buffer */ #endif #ifdef FEAT_PYTHON3 void *b_python3_ref; /* The Python3 reference to this buffer */ #endif #ifdef FEAT_TCL void *b_tcl_ref; #endif #ifdef FEAT_RUBY void *b_ruby_ref; #endif #if defined(FEAT_SYN_HL) || defined(FEAT_SPELL) synblock_T b_s; /* Info related to syntax highlighting. w_s * normally points to this, but some windows * may use a different synblock_T. */ #endif #ifdef FEAT_SIGNS signlist_T *b_signlist; /* list of signs to draw */ #endif #ifdef FEAT_NETBEANS_INTG int b_netbeans_file; /* TRUE when buffer is owned by NetBeans */ int b_was_netbeans_file;/* TRUE if b_netbeans_file was once set */ #endif }; #ifdef FEAT_DIFF /* * Stuff for diff mode. */ # define DB_COUNT 4 /* up to four buffers can be diff'ed */ /* * Each diffblock defines where a block of lines starts in each of the buffers * and how many lines it occupies in that buffer. When the lines are missing * in the buffer the df_count[] is zero. This is all counted in * buffer lines. * There is always at least one unchanged line in between the diffs. * Otherwise it would have been included in the diff above or below it. * df_lnum[] + df_count[] is the lnum below the change. When in one buffer * lines have been inserted, in the other buffer df_lnum[] is the line below * the insertion and df_count[] is zero. When appending lines at the end of * the buffer, df_lnum[] is one beyond the end! * This is using a linked list, because the number of differences is expected * to be reasonable small. The list is sorted on lnum. */ typedef struct diffblock_S diff_T; struct diffblock_S { diff_T *df_next; linenr_T df_lnum[DB_COUNT]; /* line number in buffer */ linenr_T df_count[DB_COUNT]; /* nr of inserted/changed lines */ }; #endif #define SNAP_HELP_IDX 0 #ifdef FEAT_AUTOCMD # define SNAP_AUCMD_IDX 1 # define SNAP_COUNT 2 #else # define SNAP_COUNT 1 #endif /* * Tab pages point to the top frame of each tab page. * Note: Most values are NOT valid for the current tab page! Use "curwin", * "firstwin", etc. for that. "tp_topframe" is always valid and can be * compared against "topframe" to find the current tab page. */ typedef struct tabpage_S tabpage_T; struct tabpage_S { tabpage_T *tp_next; /* next tabpage or NULL */ frame_T *tp_topframe; /* topframe for the windows */ win_T *tp_curwin; /* current window in this Tab page */ win_T *tp_prevwin; /* previous window in this Tab page */ win_T *tp_firstwin; /* first window in this Tab page */ win_T *tp_lastwin; /* last window in this Tab page */ long tp_old_Rows; /* Rows when Tab page was left */ long tp_old_Columns; /* Columns when Tab page was left */ long tp_ch_used; /* value of 'cmdheight' when frame size was set */ #ifdef FEAT_GUI int tp_prev_which_scrollbars[3]; /* previous value of which_scrollbars */ #endif #ifdef FEAT_DIFF diff_T *tp_first_diff; buf_T *(tp_diffbuf[DB_COUNT]); int tp_diff_invalid; /* list of diffs is outdated */ #endif frame_T *(tp_snapshot[SNAP_COUNT]); /* window layout snapshots */ #ifdef FEAT_EVAL dictitem_T tp_winvar; /* variable for "t:" Dictionary */ dict_T tp_vars; /* internal variables, local to tab page */ #endif }; /* * Structure to cache info for displayed lines in w_lines[]. * Each logical line has one entry. * The entry tells how the logical line is currently displayed in the window. * This is updated when displaying the window. * When the display is changed (e.g., when clearing the screen) w_lines_valid * is changed to exclude invalid entries. * When making changes to the buffer, wl_valid is reset to indicate wl_size * may not reflect what is actually in the buffer. When wl_valid is FALSE, * the entries can only be used to count the number of displayed lines used. * wl_lnum and wl_lastlnum are invalid too. */ typedef struct w_line { linenr_T wl_lnum; /* buffer line number for logical line */ short_u wl_size; /* height in screen lines */ char wl_valid; /* TRUE values are valid for text in buffer */ #ifdef FEAT_FOLDING char wl_folded; /* TRUE when this is a range of folded lines */ linenr_T wl_lastlnum; /* last buffer line number for logical line */ #endif } wline_T; /* * Windows are kept in a tree of frames. Each frame has a column (FR_COL) * or row (FR_ROW) layout or is a leaf, which has a window. */ struct frame_S { char fr_layout; /* FR_LEAF, FR_COL or FR_ROW */ #ifdef FEAT_VERTSPLIT int fr_width; int fr_newwidth; /* new width used in win_equal_rec() */ #endif int fr_height; int fr_newheight; /* new height used in win_equal_rec() */ frame_T *fr_parent; /* containing frame or NULL */ frame_T *fr_next; /* frame right or below in same parent, NULL for first */ frame_T *fr_prev; /* frame left or above in same parent, NULL for last */ /* fr_child and fr_win are mutually exclusive */ frame_T *fr_child; /* first contained frame */ win_T *fr_win; /* window that fills this frame */ }; #define FR_LEAF 0 /* frame is a leaf */ #define FR_ROW 1 /* frame with a row of windows */ #define FR_COL 2 /* frame with a column of windows */ /* * Struct used for highlighting 'hlsearch' matches, matches defined by * ":match" and matches defined by match functions. * For 'hlsearch' there is one pattern for all windows. For ":match" and the * match functions there is a different pattern for each window. */ typedef struct { regmmatch_T rm; /* points to the regexp program; contains last found match (may continue in next line) */ buf_T *buf; /* the buffer to search for a match */ linenr_T lnum; /* the line to search for a match */ int attr; /* attributes to be used for a match */ int attr_cur; /* attributes currently active in win_line() */ linenr_T first_lnum; /* first lnum to search for multi-line pat */ colnr_T startcol; /* in win_line() points to char where HL starts */ colnr_T endcol; /* in win_line() points to char where HL ends */ #ifdef FEAT_RELTIME proftime_T tm; /* for a time limit */ #endif } match_T; /* * matchitem_T provides a linked list for storing match items for ":match" and * the match functions. */ typedef struct matchitem matchitem_T; struct matchitem { matchitem_T *next; int id; /* match ID */ int priority; /* match priority */ char_u *pattern; /* pattern to highlight */ int hlg_id; /* highlight group ID */ regmmatch_T match; /* regexp program for pattern */ match_T hl; /* struct for doing the actual highlighting */ }; /* * Structure which contains all information that belongs to a window * * All row numbers are relative to the start of the window, except w_winrow. */ struct window_S { buf_T *w_buffer; /* buffer we are a window into (used often, keep it the first item!) */ #if defined(FEAT_SYN_HL) || defined(FEAT_SPELL) synblock_T *w_s; /* for :ownsyntax */ #endif #ifdef FEAT_WINDOWS win_T *w_prev; /* link to previous window */ win_T *w_next; /* link to next window */ #endif #ifdef FEAT_AUTOCMD int w_closing; /* window is being closed, don't let autocommands close it too. */ #endif frame_T *w_frame; /* frame containing this window */ pos_T w_cursor; /* cursor position in buffer */ colnr_T w_curswant; /* The column we'd like to be at. This is used to try to stay in the same column for up/down cursor motions. */ int w_set_curswant; /* If set, then update w_curswant the next time through cursupdate() to the current virtual column */ #ifdef FEAT_VISUAL /* * the next six are used to update the visual part */ char w_old_visual_mode; /* last known VIsual_mode */ linenr_T w_old_cursor_lnum; /* last known end of visual part */ colnr_T w_old_cursor_fcol; /* first column for block visual part */ colnr_T w_old_cursor_lcol; /* last column for block visual part */ linenr_T w_old_visual_lnum; /* last known start of visual part */ colnr_T w_old_visual_col; /* last known start of visual part */ colnr_T w_old_curswant; /* last known value of Curswant */ #endif /* * "w_topline", "w_leftcol" and "w_skipcol" specify the offsets for * displaying the buffer. */ linenr_T w_topline; /* buffer line number of the line at the top of the window */ #ifdef FEAT_AUTOCMD char w_topline_was_set; /* flag set to TRUE when topline is set, e.g. by winrestview() */ #endif #ifdef FEAT_DIFF int w_topfill; /* number of filler lines above w_topline */ int w_old_topfill; /* w_topfill at last redraw */ int w_botfill; /* TRUE when filler lines are actually below w_topline (at end of file) */ int w_old_botfill; /* w_botfill at last redraw */ #endif colnr_T w_leftcol; /* window column number of the left most character in the window; used when 'wrap' is off */ colnr_T w_skipcol; /* starting column when a single line doesn't fit in the window */ /* * Layout of the window in the screen. * May need to add "msg_scrolled" to "w_winrow" in rare situations. */ #ifdef FEAT_WINDOWS int w_winrow; /* first row of window in screen */ #endif int w_height; /* number of rows in window, excluding status/command line(s) */ #ifdef FEAT_WINDOWS int w_status_height; /* number of status lines (0 or 1) */ #endif #ifdef FEAT_VERTSPLIT int w_wincol; /* Leftmost column of window in screen. use W_WINCOL() */ int w_width; /* Width of window, excluding separation. use W_WIDTH() */ int w_vsep_width; /* Number of separator columns (0 or 1). use W_VSEP_WIDTH() */ #endif /* * === start of cached values ==== */ /* * Recomputing is minimized by storing the result of computations. * Use functions in screen.c to check if they are valid and to update. * w_valid is a bitfield of flags, which indicate if specific values are * valid or need to be recomputed. See screen.c for values. */ int w_valid; pos_T w_valid_cursor; /* last known position of w_cursor, used to adjust w_valid */ colnr_T w_valid_leftcol; /* last known w_leftcol */ /* * w_cline_height is the number of physical lines taken by the buffer line * that the cursor is on. We use this to avoid extra calls to plines(). */ int w_cline_height; /* current size of cursor line */ #ifdef FEAT_FOLDING int w_cline_folded; /* cursor line is folded */ #endif int w_cline_row; /* starting row of the cursor line */ colnr_T w_virtcol; /* column number of the cursor in the buffer line, as opposed to the column number we're at on the screen. This makes a difference on lines which span more than one screen line or when w_leftcol is non-zero */ /* * w_wrow and w_wcol specify the cursor position in the window. * This is related to positions in the window, not in the display or * buffer, thus w_wrow is relative to w_winrow. */ int w_wrow, w_wcol; /* cursor position in window */ linenr_T w_botline; /* number of the line below the bottom of the screen */ int w_empty_rows; /* number of ~ rows in window */ #ifdef FEAT_DIFF int w_filler_rows; /* number of filler rows at the end of the window */ #endif /* * Info about the lines currently in the window is remembered to avoid * recomputing it every time. The allocated size of w_lines[] is Rows. * Only the w_lines_valid entries are actually valid. * When the display is up-to-date w_lines[0].wl_lnum is equal to w_topline * and w_lines[w_lines_valid - 1].wl_lnum is equal to w_botline. * Between changing text and updating the display w_lines[] represents * what is currently displayed. wl_valid is reset to indicated this. * This is used for efficient redrawing. */ int w_lines_valid; /* number of valid entries */ wline_T *w_lines; #ifdef FEAT_FOLDING garray_T w_folds; /* array of nested folds */ char w_fold_manual; /* when TRUE: some folds are opened/closed manually */ char w_foldinvalid; /* when TRUE: folding needs to be recomputed */ #endif #ifdef FEAT_LINEBREAK int w_nrwidth; /* width of 'number' and 'relativenumber' column being used */ #endif /* * === end of cached values === */ int w_redr_type; /* type of redraw to be performed on win */ int w_upd_rows; /* number of window lines to update when w_redr_type is REDRAW_TOP */ linenr_T w_redraw_top; /* when != 0: first line needing redraw */ linenr_T w_redraw_bot; /* when != 0: last line needing redraw */ #ifdef FEAT_WINDOWS int w_redr_status; /* if TRUE status line must be redrawn */ #endif #ifdef FEAT_CMDL_INFO /* remember what is shown in the ruler for this window (if 'ruler' set) */ pos_T w_ru_cursor; /* cursor position shown in ruler */ colnr_T w_ru_virtcol; /* virtcol shown in ruler */ linenr_T w_ru_topline; /* topline shown in ruler */ linenr_T w_ru_line_count; /* line count used for ruler */ # ifdef FEAT_DIFF int w_ru_topfill; /* topfill shown in ruler */ # endif char w_ru_empty; /* TRUE if ruler shows 0-1 (empty line) */ #endif int w_alt_fnum; /* alternate file (for # and CTRL-^) */ #ifdef FEAT_WINDOWS alist_T *w_alist; /* pointer to arglist for this window */ #endif int w_arg_idx; /* current index in argument list (can be out of range!) */ int w_arg_idx_invalid; /* editing another file than w_arg_idx */ char_u *w_localdir; /* absolute path of local directory or NULL */ /* * Options local to a window. * They are local because they influence the layout of the window or * depend on the window layout. * There are two values: w_onebuf_opt is local to the buffer currently in * this window, w_allbuf_opt is for all buffers in this window. */ winopt_T w_onebuf_opt; winopt_T w_allbuf_opt; /* A few options have local flags for P_INSECURE. */ #ifdef FEAT_STL_OPT long_u w_p_stl_flags; /* flags for 'statusline' */ #endif #ifdef FEAT_EVAL long_u w_p_fde_flags; /* flags for 'foldexpr' */ long_u w_p_fdt_flags; /* flags for 'foldtext' */ #endif #ifdef FEAT_SYN_HL int *w_p_cc_cols; /* array of columns to highlight or NULL */ #endif /* transform a pointer to a "onebuf" option into a "allbuf" option */ #define GLOBAL_WO(p) ((char *)p + sizeof(winopt_T)) #ifdef FEAT_SCROLLBIND long w_scbind_pos; #endif #ifdef FEAT_EVAL dictitem_T w_winvar; /* variable for "w:" Dictionary */ dict_T w_vars; /* internal variables, local to window */ #endif #if defined(FEAT_RIGHTLEFT) && defined(FEAT_FKMAP) int w_farsi; /* for the window dependent Farsi functions */ #endif /* * The w_prev_pcmark field is used to check whether we really did jump to * a new line after setting the w_pcmark. If not, then we revert to * using the previous w_pcmark. */ pos_T w_pcmark; /* previous context mark */ pos_T w_prev_pcmark; /* previous w_pcmark */ #ifdef FEAT_JUMPLIST /* * the jumplist contains old cursor positions */ xfmark_T w_jumplist[JUMPLISTSIZE]; int w_jumplistlen; /* number of active entries */ int w_jumplistidx; /* current position */ int w_changelistidx; /* current position in b_changelist */ #endif #ifdef FEAT_SEARCH_EXTRA matchitem_T *w_match_head; /* head of match list */ int w_next_match_id; /* next match ID */ #endif /* * the tagstack grows from 0 upwards: * entry 0: older * entry 1: newer * entry 2: newest */ taggy_T w_tagstack[TAGSTACKSIZE]; /* the tag stack */ int w_tagstackidx; /* idx just below active entry */ int w_tagstacklen; /* number of tags on stack */ /* * w_fraction is the fractional row of the cursor within the window, from * 0 at the top row to FRACTION_MULT at the last row. * w_prev_fraction_row was the actual cursor row when w_fraction was last * calculated. */ int w_fraction; int w_prev_fraction_row; #ifdef FEAT_GUI scrollbar_T w_scrollbars[2]; /* vert. Scrollbars for this window */ #endif #ifdef FEAT_LINEBREAK linenr_T w_nrwidth_line_count; /* line count when ml_nrwidth_width * was computed. */ int w_nrwidth_width; /* nr of chars to print line count. */ #endif #ifdef FEAT_QUICKFIX qf_info_T *w_llist; /* Location list for this window */ /* * Location list reference used in the location list window. * In a non-location list window, w_llist_ref is NULL. */ qf_info_T *w_llist_ref; #endif #ifdef FEAT_MZSCHEME void *w_mzscheme_ref; /* The MzScheme value for this window */ #endif #ifdef FEAT_PERL void *w_perl_private; #endif #ifdef FEAT_PYTHON void *w_python_ref; /* The Python value for this window */ #endif #ifdef FEAT_PYTHON3 void *w_python3_ref; /* The Python value for this window */ #endif #ifdef FEAT_TCL void *w_tcl_ref; #endif #ifdef FEAT_RUBY void *w_ruby_ref; #endif }; /* * Arguments for operators. */ typedef struct oparg_S { int op_type; /* current pending operator type */ int regname; /* register to use for the operator */ int motion_type; /* type of the current cursor motion */ int motion_force; /* force motion type: 'v', 'V' or CTRL-V */ int use_reg_one; /* TRUE if delete uses reg 1 even when not linewise */ int inclusive; /* TRUE if char motion is inclusive (only valid when motion_type is MCHAR */ int end_adjusted; /* backuped b_op_end one char (only used by do_format()) */ pos_T start; /* start of the operator */ pos_T end; /* end of the operator */ pos_T cursor_start; /* cursor position before motion for "gw" */ long line_count; /* number of lines from op_start to op_end (inclusive) */ int empty; /* op_start and op_end the same (only used by do_change()) */ #ifdef FEAT_VISUAL int is_VIsual; /* operator on Visual area */ int block_mode; /* current operator is Visual block mode */ #endif colnr_T start_vcol; /* start col for block mode operator */ colnr_T end_vcol; /* end col for block mode operator */ #ifdef FEAT_AUTOCMD long prev_opcount; /* ca.opcount saved for K_CURSORHOLD */ long prev_count0; /* ca.count0 saved for K_CURSORHOLD */ #endif } oparg_T; /* * Arguments for Normal mode commands. */ typedef struct cmdarg_S { oparg_T *oap; /* Operator arguments */ int prechar; /* prefix character (optional, always 'g') */ int cmdchar; /* command character */ int nchar; /* next command character (optional) */ #ifdef FEAT_MBYTE int ncharC1; /* first composing character (optional) */ int ncharC2; /* second composing character (optional) */ #endif int extra_char; /* yet another character (optional) */ long opcount; /* count before an operator */ long count0; /* count before command, default 0 */ long count1; /* count before command, default 1 */ int arg; /* extra argument from nv_cmds[] */ int retval; /* return: CA_* values */ char_u *searchbuf; /* return: pointer to search pattern or NULL */ } cmdarg_T; /* values for retval: */ #define CA_COMMAND_BUSY 1 /* skip restarting edit() once */ #define CA_NO_ADJ_OP_END 2 /* don't adjust operator end */ #ifdef CURSOR_SHAPE /* * struct to store values from 'guicursor' and 'mouseshape' */ /* Indexes in shape_table[] */ #define SHAPE_IDX_N 0 /* Normal mode */ #define SHAPE_IDX_V 1 /* Visual mode */ #define SHAPE_IDX_I 2 /* Insert mode */ #define SHAPE_IDX_R 3 /* Replace mode */ #define SHAPE_IDX_C 4 /* Command line Normal mode */ #define SHAPE_IDX_CI 5 /* Command line Insert mode */ #define SHAPE_IDX_CR 6 /* Command line Replace mode */ #define SHAPE_IDX_O 7 /* Operator-pending mode */ #define SHAPE_IDX_VE 8 /* Visual mode with 'selection' exclusive */ #define SHAPE_IDX_CLINE 9 /* On command line */ #define SHAPE_IDX_STATUS 10 /* A status line */ #define SHAPE_IDX_SDRAG 11 /* dragging a status line */ #define SHAPE_IDX_VSEP 12 /* A vertical separator line */ #define SHAPE_IDX_VDRAG 13 /* dragging a vertical separator line */ #define SHAPE_IDX_MORE 14 /* Hit-return or More */ #define SHAPE_IDX_MOREL 15 /* Hit-return or More in last line */ #define SHAPE_IDX_SM 16 /* showing matching paren */ #define SHAPE_IDX_COUNT 17 #define SHAPE_BLOCK 0 /* block cursor */ #define SHAPE_HOR 1 /* horizontal bar cursor */ #define SHAPE_VER 2 /* vertical bar cursor */ #define MSHAPE_NUMBERED 1000 /* offset for shapes identified by number */ #define MSHAPE_HIDE 1 /* hide mouse pointer */ #define SHAPE_MOUSE 1 /* used for mouse pointer shape */ #define SHAPE_CURSOR 2 /* used for text cursor shape */ typedef struct cursor_entry { int shape; /* one of the SHAPE_ defines */ int mshape; /* one of the MSHAPE defines */ int percentage; /* percentage of cell for bar */ long blinkwait; /* blinking, wait time before blinking starts */ long blinkon; /* blinking, on time */ long blinkoff; /* blinking, off time */ int id; /* highlight group ID */ int id_lm; /* highlight group ID for :lmap mode */ char *name; /* mode name (fixed) */ char used_for; /* SHAPE_MOUSE and/or SHAPE_CURSOR */ } cursorentry_T; #endif /* CURSOR_SHAPE */ #ifdef FEAT_MENU /* Indices into vimmenu_T->strings[] and vimmenu_T->noremap[] for each mode */ #define MENU_INDEX_INVALID -1 #define MENU_INDEX_NORMAL 0 #define MENU_INDEX_VISUAL 1 #define MENU_INDEX_SELECT 2 #define MENU_INDEX_OP_PENDING 3 #define MENU_INDEX_INSERT 4 #define MENU_INDEX_CMDLINE 5 #define MENU_INDEX_TIP 6 #define MENU_MODES 7 /* Menu modes */ #define MENU_NORMAL_MODE (1 << MENU_INDEX_NORMAL) #define MENU_VISUAL_MODE (1 << MENU_INDEX_VISUAL) #define MENU_SELECT_MODE (1 << MENU_INDEX_SELECT) #define MENU_OP_PENDING_MODE (1 << MENU_INDEX_OP_PENDING) #define MENU_INSERT_MODE (1 << MENU_INDEX_INSERT) #define MENU_CMDLINE_MODE (1 << MENU_INDEX_CMDLINE) #define MENU_TIP_MODE (1 << MENU_INDEX_TIP) #define MENU_ALL_MODES ((1 << MENU_INDEX_TIP) - 1) /*note MENU_INDEX_TIP is not a 'real' mode*/ /* Start a menu name with this to not include it on the main menu bar */ #define MNU_HIDDEN_CHAR ']' typedef struct VimMenu vimmenu_T; struct VimMenu { int modes; /* Which modes is this menu visible for? */ int enabled; /* for which modes the menu is enabled */ char_u *name; /* Name of menu, possibly translated */ char_u *dname; /* Displayed Name ("name" without '&') */ #ifdef FEAT_MULTI_LANG char_u *en_name; /* "name" untranslated, NULL when "name" * was not translated */ char_u *en_dname; /* "dname" untranslated, NULL when "dname" * was not translated */ #endif int mnemonic; /* mnemonic key (after '&') */ char_u *actext; /* accelerator text (after TAB) */ int priority; /* Menu order priority */ #ifdef FEAT_GUI void (*cb) __ARGS((vimmenu_T *)); /* Call-back routine */ #endif #ifdef FEAT_TOOLBAR char_u *iconfile; /* name of file for icon or NULL */ int iconidx; /* icon index (-1 if not set) */ int icon_builtin; /* icon names is BuiltIn{nr} */ #endif char_u *strings[MENU_MODES]; /* Mapped string for each mode */ int noremap[MENU_MODES]; /* A REMAP_ flag for each mode */ char silent[MENU_MODES]; /* A silent flag for each mode */ vimmenu_T *children; /* Children of sub-menu */ vimmenu_T *parent; /* Parent of menu */ vimmenu_T *next; /* Next item in menu */ #ifdef FEAT_GUI_X11 Widget id; /* Manage this to enable item */ Widget submenu_id; /* If this is submenu, add children here */ #endif #ifdef FEAT_GUI_GTK GtkWidget *id; /* Manage this to enable item */ GtkWidget *submenu_id; /* If this is submenu, add children here */ GtkWidget *tearoff_handle; GtkWidget *label; /* Used by "set wak=" code. */ #endif #ifdef FEAT_GUI_MOTIF int sensitive; /* turn button on/off */ char **xpm; /* pixmap data */ char *xpm_fname; /* file with pixmap data */ #endif #ifdef FEAT_GUI_ATHENA Pixmap image; /* Toolbar image */ #endif #ifdef FEAT_BEVAL_TIP BalloonEval *tip; /* tooltip for this menu item */ #endif #ifdef FEAT_GUI_W16 UINT id; /* Id of menu item */ HMENU submenu_id; /* If this is submenu, add children here */ #endif #ifdef FEAT_GUI_W32 UINT id; /* Id of menu item */ HMENU submenu_id; /* If this is submenu, add children here */ HWND tearoff_handle; /* hWnd of tearoff if created */ #endif #ifdef FEAT_GUI_MAC /* MenuHandle id; */ /* short index; */ /* the item index within the father menu */ short menu_id; /* the menu id to which this item belong */ short submenu_id; /* the menu id of the children (could be get through some tricks) */ MenuHandle menu_handle; MenuHandle submenu_handle; #endif #ifdef FEAT_GUI_PHOTON PtWidget_t *id; PtWidget_t *submenu_id; #endif }; #else /* For generating prototypes when FEAT_MENU isn't defined. */ typedef int vimmenu_T; #endif /* FEAT_MENU */ /* * Struct to save values in before executing autocommands for a buffer that is * not the current buffer. Without FEAT_AUTOCMD only "curbuf" is remembered. */ typedef struct { buf_T *save_curbuf; /* saved curbuf */ #ifdef FEAT_AUTOCMD int use_aucmd_win; /* using aucmd_win */ win_T *save_curwin; /* saved curwin */ win_T *new_curwin; /* new curwin */ buf_T *new_curbuf; /* new curbuf */ char_u *globaldir; /* saved value of globaldir */ #endif } aco_save_T; /* * Generic option table item, only used for printer at the moment. */ typedef struct { const char *name; int hasnum; long number; char_u *string; /* points into option string */ int strlen; int present; } option_table_T; /* * Structure to hold printing color and font attributes. */ typedef struct { long_u fg_color; long_u bg_color; int bold; int italic; int underline; int undercurl; } prt_text_attr_T; /* * Structure passed back to the generic printer code. */ typedef struct { int n_collated_copies; int n_uncollated_copies; int duplex; int chars_per_line; int lines_per_page; int has_color; prt_text_attr_T number; #ifdef FEAT_SYN_HL int modec; int do_syntax; #endif int user_abort; char_u *jobname; #ifdef FEAT_POSTSCRIPT char_u *outfile; char_u *arguments; #endif } prt_settings_T; #define PRINT_NUMBER_WIDTH 8 /* * Used for popup menu items. */ typedef struct { char_u *pum_text; /* main menu text */ char_u *pum_kind; /* extra kind text (may be truncated) */ char_u *pum_extra; /* extra menu text (may be truncated) */ char_u *pum_info; /* extra info */ } pumitem_T; /* * Structure used for get_tagfname(). */ typedef struct { char_u *tn_tags; /* value of 'tags' when starting */ char_u *tn_np; /* current position in tn_tags */ int tn_did_filefind_init; int tn_hf_idx; void *tn_search_ctx; } tagname_T; /* * Array indexes used for cptext argument of ins_compl_add(). */ #define CPT_ABBR 0 /* "abbr" */ #define CPT_MENU 1 /* "menu" */ #define CPT_KIND 2 /* "kind" */ #define CPT_INFO 3 /* "info" */ #define CPT_COUNT 4 /* Number of entries */ typedef struct { UINT32_T total[2]; UINT32_T state[8]; char_u buffer[64]; } context_sha256_T;
zyz2011-vim
src/structs.h
C
gpl2
80,462
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * Multibyte extensions partly by Sung-Hoon Baek * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * mbyte.c: Code specifically for handling multi-byte characters. * * The encoding used in the core is set with 'encoding'. When 'encoding' is * changed, the following four variables are set (for speed). * Currently these types of character encodings are supported: * * "enc_dbcs" When non-zero it tells the type of double byte character * encoding (Chinese, Korean, Japanese, etc.). * The cell width on the display is equal to the number of * bytes. (exception: DBCS_JPNU with first byte 0x8e) * Recognizing the first or second byte is difficult, it * requires checking a byte sequence from the start. * "enc_utf8" When TRUE use Unicode characters in UTF-8 encoding. * The cell width on the display needs to be determined from * the character value. * Recognizing bytes is easy: 0xxx.xxxx is a single-byte * char, 10xx.xxxx is a trailing byte, 11xx.xxxx is a leading * byte of a multi-byte character. * To make things complicated, up to six composing characters * are allowed. These are drawn on top of the first char. * For most editing the sequence of bytes with composing * characters included is considered to be one character. * "enc_unicode" When 2 use 16-bit Unicode characters (or UTF-16). * When 4 use 32-but Unicode characters. * Internally characters are stored in UTF-8 encoding to * avoid NUL bytes. Conversion happens when doing I/O. * "enc_utf8" will also be TRUE. * * "has_mbyte" is set when "enc_dbcs" or "enc_utf8" is non-zero. * * If none of these is TRUE, 8-bit bytes are used for a character. The * encoding isn't currently specified (TODO). * * 'encoding' specifies the encoding used in the core. This is in registers, * text manipulation, buffers, etc. Conversion has to be done when characters * in another encoding are received or send: * * clipboard * ^ * | (2) * V * +---------------+ * (1) | | (3) * keyboard ----->| core |-----> display * | | * +---------------+ * ^ * | (4) * V * file * * (1) Typed characters arrive in the current locale. Conversion is to be * done when 'encoding' is different from 'termencoding'. * (2) Text will be made available with the encoding specified with * 'encoding'. If this is not sufficient, system-specific conversion * might be required. * (3) For the GUI the correct font must be selected, no conversion done. * Otherwise, conversion is to be done when 'encoding' differs from * 'termencoding'. (Different in the GTK+ 2 port -- 'termencoding' * is always used for both input and output and must always be set to * "utf-8". gui_mch_init() does this automatically.) * (4) The encoding of the file is specified with 'fileencoding'. Conversion * is to be done when it's different from 'encoding'. * * The viminfo file is a special case: Only text is converted, not file names. * Vim scripts may contain an ":encoding" command. This has an effect for * some commands, like ":menutrans" */ #include "vim.h" #ifdef WIN32UNIX # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # include <windows.h> # ifdef WIN32 # undef WIN32 /* Some windows.h define WIN32, we don't want that here. */ # endif #endif #if (defined(WIN3264) || defined(WIN32UNIX)) && !defined(__MINGW32__) # include <winnls.h> #endif #ifdef FEAT_GUI_X11 # include <X11/Intrinsic.h> #endif #ifdef X_LOCALE #include <X11/Xlocale.h> #endif #if defined(FEAT_GUI_GTK) && defined(FEAT_XIM) # include <gdk/gdkkeysyms.h> # ifdef WIN3264 # include <gdk/gdkwin32.h> # else # include <gdk/gdkx.h> # endif #endif #ifdef HAVE_WCHAR_H # include <wchar.h> #endif #if 0 /* This has been disabled, because several people reported problems with the * wcwidth() and iswprint() library functions, esp. for Hebrew. */ # ifdef __STDC_ISO_10646__ # define USE_WCHAR_FUNCTIONS # endif #endif #if defined(FEAT_MBYTE) || defined(PROTO) static int enc_canon_search __ARGS((char_u *name)); static int dbcs_char2len __ARGS((int c)); static int dbcs_char2bytes __ARGS((int c, char_u *buf)); static int dbcs_ptr2len __ARGS((char_u *p)); static int dbcs_ptr2len_len __ARGS((char_u *p, int size)); static int utf_ptr2cells_len __ARGS((char_u *p, int size)); static int dbcs_char2cells __ARGS((int c)); static int dbcs_ptr2cells_len __ARGS((char_u *p, int size)); static int dbcs_ptr2char __ARGS((char_u *p)); static int utf_safe_read_char_adv __ARGS((char_u **s, size_t *n)); /* * Lookup table to quickly get the length in bytes of a UTF-8 character from * the first byte of a UTF-8 string. * Bytes which are illegal when used as the first byte have a 1. * The NUL byte has length 1. */ static char utf8len_tab[256] = { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,6,6,1,1, }; /* * Like utf8len_tab above, but using a zero for illegal lead bytes. */ static char utf8len_tab_zero[256] = { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,6,6,0,0, }; /* * XIM often causes trouble. Define XIM_DEBUG to get a log of XIM callbacks * in the "xim.log" file. */ /* #define XIM_DEBUG */ #ifdef XIM_DEBUG static void xim_log(char *s, ...) { va_list arglist; static FILE *fd = NULL; if (fd == (FILE *)-1) return; if (fd == NULL) { fd = mch_fopen("xim.log", "w"); if (fd == NULL) { EMSG("Cannot open xim.log"); fd = (FILE *)-1; return; } } va_start(arglist, s); vfprintf(fd, s, arglist); va_end(arglist); } #endif #endif #if defined(FEAT_MBYTE) || defined(FEAT_POSTSCRIPT) || defined(PROTO) /* * Canonical encoding names and their properties. * "iso-8859-n" is handled by enc_canonize() directly. */ static struct { char *name; int prop; int codepage;} enc_canon_table[] = { #define IDX_LATIN_1 0 {"latin1", ENC_8BIT + ENC_LATIN1, 1252}, #define IDX_ISO_2 1 {"iso-8859-2", ENC_8BIT, 0}, #define IDX_ISO_3 2 {"iso-8859-3", ENC_8BIT, 0}, #define IDX_ISO_4 3 {"iso-8859-4", ENC_8BIT, 0}, #define IDX_ISO_5 4 {"iso-8859-5", ENC_8BIT, 0}, #define IDX_ISO_6 5 {"iso-8859-6", ENC_8BIT, 0}, #define IDX_ISO_7 6 {"iso-8859-7", ENC_8BIT, 0}, #define IDX_ISO_8 7 {"iso-8859-8", ENC_8BIT, 0}, #define IDX_ISO_9 8 {"iso-8859-9", ENC_8BIT, 0}, #define IDX_ISO_10 9 {"iso-8859-10", ENC_8BIT, 0}, #define IDX_ISO_11 10 {"iso-8859-11", ENC_8BIT, 0}, #define IDX_ISO_13 11 {"iso-8859-13", ENC_8BIT, 0}, #define IDX_ISO_14 12 {"iso-8859-14", ENC_8BIT, 0}, #define IDX_ISO_15 13 {"iso-8859-15", ENC_8BIT + ENC_LATIN9, 0}, #define IDX_KOI8_R 14 {"koi8-r", ENC_8BIT, 0}, #define IDX_KOI8_U 15 {"koi8-u", ENC_8BIT, 0}, #define IDX_UTF8 16 {"utf-8", ENC_UNICODE, 0}, #define IDX_UCS2 17 {"ucs-2", ENC_UNICODE + ENC_ENDIAN_B + ENC_2BYTE, 0}, #define IDX_UCS2LE 18 {"ucs-2le", ENC_UNICODE + ENC_ENDIAN_L + ENC_2BYTE, 0}, #define IDX_UTF16 19 {"utf-16", ENC_UNICODE + ENC_ENDIAN_B + ENC_2WORD, 0}, #define IDX_UTF16LE 20 {"utf-16le", ENC_UNICODE + ENC_ENDIAN_L + ENC_2WORD, 0}, #define IDX_UCS4 21 {"ucs-4", ENC_UNICODE + ENC_ENDIAN_B + ENC_4BYTE, 0}, #define IDX_UCS4LE 22 {"ucs-4le", ENC_UNICODE + ENC_ENDIAN_L + ENC_4BYTE, 0}, /* For debugging DBCS encoding on Unix. */ #define IDX_DEBUG 23 {"debug", ENC_DBCS, DBCS_DEBUG}, #define IDX_EUC_JP 24 {"euc-jp", ENC_DBCS, DBCS_JPNU}, #define IDX_SJIS 25 {"sjis", ENC_DBCS, DBCS_JPN}, #define IDX_EUC_KR 26 {"euc-kr", ENC_DBCS, DBCS_KORU}, #define IDX_EUC_CN 27 {"euc-cn", ENC_DBCS, DBCS_CHSU}, #define IDX_EUC_TW 28 {"euc-tw", ENC_DBCS, DBCS_CHTU}, #define IDX_BIG5 29 {"big5", ENC_DBCS, DBCS_CHT}, /* MS-DOS and MS-Windows codepages are included here, so that they can be * used on Unix too. Most of them are similar to ISO-8859 encodings, but * not exactly the same. */ #define IDX_CP437 30 {"cp437", ENC_8BIT, 437}, /* like iso-8859-1 */ #define IDX_CP737 31 {"cp737", ENC_8BIT, 737}, /* like iso-8859-7 */ #define IDX_CP775 32 {"cp775", ENC_8BIT, 775}, /* Baltic */ #define IDX_CP850 33 {"cp850", ENC_8BIT, 850}, /* like iso-8859-4 */ #define IDX_CP852 34 {"cp852", ENC_8BIT, 852}, /* like iso-8859-1 */ #define IDX_CP855 35 {"cp855", ENC_8BIT, 855}, /* like iso-8859-2 */ #define IDX_CP857 36 {"cp857", ENC_8BIT, 857}, /* like iso-8859-5 */ #define IDX_CP860 37 {"cp860", ENC_8BIT, 860}, /* like iso-8859-9 */ #define IDX_CP861 38 {"cp861", ENC_8BIT, 861}, /* like iso-8859-1 */ #define IDX_CP862 39 {"cp862", ENC_8BIT, 862}, /* like iso-8859-1 */ #define IDX_CP863 40 {"cp863", ENC_8BIT, 863}, /* like iso-8859-8 */ #define IDX_CP865 41 {"cp865", ENC_8BIT, 865}, /* like iso-8859-1 */ #define IDX_CP866 42 {"cp866", ENC_8BIT, 866}, /* like iso-8859-5 */ #define IDX_CP869 43 {"cp869", ENC_8BIT, 869}, /* like iso-8859-7 */ #define IDX_CP874 44 {"cp874", ENC_8BIT, 874}, /* Thai */ #define IDX_CP932 45 {"cp932", ENC_DBCS, DBCS_JPN}, #define IDX_CP936 46 {"cp936", ENC_DBCS, DBCS_CHS}, #define IDX_CP949 47 {"cp949", ENC_DBCS, DBCS_KOR}, #define IDX_CP950 48 {"cp950", ENC_DBCS, DBCS_CHT}, #define IDX_CP1250 49 {"cp1250", ENC_8BIT, 1250}, /* Czech, Polish, etc. */ #define IDX_CP1251 50 {"cp1251", ENC_8BIT, 1251}, /* Cyrillic */ /* cp1252 is considered to be equal to latin1 */ #define IDX_CP1253 51 {"cp1253", ENC_8BIT, 1253}, /* Greek */ #define IDX_CP1254 52 {"cp1254", ENC_8BIT, 1254}, /* Turkish */ #define IDX_CP1255 53 {"cp1255", ENC_8BIT, 1255}, /* Hebrew */ #define IDX_CP1256 54 {"cp1256", ENC_8BIT, 1256}, /* Arabic */ #define IDX_CP1257 55 {"cp1257", ENC_8BIT, 1257}, /* Baltic */ #define IDX_CP1258 56 {"cp1258", ENC_8BIT, 1258}, /* Vietnamese */ #define IDX_MACROMAN 57 {"macroman", ENC_8BIT + ENC_MACROMAN, 0}, /* Mac OS */ #define IDX_DECMCS 58 {"dec-mcs", ENC_8BIT, 0}, /* DEC MCS */ #define IDX_HPROMAN8 59 {"hp-roman8", ENC_8BIT, 0}, /* HP Roman8 */ #define IDX_COUNT 60 }; /* * Aliases for encoding names. */ static struct { char *name; int canon;} enc_alias_table[] = { {"ansi", IDX_LATIN_1}, {"iso-8859-1", IDX_LATIN_1}, {"latin2", IDX_ISO_2}, {"latin3", IDX_ISO_3}, {"latin4", IDX_ISO_4}, {"cyrillic", IDX_ISO_5}, {"arabic", IDX_ISO_6}, {"greek", IDX_ISO_7}, #ifdef WIN3264 {"hebrew", IDX_CP1255}, #else {"hebrew", IDX_ISO_8}, #endif {"latin5", IDX_ISO_9}, {"turkish", IDX_ISO_9}, /* ? */ {"latin6", IDX_ISO_10}, {"nordic", IDX_ISO_10}, /* ? */ {"thai", IDX_ISO_11}, /* ? */ {"latin7", IDX_ISO_13}, {"latin8", IDX_ISO_14}, {"latin9", IDX_ISO_15}, {"utf8", IDX_UTF8}, {"unicode", IDX_UCS2}, {"ucs2", IDX_UCS2}, {"ucs2be", IDX_UCS2}, {"ucs-2be", IDX_UCS2}, {"ucs2le", IDX_UCS2LE}, {"utf16", IDX_UTF16}, {"utf16be", IDX_UTF16}, {"utf-16be", IDX_UTF16}, {"utf16le", IDX_UTF16LE}, {"ucs4", IDX_UCS4}, {"ucs4be", IDX_UCS4}, {"ucs-4be", IDX_UCS4}, {"ucs4le", IDX_UCS4LE}, {"utf32", IDX_UCS4}, {"utf-32", IDX_UCS4}, {"utf32be", IDX_UCS4}, {"utf-32be", IDX_UCS4}, {"utf32le", IDX_UCS4LE}, {"utf-32le", IDX_UCS4LE}, {"932", IDX_CP932}, {"949", IDX_CP949}, {"936", IDX_CP936}, {"gbk", IDX_CP936}, {"950", IDX_CP950}, {"eucjp", IDX_EUC_JP}, {"unix-jis", IDX_EUC_JP}, {"ujis", IDX_EUC_JP}, {"shift-jis", IDX_SJIS}, {"euckr", IDX_EUC_KR}, {"5601", IDX_EUC_KR}, /* Sun: KS C 5601 */ {"euccn", IDX_EUC_CN}, {"gb2312", IDX_EUC_CN}, {"euctw", IDX_EUC_TW}, #if defined(WIN3264) || defined(WIN32UNIX) || defined(MACOS) {"japan", IDX_CP932}, {"korea", IDX_CP949}, {"prc", IDX_CP936}, {"chinese", IDX_CP936}, {"taiwan", IDX_CP950}, {"big5", IDX_CP950}, #else {"japan", IDX_EUC_JP}, {"korea", IDX_EUC_KR}, {"prc", IDX_EUC_CN}, {"chinese", IDX_EUC_CN}, {"taiwan", IDX_EUC_TW}, {"cp950", IDX_BIG5}, {"950", IDX_BIG5}, #endif {"mac", IDX_MACROMAN}, {"mac-roman", IDX_MACROMAN}, {NULL, 0} }; #ifndef CP_UTF8 # define CP_UTF8 65001 /* magic number from winnls.h */ #endif /* * Find encoding "name" in the list of canonical encoding names. * Returns -1 if not found. */ static int enc_canon_search(name) char_u *name; { int i; for (i = 0; i < IDX_COUNT; ++i) if (STRCMP(name, enc_canon_table[i].name) == 0) return i; return -1; } #endif #if defined(FEAT_MBYTE) || defined(PROTO) /* * Find canonical encoding "name" in the list and return its properties. * Returns 0 if not found. */ int enc_canon_props(name) char_u *name; { int i; i = enc_canon_search(name); if (i >= 0) return enc_canon_table[i].prop; #ifdef WIN3264 if (name[0] == 'c' && name[1] == 'p' && VIM_ISDIGIT(name[2])) { CPINFO cpinfo; /* Get info on this codepage to find out what it is. */ if (GetCPInfo(atoi(name + 2), &cpinfo) != 0) { if (cpinfo.MaxCharSize == 1) /* some single-byte encoding */ return ENC_8BIT; if (cpinfo.MaxCharSize == 2 && (cpinfo.LeadByte[0] != 0 || cpinfo.LeadByte[1] != 0)) /* must be a DBCS encoding */ return ENC_DBCS; } return 0; } #endif if (STRNCMP(name, "2byte-", 6) == 0) return ENC_DBCS; if (STRNCMP(name, "8bit-", 5) == 0 || STRNCMP(name, "iso-8859-", 9) == 0) return ENC_8BIT; return 0; } /* * Set up for using multi-byte characters. * Called in three cases: * - by main() to initialize (p_enc == NULL) * - by set_init_1() after 'encoding' was set to its default. * - by do_set() when 'encoding' has been set. * p_enc must have been passed through enc_canonize() already. * Sets the "enc_unicode", "enc_utf8", "enc_dbcs" and "has_mbyte" flags. * Fills mb_bytelen_tab[] and returns NULL when there are no problems. * When there is something wrong: Returns an error message and doesn't change * anything. */ char_u * mb_init() { int i; int idx; int n; int enc_dbcs_new = 0; #if defined(USE_ICONV) && !defined(WIN3264) && !defined(WIN32UNIX) \ && !defined(MACOS) # define LEN_FROM_CONV vimconv_T vimconv; char_u *p; #endif if (p_enc == NULL) { /* Just starting up: set the whole table to one's. */ for (i = 0; i < 256; ++i) mb_bytelen_tab[i] = 1; input_conv.vc_type = CONV_NONE; input_conv.vc_factor = 1; output_conv.vc_type = CONV_NONE; return NULL; } #ifdef WIN3264 if (p_enc[0] == 'c' && p_enc[1] == 'p' && VIM_ISDIGIT(p_enc[2])) { CPINFO cpinfo; /* Get info on this codepage to find out what it is. */ if (GetCPInfo(atoi(p_enc + 2), &cpinfo) != 0) { if (cpinfo.MaxCharSize == 1) { /* some single-byte encoding */ enc_unicode = 0; enc_utf8 = FALSE; } else if (cpinfo.MaxCharSize == 2 && (cpinfo.LeadByte[0] != 0 || cpinfo.LeadByte[1] != 0)) { /* must be a DBCS encoding, check below */ enc_dbcs_new = atoi(p_enc + 2); } else goto codepage_invalid; } else if (GetLastError() == ERROR_INVALID_PARAMETER) { codepage_invalid: return (char_u *)N_("E543: Not a valid codepage"); } } #endif else if (STRNCMP(p_enc, "8bit-", 5) == 0 || STRNCMP(p_enc, "iso-8859-", 9) == 0) { /* Accept any "8bit-" or "iso-8859-" name. */ enc_unicode = 0; enc_utf8 = FALSE; } else if (STRNCMP(p_enc, "2byte-", 6) == 0) { #ifdef WIN3264 /* Windows: accept only valid codepage numbers, check below. */ if (p_enc[6] != 'c' || p_enc[7] != 'p' || (enc_dbcs_new = atoi(p_enc + 8)) == 0) return e_invarg; #else /* Unix: accept any "2byte-" name, assume current locale. */ enc_dbcs_new = DBCS_2BYTE; #endif } else if ((idx = enc_canon_search(p_enc)) >= 0) { i = enc_canon_table[idx].prop; if (i & ENC_UNICODE) { /* Unicode */ enc_utf8 = TRUE; if (i & (ENC_2BYTE | ENC_2WORD)) enc_unicode = 2; else if (i & ENC_4BYTE) enc_unicode = 4; else enc_unicode = 0; } else if (i & ENC_DBCS) { /* 2byte, handle below */ enc_dbcs_new = enc_canon_table[idx].codepage; } else { /* Must be 8-bit. */ enc_unicode = 0; enc_utf8 = FALSE; } } else /* Don't know what encoding this is, reject it. */ return e_invarg; if (enc_dbcs_new != 0) { #ifdef WIN3264 /* Check if the DBCS code page is OK. */ if (!IsValidCodePage(enc_dbcs_new)) goto codepage_invalid; #endif enc_unicode = 0; enc_utf8 = FALSE; } enc_dbcs = enc_dbcs_new; has_mbyte = (enc_dbcs != 0 || enc_utf8); #ifdef WIN3264 enc_codepage = encname2codepage(p_enc); enc_latin9 = (STRCMP(p_enc, "iso-8859-15") == 0); #endif /* Detect an encoding that uses latin1 characters. */ enc_latin1like = (enc_utf8 || STRCMP(p_enc, "latin1") == 0 || STRCMP(p_enc, "iso-8859-15") == 0); /* * Set the function pointers. */ if (enc_utf8) { mb_ptr2len = utfc_ptr2len; mb_ptr2len_len = utfc_ptr2len_len; mb_char2len = utf_char2len; mb_char2bytes = utf_char2bytes; mb_ptr2cells = utf_ptr2cells; mb_ptr2cells_len = utf_ptr2cells_len; mb_char2cells = utf_char2cells; mb_off2cells = utf_off2cells; mb_ptr2char = utf_ptr2char; mb_head_off = utf_head_off; } else if (enc_dbcs != 0) { mb_ptr2len = dbcs_ptr2len; mb_ptr2len_len = dbcs_ptr2len_len; mb_char2len = dbcs_char2len; mb_char2bytes = dbcs_char2bytes; mb_ptr2cells = dbcs_ptr2cells; mb_ptr2cells_len = dbcs_ptr2cells_len; mb_char2cells = dbcs_char2cells; mb_off2cells = dbcs_off2cells; mb_ptr2char = dbcs_ptr2char; mb_head_off = dbcs_head_off; } else { mb_ptr2len = latin_ptr2len; mb_ptr2len_len = latin_ptr2len_len; mb_char2len = latin_char2len; mb_char2bytes = latin_char2bytes; mb_ptr2cells = latin_ptr2cells; mb_ptr2cells_len = latin_ptr2cells_len; mb_char2cells = latin_char2cells; mb_off2cells = latin_off2cells; mb_ptr2char = latin_ptr2char; mb_head_off = latin_head_off; } /* * Fill the mb_bytelen_tab[] for MB_BYTE2LEN(). */ #ifdef LEN_FROM_CONV /* When 'encoding' is different from the current locale mblen() won't * work. Use conversion to "utf-8" instead. */ vimconv.vc_type = CONV_NONE; if (enc_dbcs) { p = enc_locale(); if (p == NULL || STRCMP(p, p_enc) != 0) { convert_setup(&vimconv, p_enc, (char_u *)"utf-8"); vimconv.vc_fail = TRUE; } vim_free(p); } #endif for (i = 0; i < 256; ++i) { /* Our own function to reliably check the length of UTF-8 characters, * independent of mblen(). */ if (enc_utf8) n = utf8len_tab[i]; else if (enc_dbcs == 0) n = 1; else { #if defined(WIN3264) || defined(WIN32UNIX) /* enc_dbcs is set by setting 'fileencoding'. It becomes a Windows * CodePage identifier, which we can pass directly in to Windows * API */ n = IsDBCSLeadByteEx(enc_dbcs, (BYTE)i) ? 2 : 1; #else # if defined(MACOS) || defined(__amigaos4__) /* * if mblen() is not available, character which MSB is turned on * are treated as leading byte character. (note : This assumption * is not always true.) */ n = (i & 0x80) ? 2 : 1; # else char buf[MB_MAXBYTES + 1]; # ifdef X_LOCALE # ifndef mblen # define mblen _Xmblen # endif # endif if (i == NUL) /* just in case mblen() can't handle "" */ n = 1; else { buf[0] = i; buf[1] = 0; #ifdef LEN_FROM_CONV if (vimconv.vc_type != CONV_NONE) { /* * string_convert() should fail when converting the first * byte of a double-byte character. */ p = string_convert(&vimconv, (char_u *)buf, NULL); if (p != NULL) { vim_free(p); n = 1; } else n = 2; } else #endif { /* * mblen() should return -1 for invalid (means the leading * multibyte) character. However there are some platforms * where mblen() returns 0 for invalid character. * Therefore, following condition includes 0. */ ignored = mblen(NULL, 0); /* First reset the state. */ if (mblen(buf, (size_t)1) <= 0) n = 2; else n = 1; } } # endif #endif } mb_bytelen_tab[i] = n; } #ifdef LEN_FROM_CONV convert_setup(&vimconv, NULL, NULL); #endif /* The cell width depends on the type of multi-byte characters. */ (void)init_chartab(); /* When enc_utf8 is set or reset, (de)allocate ScreenLinesUC[] */ screenalloc(FALSE); /* When using Unicode, set default for 'fileencodings'. */ if (enc_utf8 && !option_was_set((char_u *)"fencs")) set_string_option_direct((char_u *)"fencs", -1, (char_u *)"ucs-bom,utf-8,default,latin1", OPT_FREE, 0); #if defined(HAVE_BIND_TEXTDOMAIN_CODESET) && defined(FEAT_GETTEXT) /* GNU gettext 0.10.37 supports this feature: set the codeset used for * translated messages independently from the current locale. */ (void)bind_textdomain_codeset(VIMPACKAGE, enc_utf8 ? "utf-8" : (char *)p_enc); #endif #ifdef WIN32 /* When changing 'encoding' while starting up, then convert the command * line arguments from the active codepage to 'encoding'. */ if (starting != 0) fix_arg_enc(); #endif #ifdef FEAT_AUTOCMD /* Fire an autocommand to let people do custom font setup. This must be * after Vim has been setup for the new encoding. */ apply_autocmds(EVENT_ENCODINGCHANGED, NULL, (char_u *)"", FALSE, curbuf); #endif #ifdef FEAT_SPELL /* Need to reload spell dictionaries */ spell_reload(); #endif return NULL; } /* * Return the size of the BOM for the current buffer: * 0 - no BOM * 2 - UCS-2 or UTF-16 BOM * 4 - UCS-4 BOM * 3 - UTF-8 BOM */ int bomb_size() { int n = 0; if (curbuf->b_p_bomb && !curbuf->b_p_bin) { if (*curbuf->b_p_fenc == NUL) { if (enc_utf8) { if (enc_unicode != 0) n = enc_unicode; else n = 3; } } else if (STRCMP(curbuf->b_p_fenc, "utf-8") == 0) n = 3; else if (STRNCMP(curbuf->b_p_fenc, "ucs-2", 5) == 0 || STRNCMP(curbuf->b_p_fenc, "utf-16", 6) == 0) n = 2; else if (STRNCMP(curbuf->b_p_fenc, "ucs-4", 5) == 0) n = 4; } return n; } /* * Remove all BOM from "s" by moving remaining text. */ void remove_bom(s) char_u *s; { if (enc_utf8) { char_u *p = s; while ((p = vim_strbyte(p, 0xef)) != NULL) { if (p[1] == 0xbb && p[2] == 0xbf) STRMOVE(p, p + 3); else ++p; } } } /* * Get class of pointer: * 0 for blank or NUL * 1 for punctuation * 2 for an (ASCII) word character * >2 for other word characters */ int mb_get_class(p) char_u *p; { if (MB_BYTE2LEN(p[0]) == 1) { if (p[0] == NUL || vim_iswhite(p[0])) return 0; if (vim_iswordc(p[0])) return 2; return 1; } if (enc_dbcs != 0 && p[0] != NUL && p[1] != NUL) return dbcs_class(p[0], p[1]); if (enc_utf8) return utf_class(utf_ptr2char(p)); return 0; } /* * Get class of a double-byte character. This always returns 3 or bigger. * TODO: Should return 1 for punctuation. */ int dbcs_class(lead, trail) unsigned lead; unsigned trail; { switch (enc_dbcs) { /* please add classfy routine for your language in here */ case DBCS_JPNU: /* ? */ case DBCS_JPN: { /* JIS code classification */ unsigned char lb = lead; unsigned char tb = trail; /* convert process code to JIS */ # if defined(WIN3264) || defined(WIN32UNIX) || defined(MACOS) /* process code is SJIS */ if (lb <= 0x9f) lb = (lb - 0x81) * 2 + 0x21; else lb = (lb - 0xc1) * 2 + 0x21; if (tb <= 0x7e) tb -= 0x1f; else if (tb <= 0x9e) tb -= 0x20; else { tb -= 0x7e; lb += 1; } # else /* * XXX: Code page identification can not use with all * system! So, some other encoding information * will be needed. * In japanese: SJIS,EUC,UNICODE,(JIS) * Note that JIS-code system don't use as * process code in most system because it uses * escape sequences(JIS is context depend encoding). */ /* assume process code is JAPANESE-EUC */ lb &= 0x7f; tb &= 0x7f; # endif /* exceptions */ switch (lb << 8 | tb) { case 0x2121: /* ZENKAKU space */ return 0; case 0x2122: /* KU-TEN (Japanese comma) */ case 0x2123: /* TOU-TEN (Japanese period) */ case 0x2124: /* ZENKAKU comma */ case 0x2125: /* ZENKAKU period */ return 1; case 0x213c: /* prolongedsound handled as KATAKANA */ return 13; } /* sieved by KU code */ switch (lb) { case 0x21: case 0x22: /* special symbols */ return 10; case 0x23: /* alpha-numeric */ return 11; case 0x24: /* hiragana */ return 12; case 0x25: /* katakana */ return 13; case 0x26: /* greek */ return 14; case 0x27: /* russian */ return 15; case 0x28: /* lines */ return 16; default: /* kanji */ return 17; } } case DBCS_KORU: /* ? */ case DBCS_KOR: { /* KS code classification */ unsigned char c1 = lead; unsigned char c2 = trail; /* * 20 : Hangul * 21 : Hanja * 22 : Symbols * 23 : Alpha-numeric/Roman Letter (Full width) * 24 : Hangul Letter(Alphabet) * 25 : Roman Numeral/Greek Letter * 26 : Box Drawings * 27 : Unit Symbols * 28 : Circled/Parenthesized Letter * 29 : Hirigana/Katakana * 30 : Cyrillic Letter */ if (c1 >= 0xB0 && c1 <= 0xC8) /* Hangul */ return 20; #if defined(WIN3264) || defined(WIN32UNIX) else if (c1 <= 0xA0 || c2 <= 0xA0) /* Extended Hangul Region : MS UHC(Unified Hangul Code) */ /* c1: 0x81-0xA0 with c2: 0x41-0x5A, 0x61-0x7A, 0x81-0xFE * c1: 0xA1-0xC6 with c2: 0x41-0x5A, 0x61-0x7A, 0x81-0xA0 */ return 20; #endif else if (c1 >= 0xCA && c1 <= 0xFD) /* Hanja */ return 21; else switch (c1) { case 0xA1: case 0xA2: /* Symbols */ return 22; case 0xA3: /* Alpha-numeric */ return 23; case 0xA4: /* Hangul Letter(Alphabet) */ return 24; case 0xA5: /* Roman Numeral/Greek Letter */ return 25; case 0xA6: /* Box Drawings */ return 26; case 0xA7: /* Unit Symbols */ return 27; case 0xA8: case 0xA9: if (c2 <= 0xAF) return 25; /* Roman Letter */ else if (c2 >= 0xF6) return 22; /* Symbols */ else /* Circled/Parenthesized Letter */ return 28; case 0xAA: case 0xAB: /* Hirigana/Katakana */ return 29; case 0xAC: /* Cyrillic Letter */ return 30; } } default: break; } return 3; } /* * mb_char2len() function pointer. * Return length in bytes of character "c". * Returns 1 for a single-byte character. */ int latin_char2len(c) int c UNUSED; { return 1; } static int dbcs_char2len(c) int c; { if (c >= 0x100) return 2; return 1; } /* * mb_char2bytes() function pointer. * Convert a character to its bytes. * Returns the length in bytes. */ int latin_char2bytes(c, buf) int c; char_u *buf; { buf[0] = c; return 1; } static int dbcs_char2bytes(c, buf) int c; char_u *buf; { if (c >= 0x100) { buf[0] = (unsigned)c >> 8; buf[1] = c; /* Never use a NUL byte, it causes lots of trouble. It's an invalid * character anyway. */ if (buf[1] == NUL) buf[1] = '\n'; return 2; } buf[0] = c; return 1; } /* * mb_ptr2len() function pointer. * Get byte length of character at "*p" but stop at a NUL. * For UTF-8 this includes following composing characters. * Returns 0 when *p is NUL. */ int latin_ptr2len(p) char_u *p; { return MB_BYTE2LEN(*p); } static int dbcs_ptr2len(p) char_u *p; { int len; /* Check if second byte is not missing. */ len = MB_BYTE2LEN(*p); if (len == 2 && p[1] == NUL) len = 1; return len; } /* * mb_ptr2len_len() function pointer. * Like mb_ptr2len(), but limit to read "size" bytes. * Returns 0 for an empty string. * Returns 1 for an illegal char or an incomplete byte sequence. */ int latin_ptr2len_len(p, size) char_u *p; int size; { if (size < 1 || *p == NUL) return 0; return 1; } static int dbcs_ptr2len_len(p, size) char_u *p; int size; { int len; if (size < 1 || *p == NUL) return 0; if (size == 1) return 1; /* Check that second byte is not missing. */ len = MB_BYTE2LEN(*p); if (len == 2 && p[1] == NUL) len = 1; return len; } struct interval { long first; long last; }; static int intable __ARGS((struct interval *table, size_t size, int c)); /* * Return TRUE if "c" is in "table[size / sizeof(struct interval)]". */ static int intable(table, size, c) struct interval *table; size_t size; int c; { int mid, bot, top; /* first quick check for Latin1 etc. characters */ if (c < table[0].first) return FALSE; /* binary search in table */ bot = 0; top = (int)(size / sizeof(struct interval) - 1); while (top >= bot) { mid = (bot + top) / 2; if (table[mid].last < c) bot = mid + 1; else if (table[mid].first > c) top = mid - 1; else return TRUE; } return FALSE; } /* * For UTF-8 character "c" return 2 for a double-width character, 1 for others. * Returns 4 or 6 for an unprintable character. * Is only correct for characters >= 0x80. * When p_ambw is "double", return 2 for a character with East Asian Width * class 'A'(mbiguous). */ int utf_char2cells(c) int c; { /* Sorted list of non-overlapping intervals of East Asian double width * characters, generated with ../runtime/tools/unicode.vim. */ static struct interval doublewidth[] = { {0x1100, 0x115f}, {0x11a3, 0x11a7}, {0x11fa, 0x11ff}, {0x2329, 0x232a}, {0x2e80, 0x2e99}, {0x2e9b, 0x2ef3}, {0x2f00, 0x2fd5}, {0x2ff0, 0x2ffb}, {0x3000, 0x3029}, {0x3030, 0x303e}, {0x3041, 0x3096}, {0x309b, 0x30ff}, {0x3105, 0x312d}, {0x3131, 0x318e}, {0x3190, 0x31b7}, {0x31c0, 0x31e3}, {0x31f0, 0x321e}, {0x3220, 0x3247}, {0x3250, 0x32fe}, {0x3300, 0x4dbf}, {0x4e00, 0xa48c}, {0xa490, 0xa4c6}, {0xa960, 0xa97c}, {0xac00, 0xd7a3}, {0xd7b0, 0xd7c6}, {0xd7cb, 0xd7fb}, {0xf900, 0xfaff}, {0xfe10, 0xfe19}, {0xfe30, 0xfe52}, {0xfe54, 0xfe66}, {0xfe68, 0xfe6b}, {0xff01, 0xff60}, {0xffe0, 0xffe6}, {0x1f200, 0x1f200}, {0x1f210, 0x1f231}, {0x1f240, 0x1f248}, {0x20000, 0x2fffd}, {0x30000, 0x3fffd} }; /* Sorted list of non-overlapping intervals of East Asian Ambiguous * characters, generated with ../runtime/tools/unicode.vim. */ static struct interval ambiguous[] = { {0x00a1, 0x00a1}, {0x00a4, 0x00a4}, {0x00a7, 0x00a8}, {0x00aa, 0x00aa}, {0x00ad, 0x00ae}, {0x00b0, 0x00b4}, {0x00b6, 0x00ba}, {0x00bc, 0x00bf}, {0x00c6, 0x00c6}, {0x00d0, 0x00d0}, {0x00d7, 0x00d8}, {0x00de, 0x00e1}, {0x00e6, 0x00e6}, {0x00e8, 0x00ea}, {0x00ec, 0x00ed}, {0x00f0, 0x00f0}, {0x00f2, 0x00f3}, {0x00f7, 0x00fa}, {0x00fc, 0x00fc}, {0x00fe, 0x00fe}, {0x0101, 0x0101}, {0x0111, 0x0111}, {0x0113, 0x0113}, {0x011b, 0x011b}, {0x0126, 0x0127}, {0x012b, 0x012b}, {0x0131, 0x0133}, {0x0138, 0x0138}, {0x013f, 0x0142}, {0x0144, 0x0144}, {0x0148, 0x014b}, {0x014d, 0x014d}, {0x0152, 0x0153}, {0x0166, 0x0167}, {0x016b, 0x016b}, {0x01ce, 0x01ce}, {0x01d0, 0x01d0}, {0x01d2, 0x01d2}, {0x01d4, 0x01d4}, {0x01d6, 0x01d6}, {0x01d8, 0x01d8}, {0x01da, 0x01da}, {0x01dc, 0x01dc}, {0x0251, 0x0251}, {0x0261, 0x0261}, {0x02c4, 0x02c4}, {0x02c7, 0x02c7}, {0x02c9, 0x02cb}, {0x02cd, 0x02cd}, {0x02d0, 0x02d0}, {0x02d8, 0x02db}, {0x02dd, 0x02dd}, {0x02df, 0x02df}, {0x0391, 0x03a1}, {0x03a3, 0x03a9}, {0x03b1, 0x03c1}, {0x03c3, 0x03c9}, {0x0401, 0x0401}, {0x0410, 0x044f}, {0x0451, 0x0451}, {0x2010, 0x2010}, {0x2013, 0x2016}, {0x2018, 0x2019}, {0x201c, 0x201d}, {0x2020, 0x2022}, {0x2024, 0x2027}, {0x2030, 0x2030}, {0x2032, 0x2033}, {0x2035, 0x2035}, {0x203b, 0x203b}, {0x203e, 0x203e}, {0x2074, 0x2074}, {0x207f, 0x207f}, {0x2081, 0x2084}, {0x20ac, 0x20ac}, {0x2103, 0x2103}, {0x2105, 0x2105}, {0x2109, 0x2109}, {0x2113, 0x2113}, {0x2116, 0x2116}, {0x2121, 0x2122}, {0x2126, 0x2126}, {0x212b, 0x212b}, {0x2153, 0x2154}, {0x215b, 0x215e}, {0x2160, 0x216b}, {0x2170, 0x2179}, {0x2189, 0x2189}, {0x2190, 0x2199}, {0x21b8, 0x21b9}, {0x21d2, 0x21d2}, {0x21d4, 0x21d4}, {0x21e7, 0x21e7}, {0x2200, 0x2200}, {0x2202, 0x2203}, {0x2207, 0x2208}, {0x220b, 0x220b}, {0x220f, 0x220f}, {0x2211, 0x2211}, {0x2215, 0x2215}, {0x221a, 0x221a}, {0x221d, 0x2220}, {0x2223, 0x2223}, {0x2225, 0x2225}, {0x2227, 0x222c}, {0x222e, 0x222e}, {0x2234, 0x2237}, {0x223c, 0x223d}, {0x2248, 0x2248}, {0x224c, 0x224c}, {0x2252, 0x2252}, {0x2260, 0x2261}, {0x2264, 0x2267}, {0x226a, 0x226b}, {0x226e, 0x226f}, {0x2282, 0x2283}, {0x2286, 0x2287}, {0x2295, 0x2295}, {0x2299, 0x2299}, {0x22a5, 0x22a5}, {0x22bf, 0x22bf}, {0x2312, 0x2312}, {0x2460, 0x24e9}, {0x24eb, 0x254b}, {0x2550, 0x2573}, {0x2580, 0x258f}, {0x2592, 0x2595}, {0x25a0, 0x25a1}, {0x25a3, 0x25a9}, {0x25b2, 0x25b3}, {0x25b6, 0x25b7}, {0x25bc, 0x25bd}, {0x25c0, 0x25c1}, {0x25c6, 0x25c8}, {0x25cb, 0x25cb}, {0x25ce, 0x25d1}, {0x25e2, 0x25e5}, {0x25ef, 0x25ef}, {0x2605, 0x2606}, {0x2609, 0x2609}, {0x260e, 0x260f}, {0x2614, 0x2615}, {0x261c, 0x261c}, {0x261e, 0x261e}, {0x2640, 0x2640}, {0x2642, 0x2642}, {0x2660, 0x2661}, {0x2663, 0x2665}, {0x2667, 0x266a}, {0x266c, 0x266d}, {0x266f, 0x266f}, {0x269e, 0x269f}, {0x26be, 0x26bf}, {0x26c4, 0x26cd}, {0x26cf, 0x26e1}, {0x26e3, 0x26e3}, {0x26e8, 0x26ff}, {0x273d, 0x273d}, {0x2757, 0x2757}, {0x2776, 0x277f}, {0x2b55, 0x2b59}, {0x3248, 0x324f}, {0xe000, 0xf8ff}, {0xfffd, 0xfffd}, {0x1f100, 0x1f10a}, {0x1f110, 0x1f12d}, {0x1f131, 0x1f131}, {0x1f13d, 0x1f13d}, {0x1f13f, 0x1f13f}, {0x1f142, 0x1f142}, {0x1f146, 0x1f146}, {0x1f14a, 0x1f14e}, {0x1f157, 0x1f157}, {0x1f15f, 0x1f15f}, {0x1f179, 0x1f179}, {0x1f17b, 0x1f17c}, {0x1f17f, 0x1f17f}, {0x1f18a, 0x1f18d}, {0x1f190, 0x1f190}, {0xf0000, 0xffffd}, {0x100000, 0x10fffd} }; if (c >= 0x100) { #ifdef USE_WCHAR_FUNCTIONS /* * Assume the library function wcwidth() works better than our own * stuff. It should return 1 for ambiguous width chars! */ int n = wcwidth(c); if (n < 0) return 6; /* unprintable, displays <xxxx> */ if (n > 1) return n; #else if (!utf_printable(c)) return 6; /* unprintable, displays <xxxx> */ if (intable(doublewidth, sizeof(doublewidth), c)) return 2; #endif } /* Characters below 0x100 are influenced by 'isprint' option */ else if (c >= 0x80 && !vim_isprintc(c)) return 4; /* unprintable, displays <xx> */ if (c >= 0x80 && *p_ambw == 'd' && intable(ambiguous, sizeof(ambiguous), c)) return 2; return 1; } /* * mb_ptr2cells() function pointer. * Return the number of display cells character at "*p" occupies. * This doesn't take care of unprintable characters, use ptr2cells() for that. */ int latin_ptr2cells(p) char_u *p UNUSED; { return 1; } int utf_ptr2cells(p) char_u *p; { int c; /* Need to convert to a wide character. */ if (*p >= 0x80) { c = utf_ptr2char(p); /* An illegal byte is displayed as <xx>. */ if (utf_ptr2len(p) == 1 || c == NUL) return 4; /* If the char is ASCII it must be an overlong sequence. */ if (c < 0x80) return char2cells(c); return utf_char2cells(c); } return 1; } int dbcs_ptr2cells(p) char_u *p; { /* Number of cells is equal to number of bytes, except for euc-jp when * the first byte is 0x8e. */ if (enc_dbcs == DBCS_JPNU && *p == 0x8e) return 1; return MB_BYTE2LEN(*p); } /* * mb_ptr2cells_len() function pointer. * Like mb_ptr2cells(), but limit string length to "size". * For an empty string or truncated character returns 1. */ int latin_ptr2cells_len(p, size) char_u *p UNUSED; int size UNUSED; { return 1; } static int utf_ptr2cells_len(p, size) char_u *p; int size; { int c; /* Need to convert to a wide character. */ if (size > 0 && *p >= 0x80) { if (utf_ptr2len_len(p, size) < utf8len_tab[*p]) return 1; /* truncated */ c = utf_ptr2char(p); /* An illegal byte is displayed as <xx>. */ if (utf_ptr2len(p) == 1 || c == NUL) return 4; /* If the char is ASCII it must be an overlong sequence. */ if (c < 0x80) return char2cells(c); return utf_char2cells(c); } return 1; } static int dbcs_ptr2cells_len(p, size) char_u *p; int size; { /* Number of cells is equal to number of bytes, except for euc-jp when * the first byte is 0x8e. */ if (size <= 1 || (enc_dbcs == DBCS_JPNU && *p == 0x8e)) return 1; return MB_BYTE2LEN(*p); } /* * mb_char2cells() function pointer. * Return the number of display cells character "c" occupies. * Only takes care of multi-byte chars, not "^C" and such. */ int latin_char2cells(c) int c UNUSED; { return 1; } static int dbcs_char2cells(c) int c; { /* Number of cells is equal to number of bytes, except for euc-jp when * the first byte is 0x8e. */ if (enc_dbcs == DBCS_JPNU && ((unsigned)c >> 8) == 0x8e) return 1; /* use the first byte */ return MB_BYTE2LEN((unsigned)c >> 8); } /* * Return the number of cells occupied by string "p". * Stop at a NUL character. When "len" >= 0 stop at character "p[len]". */ int mb_string2cells(p, len) char_u *p; int len; { int i; int clen = 0; for (i = 0; (len < 0 || i < len) && p[i] != NUL; i += (*mb_ptr2len)(p + i)) clen += (*mb_ptr2cells)(p + i); return clen; } /* * mb_off2cells() function pointer. * Return number of display cells for char at ScreenLines[off]. * We make sure that the offset used is less than "max_off". */ int latin_off2cells(off, max_off) unsigned off UNUSED; unsigned max_off UNUSED; { return 1; } int dbcs_off2cells(off, max_off) unsigned off; unsigned max_off; { /* never check beyond end of the line */ if (off >= max_off) return 1; /* Number of cells is equal to number of bytes, except for euc-jp when * the first byte is 0x8e. */ if (enc_dbcs == DBCS_JPNU && ScreenLines[off] == 0x8e) return 1; return MB_BYTE2LEN(ScreenLines[off]); } int utf_off2cells(off, max_off) unsigned off; unsigned max_off; { return (off + 1 < max_off && ScreenLines[off + 1] == 0) ? 2 : 1; } /* * mb_ptr2char() function pointer. * Convert a byte sequence into a character. */ int latin_ptr2char(p) char_u *p; { return *p; } static int dbcs_ptr2char(p) char_u *p; { if (MB_BYTE2LEN(*p) > 1 && p[1] != NUL) return (p[0] << 8) + p[1]; return *p; } /* * Convert a UTF-8 byte sequence to a wide character. * If the sequence is illegal or truncated by a NUL the first byte is * returned. * Does not include composing characters, of course. */ int utf_ptr2char(p) char_u *p; { int len; if (p[0] < 0x80) /* be quick for ASCII */ return p[0]; len = utf8len_tab_zero[p[0]]; if (len > 1 && (p[1] & 0xc0) == 0x80) { if (len == 2) return ((p[0] & 0x1f) << 6) + (p[1] & 0x3f); if ((p[2] & 0xc0) == 0x80) { if (len == 3) return ((p[0] & 0x0f) << 12) + ((p[1] & 0x3f) << 6) + (p[2] & 0x3f); if ((p[3] & 0xc0) == 0x80) { if (len == 4) return ((p[0] & 0x07) << 18) + ((p[1] & 0x3f) << 12) + ((p[2] & 0x3f) << 6) + (p[3] & 0x3f); if ((p[4] & 0xc0) == 0x80) { if (len == 5) return ((p[0] & 0x03) << 24) + ((p[1] & 0x3f) << 18) + ((p[2] & 0x3f) << 12) + ((p[3] & 0x3f) << 6) + (p[4] & 0x3f); if ((p[5] & 0xc0) == 0x80 && len == 6) return ((p[0] & 0x01) << 30) + ((p[1] & 0x3f) << 24) + ((p[2] & 0x3f) << 18) + ((p[3] & 0x3f) << 12) + ((p[4] & 0x3f) << 6) + (p[5] & 0x3f); } } } } /* Illegal value, just return the first byte */ return p[0]; } /* * Convert a UTF-8 byte sequence to a wide character. * String is assumed to be terminated by NUL or after "n" bytes, whichever * comes first. * The function is safe in the sense that it never accesses memory beyond the * first "n" bytes of "s". * * On success, returns decoded codepoint, advances "s" to the beginning of * next character and decreases "n" accordingly. * * If end of string was reached, returns 0 and, if "n" > 0, advances "s" past * NUL byte. * * If byte sequence is illegal or incomplete, returns -1 and does not advance * "s". */ static int utf_safe_read_char_adv(s, n) char_u **s; size_t *n; { int c, k; if (*n == 0) /* end of buffer */ return 0; k = utf8len_tab_zero[**s]; if (k == 1) { /* ASCII character or NUL */ (*n)--; return *(*s)++; } if ((size_t)k <= *n) { /* We have a multibyte sequence and it isn't truncated by buffer * limits so utf_ptr2char() is safe to use. Or the first byte is * illegal (k=0), and it's also safe to use utf_ptr2char(). */ c = utf_ptr2char(*s); /* On failure, utf_ptr2char() returns the first byte, so here we * check equality with the first byte. The only non-ASCII character * which equals the first byte of its own UTF-8 representation is * U+00C3 (UTF-8: 0xC3 0x83), so need to check that special case too. * It's safe even if n=1, else we would have k=2 > n. */ if (c != (int)(**s) || (c == 0xC3 && (*s)[1] == 0x83)) { /* byte sequence was successfully decoded */ *s += k; *n -= k; return c; } } /* byte sequence is incomplete or illegal */ return -1; } /* * Get character at **pp and advance *pp to the next character. * Note: composing characters are skipped! */ int mb_ptr2char_adv(pp) char_u **pp; { int c; c = (*mb_ptr2char)(*pp); *pp += (*mb_ptr2len)(*pp); return c; } /* * Get character at **pp and advance *pp to the next character. * Note: composing characters are returned as separate characters. */ int mb_cptr2char_adv(pp) char_u **pp; { int c; c = (*mb_ptr2char)(*pp); if (enc_utf8) *pp += utf_ptr2len(*pp); else *pp += (*mb_ptr2len)(*pp); return c; } #if defined(FEAT_ARABIC) || defined(PROTO) /* * Check whether we are dealing with Arabic combining characters. * Note: these are NOT really composing characters! */ int arabic_combine(one, two) int one; /* first character */ int two; /* character just after "one" */ { if (one == a_LAM) return arabic_maycombine(two); return FALSE; } /* * Check whether we are dealing with a character that could be regarded as an * Arabic combining character, need to check the character before this. */ int arabic_maycombine(two) int two; { if (p_arshape && !p_tbidi) return (two == a_ALEF_MADDA || two == a_ALEF_HAMZA_ABOVE || two == a_ALEF_HAMZA_BELOW || two == a_ALEF); return FALSE; } /* * Check if the character pointed to by "p2" is a composing character when it * comes after "p1". For Arabic sometimes "ab" is replaced with "c", which * behaves like a composing character. */ int utf_composinglike(p1, p2) char_u *p1; char_u *p2; { int c2; c2 = utf_ptr2char(p2); if (utf_iscomposing(c2)) return TRUE; if (!arabic_maycombine(c2)) return FALSE; return arabic_combine(utf_ptr2char(p1), c2); } #endif /* * Convert a UTF-8 byte string to a wide character. Also get up to MAX_MCO * composing characters. */ int utfc_ptr2char(p, pcc) char_u *p; int *pcc; /* return: composing chars, last one is 0 */ { int len; int c; int cc; int i = 0; c = utf_ptr2char(p); len = utf_ptr2len(p); /* Only accept a composing char when the first char isn't illegal. */ if ((len > 1 || *p < 0x80) && p[len] >= 0x80 && UTF_COMPOSINGLIKE(p, p + len)) { cc = utf_ptr2char(p + len); for (;;) { pcc[i++] = cc; if (i == MAX_MCO) break; len += utf_ptr2len(p + len); if (p[len] < 0x80 || !utf_iscomposing(cc = utf_ptr2char(p + len))) break; } } if (i < MAX_MCO) /* last composing char must be 0 */ pcc[i] = 0; return c; } /* * Convert a UTF-8 byte string to a wide character. Also get up to MAX_MCO * composing characters. Use no more than p[maxlen]. */ int utfc_ptr2char_len(p, pcc, maxlen) char_u *p; int *pcc; /* return: composing chars, last one is 0 */ int maxlen; { int len; int c; int cc; int i = 0; c = utf_ptr2char(p); len = utf_ptr2len_len(p, maxlen); /* Only accept a composing char when the first char isn't illegal. */ if ((len > 1 || *p < 0x80) && len < maxlen && p[len] >= 0x80 && UTF_COMPOSINGLIKE(p, p + len)) { cc = utf_ptr2char(p + len); for (;;) { pcc[i++] = cc; if (i == MAX_MCO) break; len += utf_ptr2len_len(p + len, maxlen - len); if (len >= maxlen || p[len] < 0x80 || !utf_iscomposing(cc = utf_ptr2char(p + len))) break; } } if (i < MAX_MCO) /* last composing char must be 0 */ pcc[i] = 0; return c; } /* * Convert the character at screen position "off" to a sequence of bytes. * Includes the composing characters. * "buf" must at least have the length MB_MAXBYTES + 1. * Only to be used when ScreenLinesUC[off] != 0. * Returns the produced number of bytes. */ int utfc_char2bytes(off, buf) int off; char_u *buf; { int len; int i; len = utf_char2bytes(ScreenLinesUC[off], buf); for (i = 0; i < Screen_mco; ++i) { if (ScreenLinesC[i][off] == 0) break; len += utf_char2bytes(ScreenLinesC[i][off], buf + len); } return len; } /* * Get the length of a UTF-8 byte sequence, not including any following * composing characters. * Returns 0 for "". * Returns 1 for an illegal byte sequence. */ int utf_ptr2len(p) char_u *p; { int len; int i; if (*p == NUL) return 0; len = utf8len_tab[*p]; for (i = 1; i < len; ++i) if ((p[i] & 0xc0) != 0x80) return 1; return len; } /* * Return length of UTF-8 character, obtained from the first byte. * "b" must be between 0 and 255! * Returns 1 for an invalid first byte value. */ int utf_byte2len(b) int b; { return utf8len_tab[b]; } /* * Get the length of UTF-8 byte sequence "p[size]". Does not include any * following composing characters. * Returns 1 for "". * Returns 1 for an illegal byte sequence (also in incomplete byte seq.). * Returns number > "size" for an incomplete byte sequence. * Never returns zero. */ int utf_ptr2len_len(p, size) char_u *p; int size; { int len; int i; int m; len = utf8len_tab[*p]; if (len == 1) return 1; /* NUL, ascii or illegal lead byte */ if (len > size) m = size; /* incomplete byte sequence. */ else m = len; for (i = 1; i < m; ++i) if ((p[i] & 0xc0) != 0x80) return 1; return len; } /* * Return the number of bytes the UTF-8 encoding of the character at "p" takes. * This includes following composing characters. */ int utfc_ptr2len(p) char_u *p; { int len; int b0 = *p; #ifdef FEAT_ARABIC int prevlen; #endif if (b0 == NUL) return 0; if (b0 < 0x80 && p[1] < 0x80) /* be quick for ASCII */ return 1; /* Skip over first UTF-8 char, stopping at a NUL byte. */ len = utf_ptr2len(p); /* Check for illegal byte. */ if (len == 1 && b0 >= 0x80) return 1; /* * Check for composing characters. We can handle only the first six, but * skip all of them (otherwise the cursor would get stuck). */ #ifdef FEAT_ARABIC prevlen = 0; #endif for (;;) { if (p[len] < 0x80 || !UTF_COMPOSINGLIKE(p + prevlen, p + len)) return len; /* Skip over composing char */ #ifdef FEAT_ARABIC prevlen = len; #endif len += utf_ptr2len(p + len); } } /* * Return the number of bytes the UTF-8 encoding of the character at "p[size]" * takes. This includes following composing characters. * Returns 0 for an empty string. * Returns 1 for an illegal char or an incomplete byte sequence. */ int utfc_ptr2len_len(p, size) char_u *p; int size; { int len; #ifdef FEAT_ARABIC int prevlen; #endif if (size < 1 || *p == NUL) return 0; if (p[0] < 0x80 && (size == 1 || p[1] < 0x80)) /* be quick for ASCII */ return 1; /* Skip over first UTF-8 char, stopping at a NUL byte. */ len = utf_ptr2len_len(p, size); /* Check for illegal byte and incomplete byte sequence. */ if ((len == 1 && p[0] >= 0x80) || len > size) return 1; /* * Check for composing characters. We can handle only the first six, but * skip all of them (otherwise the cursor would get stuck). */ #ifdef FEAT_ARABIC prevlen = 0; #endif while (len < size) { int len_next_char; if (p[len] < 0x80) break; /* * Next character length should not go beyond size to ensure that * UTF_COMPOSINGLIKE(...) does not read beyond size. */ len_next_char = utf_ptr2len_len(p + len, size - len); if (len_next_char > size - len) break; if (!UTF_COMPOSINGLIKE(p + prevlen, p + len)) break; /* Skip over composing char */ #ifdef FEAT_ARABIC prevlen = len; #endif len += len_next_char; } return len; } /* * Return the number of bytes the UTF-8 encoding of character "c" takes. * This does not include composing characters. */ int utf_char2len(c) int c; { if (c < 0x80) return 1; if (c < 0x800) return 2; if (c < 0x10000) return 3; if (c < 0x200000) return 4; if (c < 0x4000000) return 5; return 6; } /* * Convert Unicode character "c" to UTF-8 string in "buf[]". * Returns the number of bytes. * This does not include composing characters. */ int utf_char2bytes(c, buf) int c; char_u *buf; { if (c < 0x80) /* 7 bits */ { buf[0] = c; return 1; } if (c < 0x800) /* 11 bits */ { buf[0] = 0xc0 + ((unsigned)c >> 6); buf[1] = 0x80 + (c & 0x3f); return 2; } if (c < 0x10000) /* 16 bits */ { buf[0] = 0xe0 + ((unsigned)c >> 12); buf[1] = 0x80 + (((unsigned)c >> 6) & 0x3f); buf[2] = 0x80 + (c & 0x3f); return 3; } if (c < 0x200000) /* 21 bits */ { buf[0] = 0xf0 + ((unsigned)c >> 18); buf[1] = 0x80 + (((unsigned)c >> 12) & 0x3f); buf[2] = 0x80 + (((unsigned)c >> 6) & 0x3f); buf[3] = 0x80 + (c & 0x3f); return 4; } if (c < 0x4000000) /* 26 bits */ { buf[0] = 0xf8 + ((unsigned)c >> 24); buf[1] = 0x80 + (((unsigned)c >> 18) & 0x3f); buf[2] = 0x80 + (((unsigned)c >> 12) & 0x3f); buf[3] = 0x80 + (((unsigned)c >> 6) & 0x3f); buf[4] = 0x80 + (c & 0x3f); return 5; } /* 31 bits */ buf[0] = 0xfc + ((unsigned)c >> 30); buf[1] = 0x80 + (((unsigned)c >> 24) & 0x3f); buf[2] = 0x80 + (((unsigned)c >> 18) & 0x3f); buf[3] = 0x80 + (((unsigned)c >> 12) & 0x3f); buf[4] = 0x80 + (((unsigned)c >> 6) & 0x3f); buf[5] = 0x80 + (c & 0x3f); return 6; } /* * Return TRUE if "c" is a composing UTF-8 character. This means it will be * drawn on top of the preceding character. * Based on code from Markus Kuhn. */ int utf_iscomposing(c) int c; { /* Sorted list of non-overlapping intervals. * Generated by ../runtime/tools/unicode.vim. */ static struct interval combining[] = { {0x0300, 0x036f}, {0x0483, 0x0489}, {0x0591, 0x05bd}, {0x05bf, 0x05bf}, {0x05c1, 0x05c2}, {0x05c4, 0x05c5}, {0x05c7, 0x05c7}, {0x0610, 0x061a}, {0x064b, 0x065e}, {0x0670, 0x0670}, {0x06d6, 0x06dc}, {0x06de, 0x06e4}, {0x06e7, 0x06e8}, {0x06ea, 0x06ed}, {0x0711, 0x0711}, {0x0730, 0x074a}, {0x07a6, 0x07b0}, {0x07eb, 0x07f3}, {0x0816, 0x0819}, {0x081b, 0x0823}, {0x0825, 0x0827}, {0x0829, 0x082d}, {0x0900, 0x0903}, {0x093c, 0x093c}, {0x093e, 0x094e}, {0x0951, 0x0955}, {0x0962, 0x0963}, {0x0981, 0x0983}, {0x09bc, 0x09bc}, {0x09be, 0x09c4}, {0x09c7, 0x09c8}, {0x09cb, 0x09cd}, {0x09d7, 0x09d7}, {0x09e2, 0x09e3}, {0x0a01, 0x0a03}, {0x0a3c, 0x0a3c}, {0x0a3e, 0x0a42}, {0x0a47, 0x0a48}, {0x0a4b, 0x0a4d}, {0x0a51, 0x0a51}, {0x0a70, 0x0a71}, {0x0a75, 0x0a75}, {0x0a81, 0x0a83}, {0x0abc, 0x0abc}, {0x0abe, 0x0ac5}, {0x0ac7, 0x0ac9}, {0x0acb, 0x0acd}, {0x0ae2, 0x0ae3}, {0x0b01, 0x0b03}, {0x0b3c, 0x0b3c}, {0x0b3e, 0x0b44}, {0x0b47, 0x0b48}, {0x0b4b, 0x0b4d}, {0x0b56, 0x0b57}, {0x0b62, 0x0b63}, {0x0b82, 0x0b82}, {0x0bbe, 0x0bc2}, {0x0bc6, 0x0bc8}, {0x0bca, 0x0bcd}, {0x0bd7, 0x0bd7}, {0x0c01, 0x0c03}, {0x0c3e, 0x0c44}, {0x0c46, 0x0c48}, {0x0c4a, 0x0c4d}, {0x0c55, 0x0c56}, {0x0c62, 0x0c63}, {0x0c82, 0x0c83}, {0x0cbc, 0x0cbc}, {0x0cbe, 0x0cc4}, {0x0cc6, 0x0cc8}, {0x0cca, 0x0ccd}, {0x0cd5, 0x0cd6}, {0x0ce2, 0x0ce3}, {0x0d02, 0x0d03}, {0x0d3e, 0x0d44}, {0x0d46, 0x0d48}, {0x0d4a, 0x0d4d}, {0x0d57, 0x0d57}, {0x0d62, 0x0d63}, {0x0d82, 0x0d83}, {0x0dca, 0x0dca}, {0x0dcf, 0x0dd4}, {0x0dd6, 0x0dd6}, {0x0dd8, 0x0ddf}, {0x0df2, 0x0df3}, {0x0e31, 0x0e31}, {0x0e34, 0x0e3a}, {0x0e47, 0x0e4e}, {0x0eb1, 0x0eb1}, {0x0eb4, 0x0eb9}, {0x0ebb, 0x0ebc}, {0x0ec8, 0x0ecd}, {0x0f18, 0x0f19}, {0x0f35, 0x0f35}, {0x0f37, 0x0f37}, {0x0f39, 0x0f39}, {0x0f3e, 0x0f3f}, {0x0f71, 0x0f84}, {0x0f86, 0x0f87}, {0x0f90, 0x0f97}, {0x0f99, 0x0fbc}, {0x0fc6, 0x0fc6}, {0x102b, 0x103e}, {0x1056, 0x1059}, {0x105e, 0x1060}, {0x1062, 0x1064}, {0x1067, 0x106d}, {0x1071, 0x1074}, {0x1082, 0x108d}, {0x108f, 0x108f}, {0x109a, 0x109d}, {0x135f, 0x135f}, {0x1712, 0x1714}, {0x1732, 0x1734}, {0x1752, 0x1753}, {0x1772, 0x1773}, {0x17b6, 0x17d3}, {0x17dd, 0x17dd}, {0x180b, 0x180d}, {0x18a9, 0x18a9}, {0x1920, 0x192b}, {0x1930, 0x193b}, {0x19b0, 0x19c0}, {0x19c8, 0x19c9}, {0x1a17, 0x1a1b}, {0x1a55, 0x1a5e}, {0x1a60, 0x1a7c}, {0x1a7f, 0x1a7f}, {0x1b00, 0x1b04}, {0x1b34, 0x1b44}, {0x1b6b, 0x1b73}, {0x1b80, 0x1b82}, {0x1ba1, 0x1baa}, {0x1c24, 0x1c37}, {0x1cd0, 0x1cd2}, {0x1cd4, 0x1ce8}, {0x1ced, 0x1ced}, {0x1cf2, 0x1cf2}, {0x1dc0, 0x1de6}, {0x1dfd, 0x1dff}, {0x20d0, 0x20f0}, {0x2cef, 0x2cf1}, {0x2de0, 0x2dff}, {0x302a, 0x302f}, {0x3099, 0x309a}, {0xa66f, 0xa672}, {0xa67c, 0xa67d}, {0xa6f0, 0xa6f1}, {0xa802, 0xa802}, {0xa806, 0xa806}, {0xa80b, 0xa80b}, {0xa823, 0xa827}, {0xa880, 0xa881}, {0xa8b4, 0xa8c4}, {0xa8e0, 0xa8f1}, {0xa926, 0xa92d}, {0xa947, 0xa953}, {0xa980, 0xa983}, {0xa9b3, 0xa9c0}, {0xaa29, 0xaa36}, {0xaa43, 0xaa43}, {0xaa4c, 0xaa4d}, {0xaa7b, 0xaa7b}, {0xaab0, 0xaab0}, {0xaab2, 0xaab4}, {0xaab7, 0xaab8}, {0xaabe, 0xaabf}, {0xaac1, 0xaac1}, {0xabe3, 0xabea}, {0xabec, 0xabed}, {0xfb1e, 0xfb1e}, {0xfe00, 0xfe0f}, {0xfe20, 0xfe26}, {0x101fd, 0x101fd}, {0x10a01, 0x10a03}, {0x10a05, 0x10a06}, {0x10a0c, 0x10a0f}, {0x10a38, 0x10a3a}, {0x10a3f, 0x10a3f}, {0x11080, 0x11082}, {0x110b0, 0x110ba}, {0x1d165, 0x1d169}, {0x1d16d, 0x1d172}, {0x1d17b, 0x1d182}, {0x1d185, 0x1d18b}, {0x1d1aa, 0x1d1ad}, {0x1d242, 0x1d244}, {0xe0100, 0xe01ef} }; return intable(combining, sizeof(combining), c); } /* * Return TRUE for characters that can be displayed in a normal way. * Only for characters of 0x100 and above! */ int utf_printable(c) int c; { #ifdef USE_WCHAR_FUNCTIONS /* * Assume the iswprint() library function works better than our own stuff. */ return iswprint(c); #else /* Sorted list of non-overlapping intervals. * 0xd800-0xdfff is reserved for UTF-16, actually illegal. */ static struct interval nonprint[] = { {0x070f, 0x070f}, {0x180b, 0x180e}, {0x200b, 0x200f}, {0x202a, 0x202e}, {0x206a, 0x206f}, {0xd800, 0xdfff}, {0xfeff, 0xfeff}, {0xfff9, 0xfffb}, {0xfffe, 0xffff} }; return !intable(nonprint, sizeof(nonprint), c); #endif } /* * Get class of a Unicode character. * 0: white space * 1: punctuation * 2 or bigger: some class of word character. */ int utf_class(c) int c; { /* sorted list of non-overlapping intervals */ static struct clinterval { unsigned short first; unsigned short last; unsigned short class; } classes[] = { {0x037e, 0x037e, 1}, /* Greek question mark */ {0x0387, 0x0387, 1}, /* Greek ano teleia */ {0x055a, 0x055f, 1}, /* Armenian punctuation */ {0x0589, 0x0589, 1}, /* Armenian full stop */ {0x05be, 0x05be, 1}, {0x05c0, 0x05c0, 1}, {0x05c3, 0x05c3, 1}, {0x05f3, 0x05f4, 1}, {0x060c, 0x060c, 1}, {0x061b, 0x061b, 1}, {0x061f, 0x061f, 1}, {0x066a, 0x066d, 1}, {0x06d4, 0x06d4, 1}, {0x0700, 0x070d, 1}, /* Syriac punctuation */ {0x0964, 0x0965, 1}, {0x0970, 0x0970, 1}, {0x0df4, 0x0df4, 1}, {0x0e4f, 0x0e4f, 1}, {0x0e5a, 0x0e5b, 1}, {0x0f04, 0x0f12, 1}, {0x0f3a, 0x0f3d, 1}, {0x0f85, 0x0f85, 1}, {0x104a, 0x104f, 1}, /* Myanmar punctuation */ {0x10fb, 0x10fb, 1}, /* Georgian punctuation */ {0x1361, 0x1368, 1}, /* Ethiopic punctuation */ {0x166d, 0x166e, 1}, /* Canadian Syl. punctuation */ {0x1680, 0x1680, 0}, {0x169b, 0x169c, 1}, {0x16eb, 0x16ed, 1}, {0x1735, 0x1736, 1}, {0x17d4, 0x17dc, 1}, /* Khmer punctuation */ {0x1800, 0x180a, 1}, /* Mongolian punctuation */ {0x2000, 0x200b, 0}, /* spaces */ {0x200c, 0x2027, 1}, /* punctuation and symbols */ {0x2028, 0x2029, 0}, {0x202a, 0x202e, 1}, /* punctuation and symbols */ {0x202f, 0x202f, 0}, {0x2030, 0x205e, 1}, /* punctuation and symbols */ {0x205f, 0x205f, 0}, {0x2060, 0x27ff, 1}, /* punctuation and symbols */ {0x2070, 0x207f, 0x2070}, /* superscript */ {0x2080, 0x2094, 0x2080}, /* subscript */ {0x20a0, 0x27ff, 1}, /* all kinds of symbols */ {0x2800, 0x28ff, 0x2800}, /* braille */ {0x2900, 0x2998, 1}, /* arrows, brackets, etc. */ {0x29d8, 0x29db, 1}, {0x29fc, 0x29fd, 1}, {0x3000, 0x3000, 0}, /* ideographic space */ {0x3001, 0x3020, 1}, /* ideographic punctuation */ {0x3030, 0x3030, 1}, {0x303d, 0x303d, 1}, {0x3040, 0x309f, 0x3040}, /* Hiragana */ {0x30a0, 0x30ff, 0x30a0}, /* Katakana */ {0x3300, 0x9fff, 0x4e00}, /* CJK Ideographs */ {0xac00, 0xd7a3, 0xac00}, /* Hangul Syllables */ {0xf900, 0xfaff, 0x4e00}, /* CJK Ideographs */ {0xfd3e, 0xfd3f, 1}, {0xfe30, 0xfe6b, 1}, /* punctuation forms */ {0xff00, 0xff0f, 1}, /* half/fullwidth ASCII */ {0xff1a, 0xff20, 1}, /* half/fullwidth ASCII */ {0xff3b, 0xff40, 1}, /* half/fullwidth ASCII */ {0xff5b, 0xff65, 1}, /* half/fullwidth ASCII */ }; int bot = 0; int top = sizeof(classes) / sizeof(struct clinterval) - 1; int mid; /* First quick check for Latin1 characters, use 'iskeyword'. */ if (c < 0x100) { if (c == ' ' || c == '\t' || c == NUL || c == 0xa0) return 0; /* blank */ if (vim_iswordc(c)) return 2; /* word character */ return 1; /* punctuation */ } /* binary search in table */ while (top >= bot) { mid = (bot + top) / 2; if (classes[mid].last < c) bot = mid + 1; else if (classes[mid].first > c) top = mid - 1; else return (int)classes[mid].class; } /* most other characters are "word" characters */ return 2; } /* * Code for Unicode case-dependent operations. Based on notes in * http://www.unicode.org/Public/UNIDATA/CaseFolding.txt * This code uses simple case folding, not full case folding. * Last updated for Unicode 5.2. */ /* * The following tables are built by ../runtime/tools/unicode.vim. * They must be in numeric order, because we use binary search. * An entry such as {0x41,0x5a,1,32} means that Unicode characters in the * range from 0x41 to 0x5a inclusive, stepping by 1, are changed to * folded/upper/lower by adding 32. */ typedef struct { int rangeStart; int rangeEnd; int step; int offset; } convertStruct; static convertStruct foldCase[] = { {0x41,0x5a,1,32}, {0xb5,0xb5,-1,775}, {0xc0,0xd6,1,32}, {0xd8,0xde,1,32}, {0x100,0x12e,2,1}, {0x132,0x136,2,1}, {0x139,0x147,2,1}, {0x14a,0x176,2,1}, {0x178,0x178,-1,-121}, {0x179,0x17d,2,1}, {0x17f,0x17f,-1,-268}, {0x181,0x181,-1,210}, {0x182,0x184,2,1}, {0x186,0x186,-1,206}, {0x187,0x187,-1,1}, {0x189,0x18a,1,205}, {0x18b,0x18b,-1,1}, {0x18e,0x18e,-1,79}, {0x18f,0x18f,-1,202}, {0x190,0x190,-1,203}, {0x191,0x191,-1,1}, {0x193,0x193,-1,205}, {0x194,0x194,-1,207}, {0x196,0x196,-1,211}, {0x197,0x197,-1,209}, {0x198,0x198,-1,1}, {0x19c,0x19c,-1,211}, {0x19d,0x19d,-1,213}, {0x19f,0x19f,-1,214}, {0x1a0,0x1a4,2,1}, {0x1a6,0x1a6,-1,218}, {0x1a7,0x1a7,-1,1}, {0x1a9,0x1a9,-1,218}, {0x1ac,0x1ac,-1,1}, {0x1ae,0x1ae,-1,218}, {0x1af,0x1af,-1,1}, {0x1b1,0x1b2,1,217}, {0x1b3,0x1b5,2,1}, {0x1b7,0x1b7,-1,219}, {0x1b8,0x1bc,4,1}, {0x1c4,0x1c4,-1,2}, {0x1c5,0x1c5,-1,1}, {0x1c7,0x1c7,-1,2}, {0x1c8,0x1c8,-1,1}, {0x1ca,0x1ca,-1,2}, {0x1cb,0x1db,2,1}, {0x1de,0x1ee,2,1}, {0x1f1,0x1f1,-1,2}, {0x1f2,0x1f4,2,1}, {0x1f6,0x1f6,-1,-97}, {0x1f7,0x1f7,-1,-56}, {0x1f8,0x21e,2,1}, {0x220,0x220,-1,-130}, {0x222,0x232,2,1}, {0x23a,0x23a,-1,10795}, {0x23b,0x23b,-1,1}, {0x23d,0x23d,-1,-163}, {0x23e,0x23e,-1,10792}, {0x241,0x241,-1,1}, {0x243,0x243,-1,-195}, {0x244,0x244,-1,69}, {0x245,0x245,-1,71}, {0x246,0x24e,2,1}, {0x345,0x345,-1,116}, {0x370,0x372,2,1}, {0x376,0x376,-1,1}, {0x386,0x386,-1,38}, {0x388,0x38a,1,37}, {0x38c,0x38c,-1,64}, {0x38e,0x38f,1,63}, {0x391,0x3a1,1,32}, {0x3a3,0x3ab,1,32}, {0x3c2,0x3c2,-1,1}, {0x3cf,0x3cf,-1,8}, {0x3d0,0x3d0,-1,-30}, {0x3d1,0x3d1,-1,-25}, {0x3d5,0x3d5,-1,-15}, {0x3d6,0x3d6,-1,-22}, {0x3d8,0x3ee,2,1}, {0x3f0,0x3f0,-1,-54}, {0x3f1,0x3f1,-1,-48}, {0x3f4,0x3f4,-1,-60}, {0x3f5,0x3f5,-1,-64}, {0x3f7,0x3f7,-1,1}, {0x3f9,0x3f9,-1,-7}, {0x3fa,0x3fa,-1,1}, {0x3fd,0x3ff,1,-130}, {0x400,0x40f,1,80}, {0x410,0x42f,1,32}, {0x460,0x480,2,1}, {0x48a,0x4be,2,1}, {0x4c0,0x4c0,-1,15}, {0x4c1,0x4cd,2,1}, {0x4d0,0x524,2,1}, {0x531,0x556,1,48}, {0x10a0,0x10c5,1,7264}, {0x1e00,0x1e94,2,1}, {0x1e9b,0x1e9b,-1,-58}, {0x1e9e,0x1e9e,-1,-7615}, {0x1ea0,0x1efe,2,1}, {0x1f08,0x1f0f,1,-8}, {0x1f18,0x1f1d,1,-8}, {0x1f28,0x1f2f,1,-8}, {0x1f38,0x1f3f,1,-8}, {0x1f48,0x1f4d,1,-8}, {0x1f59,0x1f5f,2,-8}, {0x1f68,0x1f6f,1,-8}, {0x1f88,0x1f8f,1,-8}, {0x1f98,0x1f9f,1,-8}, {0x1fa8,0x1faf,1,-8}, {0x1fb8,0x1fb9,1,-8}, {0x1fba,0x1fbb,1,-74}, {0x1fbc,0x1fbc,-1,-9}, {0x1fbe,0x1fbe,-1,-7173}, {0x1fc8,0x1fcb,1,-86}, {0x1fcc,0x1fcc,-1,-9}, {0x1fd8,0x1fd9,1,-8}, {0x1fda,0x1fdb,1,-100}, {0x1fe8,0x1fe9,1,-8}, {0x1fea,0x1feb,1,-112}, {0x1fec,0x1fec,-1,-7}, {0x1ff8,0x1ff9,1,-128}, {0x1ffa,0x1ffb,1,-126}, {0x1ffc,0x1ffc,-1,-9}, {0x2126,0x2126,-1,-7517}, {0x212a,0x212a,-1,-8383}, {0x212b,0x212b,-1,-8262}, {0x2132,0x2132,-1,28}, {0x2160,0x216f,1,16}, {0x2183,0x2183,-1,1}, {0x24b6,0x24cf,1,26}, {0x2c00,0x2c2e,1,48}, {0x2c60,0x2c60,-1,1}, {0x2c62,0x2c62,-1,-10743}, {0x2c63,0x2c63,-1,-3814}, {0x2c64,0x2c64,-1,-10727}, {0x2c67,0x2c6b,2,1}, {0x2c6d,0x2c6d,-1,-10780}, {0x2c6e,0x2c6e,-1,-10749}, {0x2c6f,0x2c6f,-1,-10783}, {0x2c70,0x2c70,-1,-10782}, {0x2c72,0x2c75,3,1}, {0x2c7e,0x2c7f,1,-10815}, {0x2c80,0x2ce2,2,1}, {0x2ceb,0x2ced,2,1}, {0xa640,0xa65e,2,1}, {0xa662,0xa66c,2,1}, {0xa680,0xa696,2,1}, {0xa722,0xa72e,2,1}, {0xa732,0xa76e,2,1}, {0xa779,0xa77b,2,1}, {0xa77d,0xa77d,-1,-35332}, {0xa77e,0xa786,2,1}, {0xa78b,0xa78b,-1,1}, {0xff21,0xff3a,1,32}, {0x10400,0x10427,1,40} }; static int utf_convert __ARGS((int a, convertStruct table[], int tableSize)); static int utf_strnicmp __ARGS((char_u *s1, char_u *s2, size_t n1, size_t n2)); /* * Generic conversion function for case operations. * Return the converted equivalent of "a", which is a UCS-4 character. Use * the given conversion "table". Uses binary search on "table". */ static int utf_convert(a, table, tableSize) int a; convertStruct table[]; int tableSize; { int start, mid, end; /* indices into table */ int entries = tableSize / sizeof(convertStruct); start = 0; end = entries; while (start < end) { /* need to search further */ mid = (end + start) / 2; if (table[mid].rangeEnd < a) start = mid + 1; else end = mid; } if (start < entries && table[start].rangeStart <= a && a <= table[start].rangeEnd && (a - table[start].rangeStart) % table[start].step == 0) return (a + table[start].offset); else return a; } /* * Return the folded-case equivalent of "a", which is a UCS-4 character. Uses * simple case folding. */ int utf_fold(a) int a; { return utf_convert(a, foldCase, (int)sizeof(foldCase)); } static convertStruct toLower[] = { {0x41,0x5a,1,32}, {0xc0,0xd6,1,32}, {0xd8,0xde,1,32}, {0x100,0x12e,2,1}, {0x130,0x130,-1,-199}, {0x132,0x136,2,1}, {0x139,0x147,2,1}, {0x14a,0x176,2,1}, {0x178,0x178,-1,-121}, {0x179,0x17d,2,1}, {0x181,0x181,-1,210}, {0x182,0x184,2,1}, {0x186,0x186,-1,206}, {0x187,0x187,-1,1}, {0x189,0x18a,1,205}, {0x18b,0x18b,-1,1}, {0x18e,0x18e,-1,79}, {0x18f,0x18f,-1,202}, {0x190,0x190,-1,203}, {0x191,0x191,-1,1}, {0x193,0x193,-1,205}, {0x194,0x194,-1,207}, {0x196,0x196,-1,211}, {0x197,0x197,-1,209}, {0x198,0x198,-1,1}, {0x19c,0x19c,-1,211}, {0x19d,0x19d,-1,213}, {0x19f,0x19f,-1,214}, {0x1a0,0x1a4,2,1}, {0x1a6,0x1a6,-1,218}, {0x1a7,0x1a7,-1,1}, {0x1a9,0x1a9,-1,218}, {0x1ac,0x1ac,-1,1}, {0x1ae,0x1ae,-1,218}, {0x1af,0x1af,-1,1}, {0x1b1,0x1b2,1,217}, {0x1b3,0x1b5,2,1}, {0x1b7,0x1b7,-1,219}, {0x1b8,0x1bc,4,1}, {0x1c4,0x1c4,-1,2}, {0x1c5,0x1c5,-1,1}, {0x1c7,0x1c7,-1,2}, {0x1c8,0x1c8,-1,1}, {0x1ca,0x1ca,-1,2}, {0x1cb,0x1db,2,1}, {0x1de,0x1ee,2,1}, {0x1f1,0x1f1,-1,2}, {0x1f2,0x1f4,2,1}, {0x1f6,0x1f6,-1,-97}, {0x1f7,0x1f7,-1,-56}, {0x1f8,0x21e,2,1}, {0x220,0x220,-1,-130}, {0x222,0x232,2,1}, {0x23a,0x23a,-1,10795}, {0x23b,0x23b,-1,1}, {0x23d,0x23d,-1,-163}, {0x23e,0x23e,-1,10792}, {0x241,0x241,-1,1}, {0x243,0x243,-1,-195}, {0x244,0x244,-1,69}, {0x245,0x245,-1,71}, {0x246,0x24e,2,1}, {0x370,0x372,2,1}, {0x376,0x376,-1,1}, {0x386,0x386,-1,38}, {0x388,0x38a,1,37}, {0x38c,0x38c,-1,64}, {0x38e,0x38f,1,63}, {0x391,0x3a1,1,32}, {0x3a3,0x3ab,1,32}, {0x3cf,0x3cf,-1,8}, {0x3d8,0x3ee,2,1}, {0x3f4,0x3f4,-1,-60}, {0x3f7,0x3f7,-1,1}, {0x3f9,0x3f9,-1,-7}, {0x3fa,0x3fa,-1,1}, {0x3fd,0x3ff,1,-130}, {0x400,0x40f,1,80}, {0x410,0x42f,1,32}, {0x460,0x480,2,1}, {0x48a,0x4be,2,1}, {0x4c0,0x4c0,-1,15}, {0x4c1,0x4cd,2,1}, {0x4d0,0x524,2,1}, {0x531,0x556,1,48}, {0x10a0,0x10c5,1,7264}, {0x1e00,0x1e94,2,1}, {0x1e9e,0x1e9e,-1,-7615}, {0x1ea0,0x1efe,2,1}, {0x1f08,0x1f0f,1,-8}, {0x1f18,0x1f1d,1,-8}, {0x1f28,0x1f2f,1,-8}, {0x1f38,0x1f3f,1,-8}, {0x1f48,0x1f4d,1,-8}, {0x1f59,0x1f5f,2,-8}, {0x1f68,0x1f6f,1,-8}, {0x1f88,0x1f8f,1,-8}, {0x1f98,0x1f9f,1,-8}, {0x1fa8,0x1faf,1,-8}, {0x1fb8,0x1fb9,1,-8}, {0x1fba,0x1fbb,1,-74}, {0x1fbc,0x1fbc,-1,-9}, {0x1fc8,0x1fcb,1,-86}, {0x1fcc,0x1fcc,-1,-9}, {0x1fd8,0x1fd9,1,-8}, {0x1fda,0x1fdb,1,-100}, {0x1fe8,0x1fe9,1,-8}, {0x1fea,0x1feb,1,-112}, {0x1fec,0x1fec,-1,-7}, {0x1ff8,0x1ff9,1,-128}, {0x1ffa,0x1ffb,1,-126}, {0x1ffc,0x1ffc,-1,-9}, {0x2126,0x2126,-1,-7517}, {0x212a,0x212a,-1,-8383}, {0x212b,0x212b,-1,-8262}, {0x2132,0x2132,-1,28}, {0x2160,0x216f,1,16}, {0x2183,0x2183,-1,1}, {0x24b6,0x24cf,1,26}, {0x2c00,0x2c2e,1,48}, {0x2c60,0x2c60,-1,1}, {0x2c62,0x2c62,-1,-10743}, {0x2c63,0x2c63,-1,-3814}, {0x2c64,0x2c64,-1,-10727}, {0x2c67,0x2c6b,2,1}, {0x2c6d,0x2c6d,-1,-10780}, {0x2c6e,0x2c6e,-1,-10749}, {0x2c6f,0x2c6f,-1,-10783}, {0x2c70,0x2c70,-1,-10782}, {0x2c72,0x2c75,3,1}, {0x2c7e,0x2c7f,1,-10815}, {0x2c80,0x2ce2,2,1}, {0x2ceb,0x2ced,2,1}, {0xa640,0xa65e,2,1}, {0xa662,0xa66c,2,1}, {0xa680,0xa696,2,1}, {0xa722,0xa72e,2,1}, {0xa732,0xa76e,2,1}, {0xa779,0xa77b,2,1}, {0xa77d,0xa77d,-1,-35332}, {0xa77e,0xa786,2,1}, {0xa78b,0xa78b,-1,1}, {0xff21,0xff3a,1,32}, {0x10400,0x10427,1,40} }; static convertStruct toUpper[] = { {0x61,0x7a,1,-32}, {0xb5,0xb5,-1,743}, {0xe0,0xf6,1,-32}, /* 0xdf (German sharp s) is not upper-cased */ {0xf8,0xfe,1,-32}, {0xff,0xff,-1,121}, {0x101,0x12f,2,-1}, {0x131,0x131,-1,-232}, {0x133,0x137,2,-1}, {0x13a,0x148,2,-1}, {0x14b,0x177,2,-1}, {0x17a,0x17e,2,-1}, {0x17f,0x17f,-1,-300}, {0x180,0x180,-1,195}, {0x183,0x185,2,-1}, {0x188,0x18c,4,-1}, {0x192,0x192,-1,-1}, {0x195,0x195,-1,97}, {0x199,0x199,-1,-1}, {0x19a,0x19a,-1,163}, {0x19e,0x19e,-1,130}, {0x1a1,0x1a5,2,-1}, {0x1a8,0x1ad,5,-1}, {0x1b0,0x1b4,4,-1}, {0x1b6,0x1b9,3,-1}, {0x1bd,0x1bd,-1,-1}, {0x1bf,0x1bf,-1,56}, {0x1c5,0x1c5,-1,-1}, {0x1c6,0x1c6,-1,-2}, {0x1c8,0x1c8,-1,-1}, {0x1c9,0x1c9,-1,-2}, {0x1cb,0x1cb,-1,-1}, {0x1cc,0x1cc,-1,-2}, {0x1ce,0x1dc,2,-1}, {0x1dd,0x1dd,-1,-79}, {0x1df,0x1ef,2,-1}, {0x1f2,0x1f2,-1,-1}, {0x1f3,0x1f3,-1,-2}, {0x1f5,0x1f9,4,-1}, {0x1fb,0x21f,2,-1}, {0x223,0x233,2,-1}, {0x23c,0x23c,-1,-1}, {0x23f,0x240,1,10815}, {0x242,0x247,5,-1}, {0x249,0x24f,2,-1}, {0x250,0x250,-1,10783}, {0x251,0x251,-1,10780}, {0x252,0x252,-1,10782}, {0x253,0x253,-1,-210}, {0x254,0x254,-1,-206}, {0x256,0x257,1,-205}, {0x259,0x259,-1,-202}, {0x25b,0x25b,-1,-203}, {0x260,0x260,-1,-205}, {0x263,0x263,-1,-207}, {0x268,0x268,-1,-209}, {0x269,0x269,-1,-211}, {0x26b,0x26b,-1,10743}, {0x26f,0x26f,-1,-211}, {0x271,0x271,-1,10749}, {0x272,0x272,-1,-213}, {0x275,0x275,-1,-214}, {0x27d,0x27d,-1,10727}, {0x280,0x283,3,-218}, {0x288,0x288,-1,-218}, {0x289,0x289,-1,-69}, {0x28a,0x28b,1,-217}, {0x28c,0x28c,-1,-71}, {0x292,0x292,-1,-219}, {0x345,0x345,-1,84}, {0x371,0x373,2,-1}, {0x377,0x377,-1,-1}, {0x37b,0x37d,1,130}, {0x3ac,0x3ac,-1,-38}, {0x3ad,0x3af,1,-37}, {0x3b1,0x3c1,1,-32}, {0x3c2,0x3c2,-1,-31}, {0x3c3,0x3cb,1,-32}, {0x3cc,0x3cc,-1,-64}, {0x3cd,0x3ce,1,-63}, {0x3d0,0x3d0,-1,-62}, {0x3d1,0x3d1,-1,-57}, {0x3d5,0x3d5,-1,-47}, {0x3d6,0x3d6,-1,-54}, {0x3d7,0x3d7,-1,-8}, {0x3d9,0x3ef,2,-1}, {0x3f0,0x3f0,-1,-86}, {0x3f1,0x3f1,-1,-80}, {0x3f2,0x3f2,-1,7}, {0x3f5,0x3f5,-1,-96}, {0x3f8,0x3fb,3,-1}, {0x430,0x44f,1,-32}, {0x450,0x45f,1,-80}, {0x461,0x481,2,-1}, {0x48b,0x4bf,2,-1}, {0x4c2,0x4ce,2,-1}, {0x4cf,0x4cf,-1,-15}, {0x4d1,0x525,2,-1}, {0x561,0x586,1,-48}, {0x1d79,0x1d79,-1,35332}, {0x1d7d,0x1d7d,-1,3814}, {0x1e01,0x1e95,2,-1}, {0x1e9b,0x1e9b,-1,-59}, {0x1ea1,0x1eff,2,-1}, {0x1f00,0x1f07,1,8}, {0x1f10,0x1f15,1,8}, {0x1f20,0x1f27,1,8}, {0x1f30,0x1f37,1,8}, {0x1f40,0x1f45,1,8}, {0x1f51,0x1f57,2,8}, {0x1f60,0x1f67,1,8}, {0x1f70,0x1f71,1,74}, {0x1f72,0x1f75,1,86}, {0x1f76,0x1f77,1,100}, {0x1f78,0x1f79,1,128}, {0x1f7a,0x1f7b,1,112}, {0x1f7c,0x1f7d,1,126}, {0x1f80,0x1f87,1,8}, {0x1f90,0x1f97,1,8}, {0x1fa0,0x1fa7,1,8}, {0x1fb0,0x1fb1,1,8}, {0x1fb3,0x1fb3,-1,9}, {0x1fbe,0x1fbe,-1,-7205}, {0x1fc3,0x1fc3,-1,9}, {0x1fd0,0x1fd1,1,8}, {0x1fe0,0x1fe1,1,8}, {0x1fe5,0x1fe5,-1,7}, {0x1ff3,0x1ff3,-1,9}, {0x214e,0x214e,-1,-28}, {0x2170,0x217f,1,-16}, {0x2184,0x2184,-1,-1}, {0x24d0,0x24e9,1,-26}, {0x2c30,0x2c5e,1,-48}, {0x2c61,0x2c61,-1,-1}, {0x2c65,0x2c65,-1,-10795}, {0x2c66,0x2c66,-1,-10792}, {0x2c68,0x2c6c,2,-1}, {0x2c73,0x2c76,3,-1}, {0x2c81,0x2ce3,2,-1}, {0x2cec,0x2cee,2,-1}, {0x2d00,0x2d25,1,-7264}, {0xa641,0xa65f,2,-1}, {0xa663,0xa66d,2,-1}, {0xa681,0xa697,2,-1}, {0xa723,0xa72f,2,-1}, {0xa733,0xa76f,2,-1}, {0xa77a,0xa77c,2,-1}, {0xa77f,0xa787,2,-1}, {0xa78c,0xa78c,-1,-1}, {0xff41,0xff5a,1,-32}, {0x10428,0x1044f,1,-40} }; /* * Return the upper-case equivalent of "a", which is a UCS-4 character. Use * simple case folding. */ int utf_toupper(a) int a; { /* If 'casemap' contains "keepascii" use ASCII style toupper(). */ if (a < 128 && (cmp_flags & CMP_KEEPASCII)) return TOUPPER_ASC(a); #if defined(HAVE_TOWUPPER) && defined(__STDC_ISO_10646__) /* If towupper() is available and handles Unicode, use it. */ if (!(cmp_flags & CMP_INTERNAL)) return towupper(a); #endif /* For characters below 128 use locale sensitive toupper(). */ if (a < 128) return TOUPPER_LOC(a); /* For any other characters use the above mapping table. */ return utf_convert(a, toUpper, (int)sizeof(toUpper)); } int utf_islower(a) int a; { /* German sharp s is lower case but has no upper case equivalent. */ return (utf_toupper(a) != a) || a == 0xdf; } /* * Return the lower-case equivalent of "a", which is a UCS-4 character. Use * simple case folding. */ int utf_tolower(a) int a; { /* If 'casemap' contains "keepascii" use ASCII style tolower(). */ if (a < 128 && (cmp_flags & CMP_KEEPASCII)) return TOLOWER_ASC(a); #if defined(HAVE_TOWLOWER) && defined(__STDC_ISO_10646__) /* If towlower() is available and handles Unicode, use it. */ if (!(cmp_flags & CMP_INTERNAL)) return towlower(a); #endif /* For characters below 128 use locale sensitive tolower(). */ if (a < 128) return TOLOWER_LOC(a); /* For any other characters use the above mapping table. */ return utf_convert(a, toLower, (int)sizeof(toLower)); } int utf_isupper(a) int a; { return (utf_tolower(a) != a); } static int utf_strnicmp(s1, s2, n1, n2) char_u *s1, *s2; size_t n1, n2; { int c1, c2, cdiff; char_u buffer[6]; for (;;) { c1 = utf_safe_read_char_adv(&s1, &n1); c2 = utf_safe_read_char_adv(&s2, &n2); if (c1 <= 0 || c2 <= 0) break; if (c1 == c2) continue; cdiff = utf_fold(c1) - utf_fold(c2); if (cdiff != 0) return cdiff; } /* some string ended or has an incomplete/illegal character sequence */ if (c1 == 0 || c2 == 0) { /* some string ended. shorter string is smaller */ if (c1 == 0 && c2 == 0) return 0; return c1 == 0 ? -1 : 1; } /* Continue with bytewise comparison to produce some result that * would make comparison operations involving this function transitive. * * If only one string had an error, comparison should be made with * folded version of the other string. In this case it is enough * to fold just one character to determine the result of comparison. */ if (c1 != -1 && c2 == -1) { n1 = utf_char2bytes(utf_fold(c1), buffer); s1 = buffer; } else if (c2 != -1 && c1 == -1) { n2 = utf_char2bytes(utf_fold(c2), buffer); s2 = buffer; } while (n1 > 0 && n2 > 0 && *s1 != NUL && *s2 != NUL) { cdiff = (int)(*s1) - (int)(*s2); if (cdiff != 0) return cdiff; s1++; s2++; n1--; n2--; } if (n1 > 0 && *s1 == NUL) n1 = 0; if (n2 > 0 && *s2 == NUL) n2 = 0; if (n1 == 0 && n2 == 0) return 0; return n1 == 0 ? -1 : 1; } /* * Version of strnicmp() that handles multi-byte characters. * Needed for Big5, Sjift-JIS and UTF-8 encoding. Other DBCS encodings can * probably use strnicmp(), because there are no ASCII characters in the * second byte. * Returns zero if s1 and s2 are equal (ignoring case), the difference between * two characters otherwise. */ int mb_strnicmp(s1, s2, nn) char_u *s1, *s2; size_t nn; { int i, l; int cdiff; int n = (int)nn; if (enc_utf8) { return utf_strnicmp(s1, s2, nn, nn); } else { for (i = 0; i < n; i += l) { if (s1[i] == NUL && s2[i] == NUL) /* both strings end */ return 0; l = (*mb_ptr2len)(s1 + i); if (l <= 1) { /* Single byte: first check normally, then with ignore case. */ if (s1[i] != s2[i]) { cdiff = MB_TOLOWER(s1[i]) - MB_TOLOWER(s2[i]); if (cdiff != 0) return cdiff; } } else { /* For non-Unicode multi-byte don't ignore case. */ if (l > n - i) l = n - i; cdiff = STRNCMP(s1 + i, s2 + i, l); if (cdiff != 0) return cdiff; } } } return 0; } /* * "g8": show bytes of the UTF-8 char under the cursor. Doesn't matter what * 'encoding' has been set to. */ void show_utf8() { int len; int rlen = 0; char_u *line; int clen; int i; /* Get the byte length of the char under the cursor, including composing * characters. */ line = ml_get_cursor(); len = utfc_ptr2len(line); if (len == 0) { MSG("NUL"); return; } clen = 0; for (i = 0; i < len; ++i) { if (clen == 0) { /* start of (composing) character, get its length */ if (i > 0) { STRCPY(IObuff + rlen, "+ "); rlen += 2; } clen = utf_ptr2len(line + i); } sprintf((char *)IObuff + rlen, "%02x ", (line[i] == NL) ? NUL : line[i]); /* NUL is stored as NL */ --clen; rlen += (int)STRLEN(IObuff + rlen); if (rlen > IOSIZE - 20) break; } msg(IObuff); } /* * mb_head_off() function pointer. * Return offset from "p" to the first byte of the character it points into. * If "p" points to the NUL at the end of the string return 0. * Returns 0 when already at the first byte of a character. */ int latin_head_off(base, p) char_u *base UNUSED; char_u *p UNUSED; { return 0; } int dbcs_head_off(base, p) char_u *base; char_u *p; { char_u *q; /* It can't be a trailing byte when not using DBCS, at the start of the * string or the previous byte can't start a double-byte. */ if (p <= base || MB_BYTE2LEN(p[-1]) == 1 || *p == NUL) return 0; /* This is slow: need to start at the base and go forward until the * byte we are looking for. Return 1 when we went past it, 0 otherwise. */ q = base; while (q < p) q += dbcs_ptr2len(q); return (q == p) ? 0 : 1; } /* * Special version of dbcs_head_off() that works for ScreenLines[], where * single-width DBCS_JPNU characters are stored separately. */ int dbcs_screen_head_off(base, p) char_u *base; char_u *p; { char_u *q; /* It can't be a trailing byte when not using DBCS, at the start of the * string or the previous byte can't start a double-byte. * For euc-jp an 0x8e byte in the previous cell always means we have a * lead byte in the current cell. */ if (p <= base || (enc_dbcs == DBCS_JPNU && p[-1] == 0x8e) || MB_BYTE2LEN(p[-1]) == 1 || *p == NUL) return 0; /* This is slow: need to start at the base and go forward until the * byte we are looking for. Return 1 when we went past it, 0 otherwise. * For DBCS_JPNU look out for 0x8e, which means the second byte is not * stored as the next byte. */ q = base; while (q < p) { if (enc_dbcs == DBCS_JPNU && *q == 0x8e) ++q; else q += dbcs_ptr2len(q); } return (q == p) ? 0 : 1; } int utf_head_off(base, p) char_u *base; char_u *p; { char_u *q; char_u *s; int c; int len; #ifdef FEAT_ARABIC char_u *j; #endif if (*p < 0x80) /* be quick for ASCII */ return 0; /* Skip backwards over trailing bytes: 10xx.xxxx * Skip backwards again if on a composing char. */ for (q = p; ; --q) { /* Move s to the last byte of this char. */ for (s = q; (s[1] & 0xc0) == 0x80; ++s) ; /* Move q to the first byte of this char. */ while (q > base && (*q & 0xc0) == 0x80) --q; /* Check for illegal sequence. Do allow an illegal byte after where we * started. */ len = utf8len_tab[*q]; if (len != (int)(s - q + 1) && len != (int)(p - q + 1)) return 0; if (q <= base) break; c = utf_ptr2char(q); if (utf_iscomposing(c)) continue; #ifdef FEAT_ARABIC if (arabic_maycombine(c)) { /* Advance to get a sneak-peak at the next char */ j = q; --j; /* Move j to the first byte of this char. */ while (j > base && (*j & 0xc0) == 0x80) --j; if (arabic_combine(utf_ptr2char(j), c)) continue; } #endif break; } return (int)(p - q); } /* * Copy a character from "*fp" to "*tp" and advance the pointers. */ void mb_copy_char(fp, tp) char_u **fp; char_u **tp; { int l = (*mb_ptr2len)(*fp); mch_memmove(*tp, *fp, (size_t)l); *tp += l; *fp += l; } /* * Return the offset from "p" to the first byte of a character. When "p" is * at the start of a character 0 is returned, otherwise the offset to the next * character. Can start anywhere in a stream of bytes. */ int mb_off_next(base, p) char_u *base; char_u *p; { int i; int j; if (enc_utf8) { if (*p < 0x80) /* be quick for ASCII */ return 0; /* Find the next character that isn't 10xx.xxxx */ for (i = 0; (p[i] & 0xc0) == 0x80; ++i) ; if (i > 0) { /* Check for illegal sequence. */ for (j = 0; p - j > base; ++j) if ((p[-j] & 0xc0) != 0x80) break; if (utf8len_tab[p[-j]] != i + j) return 0; } return i; } /* Only need to check if we're on a trail byte, it doesn't matter if we * want the offset to the next or current character. */ return (*mb_head_off)(base, p); } /* * Return the offset from "p" to the last byte of the character it points * into. Can start anywhere in a stream of bytes. */ int mb_tail_off(base, p) char_u *base; char_u *p; { int i; int j; if (*p == NUL) return 0; if (enc_utf8) { /* Find the last character that is 10xx.xxxx */ for (i = 0; (p[i + 1] & 0xc0) == 0x80; ++i) ; /* Check for illegal sequence. */ for (j = 0; p - j > base; ++j) if ((p[-j] & 0xc0) != 0x80) break; if (utf8len_tab[p[-j]] != i + j + 1) return 0; return i; } /* It can't be the first byte if a double-byte when not using DBCS, at the * end of the string or the byte can't start a double-byte. */ if (enc_dbcs == 0 || p[1] == NUL || MB_BYTE2LEN(*p) == 1) return 0; /* Return 1 when on the lead byte, 0 when on the tail byte. */ return 1 - dbcs_head_off(base, p); } /* * Find the next illegal byte sequence. */ void utf_find_illegal() { pos_T pos = curwin->w_cursor; char_u *p; int len; vimconv_T vimconv; char_u *tofree = NULL; vimconv.vc_type = CONV_NONE; if (enc_utf8 && (enc_canon_props(curbuf->b_p_fenc) & ENC_8BIT)) { /* 'encoding' is "utf-8" but we are editing a 8-bit encoded file, * possibly a utf-8 file with illegal bytes. Setup for conversion * from utf-8 to 'fileencoding'. */ convert_setup(&vimconv, p_enc, curbuf->b_p_fenc); } #ifdef FEAT_VIRTUALEDIT curwin->w_cursor.coladd = 0; #endif for (;;) { p = ml_get_cursor(); if (vimconv.vc_type != CONV_NONE) { vim_free(tofree); tofree = string_convert(&vimconv, p, NULL); if (tofree == NULL) break; p = tofree; } while (*p != NUL) { /* Illegal means that there are not enough trail bytes (checked by * utf_ptr2len()) or too many of them (overlong sequence). */ len = utf_ptr2len(p); if (*p >= 0x80 && (len == 1 || utf_char2len(utf_ptr2char(p)) != len)) { if (vimconv.vc_type == CONV_NONE) curwin->w_cursor.col += (colnr_T)(p - ml_get_cursor()); else { int l; len = (int)(p - tofree); for (p = ml_get_cursor(); *p != NUL && len-- > 0; p += l) { l = utf_ptr2len(p); curwin->w_cursor.col += l; } } goto theend; } p += len; } if (curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count) break; ++curwin->w_cursor.lnum; curwin->w_cursor.col = 0; } /* didn't find it: don't move and beep */ curwin->w_cursor = pos; beep_flush(); theend: vim_free(tofree); convert_setup(&vimconv, NULL, NULL); } #if defined(FEAT_GUI_GTK) || defined(PROTO) /* * Return TRUE if string "s" is a valid utf-8 string. * When "end" is NULL stop at the first NUL. * When "end" is positive stop there. */ int utf_valid_string(s, end) char_u *s; char_u *end; { int l; char_u *p = s; while (end == NULL ? *p != NUL : p < end) { l = utf8len_tab_zero[*p]; if (l == 0) return FALSE; /* invalid lead byte */ if (end != NULL && p + l > end) return FALSE; /* incomplete byte sequence */ ++p; while (--l > 0) if ((*p++ & 0xc0) != 0x80) return FALSE; /* invalid trail byte */ } return TRUE; } #endif #if defined(FEAT_GUI) || defined(PROTO) /* * Special version of mb_tail_off() for use in ScreenLines[]. */ int dbcs_screen_tail_off(base, p) char_u *base; char_u *p; { /* It can't be the first byte if a double-byte when not using DBCS, at the * end of the string or the byte can't start a double-byte. * For euc-jp an 0x8e byte always means we have a lead byte in the current * cell. */ if (*p == NUL || p[1] == NUL || (enc_dbcs == DBCS_JPNU && *p == 0x8e) || MB_BYTE2LEN(*p) == 1) return 0; /* Return 1 when on the lead byte, 0 when on the tail byte. */ return 1 - dbcs_screen_head_off(base, p); } #endif /* * If the cursor moves on an trail byte, set the cursor on the lead byte. * Thus it moves left if necessary. * Return TRUE when the cursor was adjusted. */ void mb_adjust_cursor() { mb_adjustpos(curbuf, &curwin->w_cursor); } /* * Adjust position "*lp" to point to the first byte of a multi-byte character. * If it points to a tail byte it's moved backwards to the head byte. */ void mb_adjustpos(buf, lp) buf_T *buf; pos_T *lp; { char_u *p; if (lp->col > 0 #ifdef FEAT_VIRTUALEDIT || lp->coladd > 1 #endif ) { p = ml_get_buf(buf, lp->lnum, FALSE); lp->col -= (*mb_head_off)(p, p + lp->col); #ifdef FEAT_VIRTUALEDIT /* Reset "coladd" when the cursor would be on the right half of a * double-wide character. */ if (lp->coladd == 1 && p[lp->col] != TAB && vim_isprintc((*mb_ptr2char)(p + lp->col)) && ptr2cells(p + lp->col) > 1) lp->coladd = 0; #endif } } /* * Return a pointer to the character before "*p", if there is one. */ char_u * mb_prevptr(line, p) char_u *line; /* start of the string */ char_u *p; { if (p > line) mb_ptr_back(line, p); return p; } /* * Return the character length of "str". Each multi-byte character (with * following composing characters) counts as one. */ int mb_charlen(str) char_u *str; { char_u *p = str; int count; if (p == NULL) return 0; for (count = 0; *p != NUL; count++) p += (*mb_ptr2len)(p); return count; } #if defined(FEAT_SPELL) || defined(PROTO) /* * Like mb_charlen() but for a string with specified length. */ int mb_charlen_len(str, len) char_u *str; int len; { char_u *p = str; int count; for (count = 0; *p != NUL && p < str + len; count++) p += (*mb_ptr2len)(p); return count; } #endif /* * Try to un-escape a multi-byte character. * Used for the "to" and "from" part of a mapping. * Return the un-escaped string if it is a multi-byte character, and advance * "pp" to just after the bytes that formed it. * Return NULL if no multi-byte char was found. */ char_u * mb_unescape(pp) char_u **pp; { static char_u buf[MB_MAXBYTES + 1]; int n, m = 0; char_u *str = *pp; /* Must translate K_SPECIAL KS_SPECIAL KE_FILLER to K_SPECIAL and CSI * KS_EXTRA KE_CSI to CSI. */ for (n = 0; str[n] != NUL && m <= MB_MAXBYTES; ++n) { if (str[n] == K_SPECIAL && str[n + 1] == KS_SPECIAL && str[n + 2] == KE_FILLER) { buf[m++] = K_SPECIAL; n += 2; } else if ((str[n] == K_SPECIAL # ifdef FEAT_GUI || str[n] == CSI # endif ) && str[n + 1] == KS_EXTRA && str[n + 2] == (int)KE_CSI) { buf[m++] = CSI; n += 2; } else if (str[n] == K_SPECIAL # ifdef FEAT_GUI || str[n] == CSI # endif ) break; /* a special key can't be a multibyte char */ else buf[m++] = str[n]; buf[m] = NUL; /* Return a multi-byte character if it's found. An illegal sequence * will result in a 1 here. */ if ((*mb_ptr2len)(buf) > 1) { *pp = str + n + 1; return buf; } } return NULL; } /* * Return TRUE if the character at "row"/"col" on the screen is the left side * of a double-width character. * Caller must make sure "row" and "col" are not invalid! */ int mb_lefthalve(row, col) int row; int col; { #ifdef FEAT_HANGULIN if (composing_hangul) return TRUE; #endif return (*mb_off2cells)(LineOffset[row] + col, LineOffset[row] + screen_Columns) > 1; } /* * Correct a position on the screen, if it's the right half of a double-wide * char move it to the left half. Returns the corrected column. */ int mb_fix_col(col, row) int col; int row; { col = check_col(col); row = check_row(row); if (has_mbyte && ScreenLines != NULL && col > 0 && ((enc_dbcs && ScreenLines[LineOffset[row] + col] != NUL && dbcs_screen_head_off(ScreenLines + LineOffset[row], ScreenLines + LineOffset[row] + col)) || (enc_utf8 && ScreenLines[LineOffset[row] + col] == 0))) return col - 1; return col; } #endif #if defined(FEAT_MBYTE) || defined(FEAT_POSTSCRIPT) || defined(PROTO) static int enc_alias_search __ARGS((char_u *name)); /* * Skip the Vim specific head of a 'encoding' name. */ char_u * enc_skip(p) char_u *p; { if (STRNCMP(p, "2byte-", 6) == 0) return p + 6; if (STRNCMP(p, "8bit-", 5) == 0) return p + 5; return p; } /* * Find the canonical name for encoding "enc". * When the name isn't recognized, returns "enc" itself, but with all lower * case characters and '_' replaced with '-'. * Returns an allocated string. NULL for out-of-memory. */ char_u * enc_canonize(enc) char_u *enc; { char_u *r; char_u *p, *s; int i; # ifdef FEAT_MBYTE if (STRCMP(enc, "default") == 0) { /* Use the default encoding as it's found by set_init_1(). */ r = get_encoding_default(); if (r == NULL) r = (char_u *)"latin1"; return vim_strsave(r); } # endif /* copy "enc" to allocated memory, with room for two '-' */ r = alloc((unsigned)(STRLEN(enc) + 3)); if (r != NULL) { /* Make it all lower case and replace '_' with '-'. */ p = r; for (s = enc; *s != NUL; ++s) { if (*s == '_') *p++ = '-'; else *p++ = TOLOWER_ASC(*s); } *p = NUL; /* Skip "2byte-" and "8bit-". */ p = enc_skip(r); /* Change "microsoft-cp" to "cp". Used in some spell files. */ if (STRNCMP(p, "microsoft-cp", 12) == 0) STRMOVE(p, p + 10); /* "iso8859" -> "iso-8859" */ if (STRNCMP(p, "iso8859", 7) == 0) { STRMOVE(p + 4, p + 3); p[3] = '-'; } /* "iso-8859n" -> "iso-8859-n" */ if (STRNCMP(p, "iso-8859", 8) == 0 && p[8] != '-') { STRMOVE(p + 9, p + 8); p[8] = '-'; } /* "latin-N" -> "latinN" */ if (STRNCMP(p, "latin-", 6) == 0) STRMOVE(p + 5, p + 6); if (enc_canon_search(p) >= 0) { /* canonical name can be used unmodified */ if (p != r) STRMOVE(r, p); } else if ((i = enc_alias_search(p)) >= 0) { /* alias recognized, get canonical name */ vim_free(r); r = vim_strsave((char_u *)enc_canon_table[i].name); } } return r; } /* * Search for an encoding alias of "name". * Returns -1 when not found. */ static int enc_alias_search(name) char_u *name; { int i; for (i = 0; enc_alias_table[i].name != NULL; ++i) if (STRCMP(name, enc_alias_table[i].name) == 0) return enc_alias_table[i].canon; return -1; } #endif #if defined(FEAT_MBYTE) || defined(PROTO) #ifdef HAVE_LANGINFO_H # include <langinfo.h> #endif /* * Get the canonicalized encoding of the current locale. * Returns an allocated string when successful, NULL when not. */ char_u * enc_locale() { #ifndef WIN3264 char *s; char *p; int i; #endif char buf[50]; #ifdef WIN3264 long acp = GetACP(); if (acp == 1200) STRCPY(buf, "ucs-2le"); else if (acp == 1252) /* cp1252 is used as latin1 */ STRCPY(buf, "latin1"); else sprintf(buf, "cp%ld", acp); #else # ifdef HAVE_NL_LANGINFO_CODESET if ((s = nl_langinfo(CODESET)) == NULL || *s == NUL) # endif # if defined(HAVE_LOCALE_H) || defined(X_LOCALE) if ((s = setlocale(LC_CTYPE, NULL)) == NULL || *s == NUL) # endif if ((s = getenv("LC_ALL")) == NULL || *s == NUL) if ((s = getenv("LC_CTYPE")) == NULL || *s == NUL) s = getenv("LANG"); if (s == NULL || *s == NUL) return FAIL; /* The most generic locale format is: * language[_territory][.codeset][@modifier][+special][,[sponsor][_revision]] * If there is a '.' remove the part before it. * if there is something after the codeset, remove it. * Make the name lowercase and replace '_' with '-'. * Exception: "ja_JP.EUC" == "euc-jp", "zh_CN.EUC" = "euc-cn", * "ko_KR.EUC" == "euc-kr" */ if ((p = (char *)vim_strchr((char_u *)s, '.')) != NULL) { if (p > s + 2 && STRNICMP(p + 1, "EUC", 3) == 0 && !isalnum((int)p[4]) && p[4] != '-' && p[-3] == '_') { /* copy "XY.EUC" to "euc-XY" to buf[10] */ STRCPY(buf + 10, "euc-"); buf[14] = p[-2]; buf[15] = p[-1]; buf[16] = 0; s = buf + 10; } else s = p + 1; } for (i = 0; s[i] != NUL && i < (int)sizeof(buf) - 1; ++i) { if (s[i] == '_' || s[i] == '-') buf[i] = '-'; else if (isalnum((int)s[i])) buf[i] = TOLOWER_ASC(s[i]); else break; } buf[i] = NUL; #endif return enc_canonize((char_u *)buf); } #if defined(WIN3264) || defined(PROTO) /* * Convert an encoding name to an MS-Windows codepage. * Returns zero if no codepage can be figured out. */ int encname2codepage(name) char_u *name; { int cp; char_u *p = name; int idx; if (STRNCMP(p, "8bit-", 5) == 0) p += 5; else if (STRNCMP(p_enc, "2byte-", 6) == 0) p += 6; if (p[0] == 'c' && p[1] == 'p') cp = atoi(p + 2); else if ((idx = enc_canon_search(p)) >= 0) cp = enc_canon_table[idx].codepage; else return 0; if (IsValidCodePage(cp)) return cp; return 0; } #endif # if defined(USE_ICONV) || defined(PROTO) static char_u *iconv_string __ARGS((vimconv_T *vcp, char_u *str, int slen, int *unconvlenp, int *resultlenp)); /* * Call iconv_open() with a check if iconv() works properly (there are broken * versions). * Returns (void *)-1 if failed. * (should return iconv_t, but that causes problems with prototypes). */ void * my_iconv_open(to, from) char_u *to; char_u *from; { iconv_t fd; #define ICONV_TESTLEN 400 char_u tobuf[ICONV_TESTLEN]; char *p; size_t tolen; static int iconv_ok = -1; if (iconv_ok == FALSE) return (void *)-1; /* detected a broken iconv() previously */ #ifdef DYNAMIC_ICONV /* Check if the iconv.dll can be found. */ if (!iconv_enabled(TRUE)) return (void *)-1; #endif fd = iconv_open((char *)enc_skip(to), (char *)enc_skip(from)); if (fd != (iconv_t)-1 && iconv_ok == -1) { /* * Do a dummy iconv() call to check if it actually works. There is a * version of iconv() on Linux that is broken. We can't ignore it, * because it's wide-spread. The symptoms are that after outputting * the initial shift state the "to" pointer is NULL and conversion * stops for no apparent reason after about 8160 characters. */ p = (char *)tobuf; tolen = ICONV_TESTLEN; (void)iconv(fd, NULL, NULL, &p, &tolen); if (p == NULL) { iconv_ok = FALSE; iconv_close(fd); fd = (iconv_t)-1; } else iconv_ok = TRUE; } return (void *)fd; } /* * Convert the string "str[slen]" with iconv(). * If "unconvlenp" is not NULL handle the string ending in an incomplete * sequence and set "*unconvlenp" to the length of it. * Returns the converted string in allocated memory. NULL for an error. * If resultlenp is not NULL, sets it to the result length in bytes. */ static char_u * iconv_string(vcp, str, slen, unconvlenp, resultlenp) vimconv_T *vcp; char_u *str; int slen; int *unconvlenp; int *resultlenp; { const char *from; size_t fromlen; char *to; size_t tolen; size_t len = 0; size_t done = 0; char_u *result = NULL; char_u *p; int l; from = (char *)str; fromlen = slen; for (;;) { if (len == 0 || ICONV_ERRNO == ICONV_E2BIG) { /* Allocate enough room for most conversions. When re-allocating * increase the buffer size. */ len = len + fromlen * 2 + 40; p = alloc((unsigned)len); if (p != NULL && done > 0) mch_memmove(p, result, done); vim_free(result); result = p; if (result == NULL) /* out of memory */ break; } to = (char *)result + done; tolen = len - done - 2; /* Avoid a warning for systems with a wrong iconv() prototype by * casting the second argument to void *. */ if (iconv(vcp->vc_fd, (void *)&from, &fromlen, &to, &tolen) != (size_t)-1) { /* Finished, append a NUL. */ *to = NUL; break; } /* Check both ICONV_EINVAL and EINVAL, because the dynamically loaded * iconv library may use one of them. */ if (!vcp->vc_fail && unconvlenp != NULL && (ICONV_ERRNO == ICONV_EINVAL || ICONV_ERRNO == EINVAL)) { /* Handle an incomplete sequence at the end. */ *to = NUL; *unconvlenp = (int)fromlen; break; } /* Check both ICONV_EILSEQ and EILSEQ, because the dynamically loaded * iconv library may use one of them. */ else if (!vcp->vc_fail && (ICONV_ERRNO == ICONV_EILSEQ || ICONV_ERRNO == EILSEQ || ICONV_ERRNO == ICONV_EINVAL || ICONV_ERRNO == EINVAL)) { /* Can't convert: insert a '?' and skip a character. This assumes * conversion from 'encoding' to something else. In other * situations we don't know what to skip anyway. */ *to++ = '?'; if ((*mb_ptr2cells)((char_u *)from) > 1) *to++ = '?'; if (enc_utf8) l = utfc_ptr2len_len((char_u *)from, (int)fromlen); else { l = (*mb_ptr2len)((char_u *)from); if (l > (int)fromlen) l = (int)fromlen; } from += l; fromlen -= l; } else if (ICONV_ERRNO != ICONV_E2BIG) { /* conversion failed */ vim_free(result); result = NULL; break; } /* Not enough room or skipping illegal sequence. */ done = to - (char *)result; } if (resultlenp != NULL && result != NULL) *resultlenp = (int)(to - (char *)result); return result; } # if defined(DYNAMIC_ICONV) || defined(PROTO) /* * Dynamically load the "iconv.dll" on Win32. */ #ifndef DYNAMIC_ICONV /* just generating prototypes */ # define HINSTANCE int #endif static HINSTANCE hIconvDLL = 0; static HINSTANCE hMsvcrtDLL = 0; # ifndef DYNAMIC_ICONV_DLL # define DYNAMIC_ICONV_DLL "iconv.dll" # define DYNAMIC_ICONV_DLL_ALT "libiconv.dll" # endif # ifndef DYNAMIC_MSVCRT_DLL # define DYNAMIC_MSVCRT_DLL "msvcrt.dll" # endif /* * Try opening the iconv.dll and return TRUE if iconv() can be used. */ int iconv_enabled(verbose) int verbose; { if (hIconvDLL != 0 && hMsvcrtDLL != 0) return TRUE; hIconvDLL = vimLoadLib(DYNAMIC_ICONV_DLL); if (hIconvDLL == 0) /* sometimes it's called libiconv.dll */ hIconvDLL = vimLoadLib(DYNAMIC_ICONV_DLL_ALT); if (hIconvDLL != 0) hMsvcrtDLL = vimLoadLib(DYNAMIC_MSVCRT_DLL); if (hIconvDLL == 0 || hMsvcrtDLL == 0) { /* Only give the message when 'verbose' is set, otherwise it might be * done whenever a conversion is attempted. */ if (verbose && p_verbose > 0) { verbose_enter(); EMSG2(_(e_loadlib), hIconvDLL == 0 ? DYNAMIC_ICONV_DLL : DYNAMIC_MSVCRT_DLL); verbose_leave(); } iconv_end(); return FALSE; } iconv = (void *)GetProcAddress(hIconvDLL, "libiconv"); iconv_open = (void *)GetProcAddress(hIconvDLL, "libiconv_open"); iconv_close = (void *)GetProcAddress(hIconvDLL, "libiconv_close"); iconvctl = (void *)GetProcAddress(hIconvDLL, "libiconvctl"); iconv_errno = (void *)GetProcAddress(hMsvcrtDLL, "_errno"); if (iconv == NULL || iconv_open == NULL || iconv_close == NULL || iconvctl == NULL || iconv_errno == NULL) { iconv_end(); if (verbose && p_verbose > 0) { verbose_enter(); EMSG2(_(e_loadfunc), "for libiconv"); verbose_leave(); } return FALSE; } return TRUE; } void iconv_end() { /* Don't use iconv() when inputting or outputting characters. */ if (input_conv.vc_type == CONV_ICONV) convert_setup(&input_conv, NULL, NULL); if (output_conv.vc_type == CONV_ICONV) convert_setup(&output_conv, NULL, NULL); if (hIconvDLL != 0) FreeLibrary(hIconvDLL); if (hMsvcrtDLL != 0) FreeLibrary(hMsvcrtDLL); hIconvDLL = 0; hMsvcrtDLL = 0; } # endif /* DYNAMIC_ICONV */ # endif /* USE_ICONV */ #endif /* FEAT_MBYTE */ #if defined(FEAT_XIM) || defined(PROTO) # if defined(FEAT_GUI_GTK) || defined(PROTO) static int xim_has_preediting INIT(= FALSE); /* IM current status */ /* * Set preedit_start_col to the current cursor position. */ static void init_preedit_start_col(void) { if (State & CMDLINE) preedit_start_col = cmdline_getvcol_cursor(); else if (curwin != NULL) getvcol(curwin, &curwin->w_cursor, &preedit_start_col, NULL, NULL); /* Prevent that preediting marks the buffer as changed. */ xim_changed_while_preediting = curbuf->b_changed; } static int im_is_active = FALSE; /* IM is enabled for current mode */ static int preedit_is_active = FALSE; static int im_preedit_cursor = 0; /* cursor offset in characters */ static int im_preedit_trailing = 0; /* number of characters after cursor */ static unsigned long im_commit_handler_id = 0; static unsigned int im_activatekey_keyval = GDK_VoidSymbol; static unsigned int im_activatekey_state = 0; void im_set_active(int active) { int was_active; was_active = !!im_is_active; im_is_active = (active && !p_imdisable); if (im_is_active != was_active) xim_reset(); } void xim_set_focus(int focus) { if (xic != NULL) { if (focus) gtk_im_context_focus_in(xic); else gtk_im_context_focus_out(xic); } } void im_set_position(int row, int col) { if (xic != NULL) { GdkRectangle area; area.x = FILL_X(col); area.y = FILL_Y(row); area.width = gui.char_width * (mb_lefthalve(row, col) ? 2 : 1); area.height = gui.char_height; gtk_im_context_set_cursor_location(xic, &area); } } # if 0 || defined(PROTO) /* apparently only used in gui_x11.c */ void xim_set_preedit(void) { im_set_position(gui.row, gui.col); } # endif static void im_add_to_input(char_u *str, int len) { /* Convert from 'termencoding' (always "utf-8") to 'encoding' */ if (input_conv.vc_type != CONV_NONE) { str = string_convert(&input_conv, str, &len); g_return_if_fail(str != NULL); } add_to_input_buf_csi(str, len); if (input_conv.vc_type != CONV_NONE) vim_free(str); if (p_mh) /* blank out the pointer if necessary */ gui_mch_mousehide(TRUE); } static void im_delete_preedit(void) { char_u bskey[] = {CSI, 'k', 'b'}; char_u delkey[] = {CSI, 'k', 'D'}; if (State & NORMAL) { im_preedit_cursor = 0; return; } for (; im_preedit_cursor > 0; --im_preedit_cursor) add_to_input_buf(bskey, (int)sizeof(bskey)); for (; im_preedit_trailing > 0; --im_preedit_trailing) add_to_input_buf(delkey, (int)sizeof(delkey)); } /* * Move the cursor left by "num_move_back" characters. * Note that ins_left() checks im_is_preediting() to avoid breaking undo for * these K_LEFT keys. */ static void im_correct_cursor(int num_move_back) { char_u backkey[] = {CSI, 'k', 'l'}; if (State & NORMAL) return; # ifdef FEAT_RIGHTLEFT if ((State & CMDLINE) == 0 && curwin != NULL && curwin->w_p_rl) backkey[2] = 'r'; # endif for (; num_move_back > 0; --num_move_back) add_to_input_buf(backkey, (int)sizeof(backkey)); } static int xim_expected_char = NUL; static int xim_ignored_char = FALSE; /* * Update the mode and cursor while in an IM callback. */ static void im_show_info(void) { int old_vgetc_busy; old_vgetc_busy = vgetc_busy; vgetc_busy = TRUE; showmode(); vgetc_busy = old_vgetc_busy; if ((State & NORMAL) || (State & INSERT)) setcursor(); out_flush(); } /* * Callback invoked when the user finished preediting. * Put the final string into the input buffer. */ static void im_commit_cb(GtkIMContext *context UNUSED, const gchar *str, gpointer data UNUSED) { int slen = (int)STRLEN(str); int add_to_input = TRUE; int clen; int len = slen; int commit_with_preedit = TRUE; char_u *im_str; #ifdef XIM_DEBUG xim_log("im_commit_cb(): %s\n", str); #endif /* The imhangul module doesn't reset the preedit string before * committing. Call im_delete_preedit() to work around that. */ im_delete_preedit(); /* Indicate that preediting has finished. */ if (preedit_start_col == MAXCOL) { init_preedit_start_col(); commit_with_preedit = FALSE; } /* The thing which setting "preedit_start_col" to MAXCOL means that * "preedit_start_col" will be set forcely when calling * preedit_changed_cb() next time. * "preedit_start_col" should not reset with MAXCOL on this part. Vim * is simulating the preediting by using add_to_input_str(). when * preedit begin immediately before committed, the typebuf is not * flushed to screen, then it can't get correct "preedit_start_col". * Thus, it should calculate the cells by adding cells of the committed * string. */ if (input_conv.vc_type != CONV_NONE) { im_str = string_convert(&input_conv, (char_u *)str, &len); g_return_if_fail(im_str != NULL); } else im_str = (char_u *)str; clen = mb_string2cells(im_str, len); if (input_conv.vc_type != CONV_NONE) vim_free(im_str); preedit_start_col += clen; /* Is this a single character that matches a keypad key that's just * been pressed? If so, we don't want it to be entered as such - let * us carry on processing the raw keycode so that it may be used in * mappings as <kSomething>. */ if (xim_expected_char != NUL) { /* We're currently processing a keypad or other special key */ if (slen == 1 && str[0] == xim_expected_char) { /* It's a match - don't do it here */ xim_ignored_char = TRUE; add_to_input = FALSE; } else { /* Not a match */ xim_ignored_char = FALSE; } } if (add_to_input) im_add_to_input((char_u *)str, slen); /* Inserting chars while "im_is_active" is set does not cause a change of * buffer. When the chars are committed the buffer must be marked as * changed. */ if (!commit_with_preedit) preedit_start_col = MAXCOL; /* This flag is used in changed() at next call. */ xim_changed_while_preediting = TRUE; if (gtk_main_level() > 0) gtk_main_quit(); } /* * Callback invoked after start to the preedit. */ static void im_preedit_start_cb(GtkIMContext *context UNUSED, gpointer data UNUSED) { #ifdef XIM_DEBUG xim_log("im_preedit_start_cb()\n"); #endif im_is_active = TRUE; preedit_is_active = TRUE; gui_update_cursor(TRUE, FALSE); im_show_info(); } /* * Callback invoked after end to the preedit. */ static void im_preedit_end_cb(GtkIMContext *context UNUSED, gpointer data UNUSED) { #ifdef XIM_DEBUG xim_log("im_preedit_end_cb()\n"); #endif im_delete_preedit(); /* Indicate that preediting has finished */ preedit_start_col = MAXCOL; xim_has_preediting = FALSE; #if 0 /* Removal of this line suggested by Takuhiro Nishioka. Fixes that IM was * switched off unintentionally. We now use preedit_is_active (added by * SungHyun Nam). */ im_is_active = FALSE; #endif preedit_is_active = FALSE; gui_update_cursor(TRUE, FALSE); im_show_info(); } /* * Callback invoked after changes to the preedit string. If the preedit * string was empty before, remember the preedit start column so we know * where to apply feedback attributes. Delete the previous preedit string * if there was one, save the new preedit cursor offset, and put the new * string into the input buffer. * * TODO: The pragmatic "put into input buffer" approach used here has * several fundamental problems: * * - The characters in the preedit string are subject to remapping. * That's broken, only the finally committed string should be remapped. * * - There is a race condition involved: The retrieved value for the * current cursor position will be wrong if any unprocessed characters * are still queued in the input buffer. * * - Due to the lack of synchronization between the file buffer in memory * and any typed characters, it's practically impossible to implement the * "retrieve_surrounding" and "delete_surrounding" signals reliably. IM * modules for languages such as Thai are likely to rely on this feature * for proper operation. * * Conclusions: I think support for preediting needs to be moved to the * core parts of Vim. Ideally, until it has been committed, the preediting * string should only be displayed and not affect the buffer content at all. * The question how to deal with the synchronization issue still remains. * Circumventing the input buffer is probably not desirable. Anyway, I think * implementing "retrieve_surrounding" is the only hard problem. * * One way to solve all of this in a clean manner would be to queue all key * press/release events "as is" in the input buffer, and apply the IM filtering * at the receiving end of the queue. This, however, would have a rather large * impact on the code base. If there is an easy way to force processing of all * remaining input from within the "retrieve_surrounding" signal handler, this * might not be necessary. Gotta ask on vim-dev for opinions. */ static void im_preedit_changed_cb(GtkIMContext *context, gpointer data UNUSED) { char *preedit_string = NULL; int cursor_index = 0; int num_move_back = 0; char_u *str; char_u *p; int i; gtk_im_context_get_preedit_string(context, &preedit_string, NULL, &cursor_index); #ifdef XIM_DEBUG xim_log("im_preedit_changed_cb(): %s\n", preedit_string); #endif g_return_if_fail(preedit_string != NULL); /* just in case */ /* If preedit_start_col is MAXCOL set it to the current cursor position. */ if (preedit_start_col == MAXCOL && preedit_string[0] != '\0') { xim_has_preediting = TRUE; /* Urgh, this breaks if the input buffer isn't empty now */ init_preedit_start_col(); } else if (cursor_index == 0 && preedit_string[0] == '\0') { xim_has_preediting = FALSE; /* If at the start position (after typing backspace) * preedit_start_col must be reset. */ preedit_start_col = MAXCOL; } im_delete_preedit(); /* * Compute the end of the preediting area: "preedit_end_col". * According to the documentation of gtk_im_context_get_preedit_string(), * the cursor_pos output argument returns the offset in bytes. This is * unfortunately not true -- real life shows the offset is in characters, * and the GTK+ source code agrees with me. Will file a bug later. */ if (preedit_start_col != MAXCOL) preedit_end_col = preedit_start_col; str = (char_u *)preedit_string; for (p = str, i = 0; *p != NUL; p += utf_byte2len(*p), ++i) { int is_composing; is_composing = ((*p & 0x80) != 0 && utf_iscomposing(utf_ptr2char(p))); /* * These offsets are used as counters when generating <BS> and <Del> * to delete the preedit string. So don't count composing characters * unless 'delcombine' is enabled. */ if (!is_composing || p_deco) { if (i < cursor_index) ++im_preedit_cursor; else ++im_preedit_trailing; } if (!is_composing && i >= cursor_index) { /* This is essentially the same as im_preedit_trailing, except * composing characters are not counted even if p_deco is set. */ ++num_move_back; } if (preedit_start_col != MAXCOL) preedit_end_col += utf_ptr2cells(p); } if (p > str) { im_add_to_input(str, (int)(p - str)); im_correct_cursor(num_move_back); } g_free(preedit_string); if (gtk_main_level() > 0) gtk_main_quit(); } /* * Translate the Pango attributes at iter to Vim highlighting attributes. * Ignore attributes not supported by Vim highlighting. This shouldn't have * too much impact -- right now we handle even more attributes than necessary * for the IM modules I tested with. */ static int translate_pango_attributes(PangoAttrIterator *iter) { PangoAttribute *attr; int char_attr = HL_NORMAL; attr = pango_attr_iterator_get(iter, PANGO_ATTR_UNDERLINE); if (attr != NULL && ((PangoAttrInt *)attr)->value != (int)PANGO_UNDERLINE_NONE) char_attr |= HL_UNDERLINE; attr = pango_attr_iterator_get(iter, PANGO_ATTR_WEIGHT); if (attr != NULL && ((PangoAttrInt *)attr)->value >= (int)PANGO_WEIGHT_BOLD) char_attr |= HL_BOLD; attr = pango_attr_iterator_get(iter, PANGO_ATTR_STYLE); if (attr != NULL && ((PangoAttrInt *)attr)->value != (int)PANGO_STYLE_NORMAL) char_attr |= HL_ITALIC; attr = pango_attr_iterator_get(iter, PANGO_ATTR_BACKGROUND); if (attr != NULL) { const PangoColor *color = &((PangoAttrColor *)attr)->color; /* Assume inverse if black background is requested */ if ((color->red | color->green | color->blue) == 0) char_attr |= HL_INVERSE; } return char_attr; } /* * Retrieve the highlighting attributes at column col in the preedit string. * Return -1 if not in preediting mode or if col is out of range. */ int im_get_feedback_attr(int col) { char *preedit_string = NULL; PangoAttrList *attr_list = NULL; int char_attr = -1; if (xic == NULL) return char_attr; gtk_im_context_get_preedit_string(xic, &preedit_string, &attr_list, NULL); if (preedit_string != NULL && attr_list != NULL) { int idx; /* Get the byte index as used by PangoAttrIterator */ for (idx = 0; col > 0 && preedit_string[idx] != '\0'; --col) idx += utfc_ptr2len((char_u *)preedit_string + idx); if (preedit_string[idx] != '\0') { PangoAttrIterator *iter; int start, end; char_attr = HL_NORMAL; iter = pango_attr_list_get_iterator(attr_list); /* Extract all relevant attributes from the list. */ do { pango_attr_iterator_range(iter, &start, &end); if (idx >= start && idx < end) char_attr |= translate_pango_attributes(iter); } while (pango_attr_iterator_next(iter)); pango_attr_iterator_destroy(iter); } } if (attr_list != NULL) pango_attr_list_unref(attr_list); g_free(preedit_string); return char_attr; } void xim_init(void) { #ifdef XIM_DEBUG xim_log("xim_init()\n"); #endif g_return_if_fail(gui.drawarea != NULL); g_return_if_fail(gui.drawarea->window != NULL); xic = gtk_im_multicontext_new(); g_object_ref(xic); im_commit_handler_id = g_signal_connect(G_OBJECT(xic), "commit", G_CALLBACK(&im_commit_cb), NULL); g_signal_connect(G_OBJECT(xic), "preedit_changed", G_CALLBACK(&im_preedit_changed_cb), NULL); g_signal_connect(G_OBJECT(xic), "preedit_start", G_CALLBACK(&im_preedit_start_cb), NULL); g_signal_connect(G_OBJECT(xic), "preedit_end", G_CALLBACK(&im_preedit_end_cb), NULL); gtk_im_context_set_client_window(xic, gui.drawarea->window); } void im_shutdown(void) { #ifdef XIM_DEBUG xim_log("im_shutdown()\n"); #endif if (xic != NULL) { gtk_im_context_focus_out(xic); g_object_unref(xic); xic = NULL; } im_is_active = FALSE; im_commit_handler_id = 0; preedit_start_col = MAXCOL; xim_has_preediting = FALSE; } /* * Convert the string argument to keyval and state for GdkEventKey. * If str is valid return TRUE, otherwise FALSE. * * See 'imactivatekey' for documentation of the format. */ static int im_string_to_keyval(const char *str, unsigned int *keyval, unsigned int *state) { const char *mods_end; unsigned tmp_keyval; unsigned tmp_state = 0; mods_end = strrchr(str, '-'); mods_end = (mods_end != NULL) ? mods_end + 1 : str; /* Parse modifier keys */ while (str < mods_end) switch (*str++) { case '-': break; case 'S': case 's': tmp_state |= (unsigned)GDK_SHIFT_MASK; break; case 'L': case 'l': tmp_state |= (unsigned)GDK_LOCK_MASK; break; case 'C': case 'c': tmp_state |= (unsigned)GDK_CONTROL_MASK;break; case '1': tmp_state |= (unsigned)GDK_MOD1_MASK; break; case '2': tmp_state |= (unsigned)GDK_MOD2_MASK; break; case '3': tmp_state |= (unsigned)GDK_MOD3_MASK; break; case '4': tmp_state |= (unsigned)GDK_MOD4_MASK; break; case '5': tmp_state |= (unsigned)GDK_MOD5_MASK; break; default: return FALSE; } tmp_keyval = gdk_keyval_from_name(str); if (tmp_keyval == 0 || tmp_keyval == GDK_VoidSymbol) return FALSE; if (keyval != NULL) *keyval = tmp_keyval; if (state != NULL) *state = tmp_state; return TRUE; } /* * Return TRUE if p_imak is valid, otherwise FALSE. As a special case, an * empty string is also regarded as valid. * * Note: The numerical key value of p_imak is cached if it was valid; thus * boldly assuming im_xim_isvalid_imactivate() will always be called whenever * 'imak' changes. This is currently the case but not obvious -- should * probably rename the function for clarity. */ int im_xim_isvalid_imactivate(void) { if (p_imak[0] == NUL) { im_activatekey_keyval = GDK_VoidSymbol; im_activatekey_state = 0; return TRUE; } return im_string_to_keyval((const char *)p_imak, &im_activatekey_keyval, &im_activatekey_state); } static void im_synthesize_keypress(unsigned int keyval, unsigned int state) { GdkEventKey *event; # ifdef HAVE_GTK_MULTIHEAD event = (GdkEventKey *)gdk_event_new(GDK_KEY_PRESS); g_object_ref(gui.drawarea->window); /* unreffed by gdk_event_free() */ # else event = (GdkEventKey *)g_malloc0((gulong)sizeof(GdkEvent)); event->type = GDK_KEY_PRESS; # endif event->window = gui.drawarea->window; event->send_event = TRUE; event->time = GDK_CURRENT_TIME; event->state = state; event->keyval = keyval; event->hardware_keycode = /* needed for XIM */ XKeysymToKeycode(GDK_WINDOW_XDISPLAY(event->window), (KeySym)keyval); event->length = 0; event->string = NULL; gtk_im_context_filter_keypress(xic, event); /* For consistency, also send the corresponding release event. */ event->type = GDK_KEY_RELEASE; event->send_event = FALSE; gtk_im_context_filter_keypress(xic, event); # ifdef HAVE_GTK_MULTIHEAD gdk_event_free((GdkEvent *)event); # else g_free(event); # endif } void xim_reset(void) { if (xic != NULL) { /* * The third-party imhangul module (and maybe others too) ignores * gtk_im_context_reset() or at least doesn't reset the active state. * Thus sending imactivatekey would turn it off if it was on before, * which is clearly not what we want. Fortunately we can work around * that for imhangul by sending GDK_Escape, but I don't know if it * works with all IM modules that support an activation key :/ * * An alternative approach would be to destroy the IM context and * recreate it. But that means loading/unloading the IM module on * every mode switch, which causes a quite noticeable delay even on * my rather fast box... * * * Moreover, there are some XIM which cannot respond to * im_synthesize_keypress(). we hope that they reset by * xim_shutdown(). */ if (im_activatekey_keyval != GDK_VoidSymbol && im_is_active) im_synthesize_keypress(GDK_Escape, 0U); gtk_im_context_reset(xic); /* * HACK for Ami: This sequence of function calls makes Ami handle * the IM reset graciously, without breaking loads of other stuff. * It seems to force English mode as well, which is exactly what we * want because it makes the Ami status display work reliably. */ gtk_im_context_set_use_preedit(xic, FALSE); if (p_imdisable) im_shutdown(); else { gtk_im_context_set_use_preedit(xic, TRUE); xim_set_focus(gui.in_focus); if (im_activatekey_keyval != GDK_VoidSymbol) { if (im_is_active) { g_signal_handler_block(xic, im_commit_handler_id); im_synthesize_keypress(im_activatekey_keyval, im_activatekey_state); g_signal_handler_unblock(xic, im_commit_handler_id); } } else { im_shutdown(); xim_init(); xim_set_focus(gui.in_focus); } } } preedit_start_col = MAXCOL; xim_has_preediting = FALSE; } int xim_queue_key_press_event(GdkEventKey *event, int down) { if (down) { /* * Workaround GTK2 XIM 'feature' that always converts keypad keys to * chars., even when not part of an IM sequence (ref. feature of * gdk/gdkkeyuni.c). * Flag any keypad keys that might represent a single char. * If this (on its own - i.e., not part of an IM sequence) is * committed while we're processing one of these keys, we can ignore * that commit and go ahead & process it ourselves. That way we can * still distinguish keypad keys for use in mappings. * Also add GDK_space to make <S-Space> work. */ switch (event->keyval) { case GDK_KP_Add: xim_expected_char = '+'; break; case GDK_KP_Subtract: xim_expected_char = '-'; break; case GDK_KP_Divide: xim_expected_char = '/'; break; case GDK_KP_Multiply: xim_expected_char = '*'; break; case GDK_KP_Decimal: xim_expected_char = '.'; break; case GDK_KP_Equal: xim_expected_char = '='; break; case GDK_KP_0: xim_expected_char = '0'; break; case GDK_KP_1: xim_expected_char = '1'; break; case GDK_KP_2: xim_expected_char = '2'; break; case GDK_KP_3: xim_expected_char = '3'; break; case GDK_KP_4: xim_expected_char = '4'; break; case GDK_KP_5: xim_expected_char = '5'; break; case GDK_KP_6: xim_expected_char = '6'; break; case GDK_KP_7: xim_expected_char = '7'; break; case GDK_KP_8: xim_expected_char = '8'; break; case GDK_KP_9: xim_expected_char = '9'; break; case GDK_space: xim_expected_char = ' '; break; default: xim_expected_char = NUL; } xim_ignored_char = FALSE; } /* * When typing fFtT, XIM may be activated. Thus it must pass * gtk_im_context_filter_keypress() in Normal mode. * And while doing :sh too. */ if (xic != NULL && !p_imdisable && (State & (INSERT | CMDLINE | NORMAL | EXTERNCMD)) != 0) { /* * Filter 'imactivatekey' and map it to CTRL-^. This way, Vim is * always aware of the current status of IM, and can even emulate * the activation key for modules that don't support one. */ if (event->keyval == im_activatekey_keyval && (event->state & im_activatekey_state) == im_activatekey_state) { unsigned int state_mask; /* Require the state of the 3 most used modifiers to match exactly. * Otherwise e.g. <S-C-space> would be unusable for other purposes * if the IM activate key is <S-space>. */ state_mask = im_activatekey_state; state_mask |= ((int)GDK_SHIFT_MASK | (int)GDK_CONTROL_MASK | (int)GDK_MOD1_MASK); if ((event->state & state_mask) != im_activatekey_state) return FALSE; /* Don't send it a second time on GDK_KEY_RELEASE. */ if (event->type != GDK_KEY_PRESS) return TRUE; if (map_to_exists_mode((char_u *)"", LANGMAP, FALSE)) { im_set_active(FALSE); /* ":lmap" mappings exists, toggle use of mappings. */ State ^= LANGMAP; if (State & LANGMAP) { curbuf->b_p_iminsert = B_IMODE_NONE; State &= ~LANGMAP; } else { curbuf->b_p_iminsert = B_IMODE_LMAP; State |= LANGMAP; } return TRUE; } return gtk_im_context_filter_keypress(xic, event); } /* Don't filter events through the IM context if IM isn't active * right now. Unlike with GTK+ 1.2 we cannot rely on the IM module * not doing anything before the activation key was sent. */ if (im_activatekey_keyval == GDK_VoidSymbol || im_is_active) { int imresult = gtk_im_context_filter_keypress(xic, event); /* Some XIM send following sequence: * 1. preedited string. * 2. committed string. * 3. line changed key. * 4. preedited string. * 5. remove preedited string. * if 3, Vim can't move back the above line for 5. * thus, this part should not parse the key. */ if (!imresult && preedit_start_col != MAXCOL && event->keyval == GDK_Return) { im_synthesize_keypress(GDK_Return, 0U); return FALSE; } /* If XIM tried to commit a keypad key as a single char., * ignore it so we can use the keypad key 'raw', for mappings. */ if (xim_expected_char != NUL && xim_ignored_char) /* We had a keypad key, and XIM tried to thieve it */ return FALSE; /* This is supposed to fix a problem with iBus, that space * characters don't work in input mode. */ xim_expected_char = NUL; /* Normal processing */ return imresult; } } return FALSE; } int im_get_status(void) { return im_is_active; } int preedit_get_status(void) { return preedit_is_active; } int im_is_preediting() { return xim_has_preediting; } # else /* !FEAT_GUI_GTK */ static int xim_is_active = FALSE; /* XIM should be active in the current mode */ static int xim_has_focus = FALSE; /* XIM is really being used for Vim */ #ifdef FEAT_GUI_X11 static XIMStyle input_style; static int status_area_enabled = TRUE; #endif /* * Switch using XIM on/off. This is used by the code that changes "State". */ void im_set_active(active) int active; { if (xic == NULL) return; /* If 'imdisable' is set, XIM is never active. */ if (p_imdisable) active = FALSE; #if !defined(FEAT_GUI_GTK) else if (input_style & XIMPreeditPosition) /* There is a problem in switching XIM off when preediting is used, * and it is not clear how this can be solved. For now, keep XIM on * all the time, like it was done in Vim 5.8. */ active = TRUE; #endif /* Remember the active state, it is needed when Vim gets keyboard focus. */ xim_is_active = active; xim_set_preedit(); } /* * Adjust using XIM for gaining or losing keyboard focus. Also called when * "xim_is_active" changes. */ void xim_set_focus(focus) int focus; { if (xic == NULL) return; /* * XIM only gets focus when the Vim window has keyboard focus and XIM has * been set active for the current mode. */ if (focus && xim_is_active) { if (!xim_has_focus) { xim_has_focus = TRUE; XSetICFocus(xic); } } else { if (xim_has_focus) { xim_has_focus = FALSE; XUnsetICFocus(xic); } } } void im_set_position(row, col) int row UNUSED; int col UNUSED; { xim_set_preedit(); } /* * Set the XIM to the current cursor position. */ void xim_set_preedit() { XVaNestedList attr_list; XRectangle spot_area; XPoint over_spot; int line_space; if (xic == NULL) return; xim_set_focus(TRUE); if (!xim_has_focus) { /* hide XIM cursor */ over_spot.x = 0; over_spot.y = -100; /* arbitrary invisible position */ attr_list = (XVaNestedList) XVaCreateNestedList(0, XNSpotLocation, &over_spot, NULL); XSetICValues(xic, XNPreeditAttributes, attr_list, NULL); XFree(attr_list); return; } if (input_style & XIMPreeditPosition) { if (xim_fg_color == INVALCOLOR) { xim_fg_color = gui.def_norm_pixel; xim_bg_color = gui.def_back_pixel; } over_spot.x = TEXT_X(gui.col); over_spot.y = TEXT_Y(gui.row); spot_area.x = 0; spot_area.y = 0; spot_area.height = gui.char_height * Rows; spot_area.width = gui.char_width * Columns; line_space = gui.char_height; attr_list = (XVaNestedList) XVaCreateNestedList(0, XNSpotLocation, &over_spot, XNForeground, (Pixel) xim_fg_color, XNBackground, (Pixel) xim_bg_color, XNArea, &spot_area, XNLineSpace, line_space, NULL); if (XSetICValues(xic, XNPreeditAttributes, attr_list, NULL)) EMSG(_("E284: Cannot set IC values")); XFree(attr_list); } } #if defined(FEAT_GUI_X11) static char e_xim[] = N_("E285: Failed to create input context"); #endif #if defined(FEAT_GUI_X11) || defined(PROTO) # if defined(XtSpecificationRelease) && XtSpecificationRelease >= 6 && !defined(sun) # define USE_X11R6_XIM # endif static int xim_real_init __ARGS((Window x11_window, Display *x11_display)); #ifdef USE_X11R6_XIM static void xim_instantiate_cb __ARGS((Display *display, XPointer client_data, XPointer call_data)); static void xim_destroy_cb __ARGS((XIM im, XPointer client_data, XPointer call_data)); static void xim_instantiate_cb(display, client_data, call_data) Display *display; XPointer client_data UNUSED; XPointer call_data UNUSED; { Window x11_window; Display *x11_display; #ifdef XIM_DEBUG xim_log("xim_instantiate_cb()\n"); #endif gui_get_x11_windis(&x11_window, &x11_display); if (display != x11_display) return; xim_real_init(x11_window, x11_display); gui_set_shellsize(FALSE, FALSE, RESIZE_BOTH); if (xic != NULL) XUnregisterIMInstantiateCallback(x11_display, NULL, NULL, NULL, xim_instantiate_cb, NULL); } static void xim_destroy_cb(im, client_data, call_data) XIM im UNUSED; XPointer client_data UNUSED; XPointer call_data UNUSED; { Window x11_window; Display *x11_display; #ifdef XIM_DEBUG xim_log("xim_destroy_cb()\n"); #endif gui_get_x11_windis(&x11_window, &x11_display); xic = NULL; status_area_enabled = FALSE; gui_set_shellsize(FALSE, FALSE, RESIZE_BOTH); XRegisterIMInstantiateCallback(x11_display, NULL, NULL, NULL, xim_instantiate_cb, NULL); } #endif void xim_init() { Window x11_window; Display *x11_display; #ifdef XIM_DEBUG xim_log("xim_init()\n"); #endif gui_get_x11_windis(&x11_window, &x11_display); xic = NULL; if (xim_real_init(x11_window, x11_display)) return; gui_set_shellsize(FALSE, FALSE, RESIZE_BOTH); #ifdef USE_X11R6_XIM XRegisterIMInstantiateCallback(x11_display, NULL, NULL, NULL, xim_instantiate_cb, NULL); #endif } static int xim_real_init(x11_window, x11_display) Window x11_window; Display *x11_display; { int i; char *p, *s, *ns, *end, tmp[1024]; #define IMLEN_MAX 40 char buf[IMLEN_MAX + 7]; XIM xim = NULL; XIMStyles *xim_styles; XIMStyle this_input_style = 0; Boolean found; XPoint over_spot; XVaNestedList preedit_list, status_list; input_style = 0; status_area_enabled = FALSE; if (xic != NULL) return FALSE; if (gui.rsrc_input_method != NULL && *gui.rsrc_input_method != NUL) { strcpy(tmp, gui.rsrc_input_method); for (ns = s = tmp; ns != NULL && *s != NUL;) { s = (char *)skipwhite((char_u *)s); if (*s == NUL) break; if ((ns = end = strchr(s, ',')) == NULL) end = s + strlen(s); while (isspace(((char_u *)end)[-1])) end--; *end = NUL; if (strlen(s) <= IMLEN_MAX) { strcpy(buf, "@im="); strcat(buf, s); if ((p = XSetLocaleModifiers(buf)) != NULL && *p != NUL && (xim = XOpenIM(x11_display, NULL, NULL, NULL)) != NULL) break; } s = ns + 1; } } if (xim == NULL && (p = XSetLocaleModifiers("")) != NULL && *p != NUL) xim = XOpenIM(x11_display, NULL, NULL, NULL); /* This is supposed to be useful to obtain characters through * XmbLookupString() without really using a XIM. */ if (xim == NULL && (p = XSetLocaleModifiers("@im=none")) != NULL && *p != NUL) xim = XOpenIM(x11_display, NULL, NULL, NULL); if (xim == NULL) { /* Only give this message when verbose is set, because too many people * got this message when they didn't want to use a XIM. */ if (p_verbose > 0) { verbose_enter(); EMSG(_("E286: Failed to open input method")); verbose_leave(); } return FALSE; } #ifdef USE_X11R6_XIM { XIMCallback destroy_cb; destroy_cb.callback = xim_destroy_cb; destroy_cb.client_data = NULL; if (XSetIMValues(xim, XNDestroyCallback, &destroy_cb, NULL)) EMSG(_("E287: Warning: Could not set destroy callback to IM")); } #endif if (XGetIMValues(xim, XNQueryInputStyle, &xim_styles, NULL) || !xim_styles) { EMSG(_("E288: input method doesn't support any style")); XCloseIM(xim); return FALSE; } found = False; strcpy(tmp, gui.rsrc_preedit_type_name); for (s = tmp; s && !found; ) { while (*s && isspace((unsigned char)*s)) s++; if (!*s) break; if ((ns = end = strchr(s, ',')) != 0) ns++; else end = s + strlen(s); while (isspace((unsigned char)*end)) end--; *end = '\0'; if (!strcmp(s, "OverTheSpot")) this_input_style = (XIMPreeditPosition | XIMStatusArea); else if (!strcmp(s, "OffTheSpot")) this_input_style = (XIMPreeditArea | XIMStatusArea); else if (!strcmp(s, "Root")) this_input_style = (XIMPreeditNothing | XIMStatusNothing); for (i = 0; (unsigned short)i < xim_styles->count_styles; i++) { if (this_input_style == xim_styles->supported_styles[i]) { found = True; break; } } if (!found) for (i = 0; (unsigned short)i < xim_styles->count_styles; i++) { if ((xim_styles->supported_styles[i] & this_input_style) == (this_input_style & ~XIMStatusArea)) { this_input_style &= ~XIMStatusArea; found = True; break; } } s = ns; } XFree(xim_styles); if (!found) { /* Only give this message when verbose is set, because too many people * got this message when they didn't want to use a XIM. */ if (p_verbose > 0) { verbose_enter(); EMSG(_("E289: input method doesn't support my preedit type")); verbose_leave(); } XCloseIM(xim); return FALSE; } over_spot.x = TEXT_X(gui.col); over_spot.y = TEXT_Y(gui.row); input_style = this_input_style; /* A crash was reported when trying to pass gui.norm_font as XNFontSet, * thus that has been removed. Hopefully the default works... */ #ifdef FEAT_XFONTSET if (gui.fontset != NOFONTSET) { preedit_list = XVaCreateNestedList(0, XNSpotLocation, &over_spot, XNForeground, (Pixel)gui.def_norm_pixel, XNBackground, (Pixel)gui.def_back_pixel, XNFontSet, (XFontSet)gui.fontset, NULL); status_list = XVaCreateNestedList(0, XNForeground, (Pixel)gui.def_norm_pixel, XNBackground, (Pixel)gui.def_back_pixel, XNFontSet, (XFontSet)gui.fontset, NULL); } else #endif { preedit_list = XVaCreateNestedList(0, XNSpotLocation, &over_spot, XNForeground, (Pixel)gui.def_norm_pixel, XNBackground, (Pixel)gui.def_back_pixel, NULL); status_list = XVaCreateNestedList(0, XNForeground, (Pixel)gui.def_norm_pixel, XNBackground, (Pixel)gui.def_back_pixel, NULL); } xic = XCreateIC(xim, XNInputStyle, input_style, XNClientWindow, x11_window, XNFocusWindow, gui.wid, XNPreeditAttributes, preedit_list, XNStatusAttributes, status_list, NULL); XFree(status_list); XFree(preedit_list); if (xic != NULL) { if (input_style & XIMStatusArea) { xim_set_status_area(); status_area_enabled = TRUE; } else gui_set_shellsize(FALSE, FALSE, RESIZE_BOTH); } else { EMSG(_(e_xim)); XCloseIM(xim); return FALSE; } return TRUE; } #endif /* FEAT_GUI_X11 */ /* * Get IM status. When IM is on, return TRUE. Else return FALSE. * FIXME: This doesn't work correctly: Having focus doesn't always mean XIM is * active, when not having focus XIM may still be active (e.g., when using a * tear-off menu item). */ int im_get_status() { return xim_has_focus; } # endif /* !FEAT_GUI_GTK */ # if !defined(FEAT_GUI_GTK) || defined(PROTO) /* * Set up the status area. * * This should use a separate Widget, but that seems not possible, because * preedit_area and status_area should be set to the same window as for the * text input. Unfortunately this means the status area pollutes the text * window... */ void xim_set_status_area() { XVaNestedList preedit_list = 0, status_list = 0, list = 0; XRectangle pre_area, status_area; if (xic == NULL) return; if (input_style & XIMStatusArea) { if (input_style & XIMPreeditArea) { XRectangle *needed_rect; /* to get status_area width */ status_list = XVaCreateNestedList(0, XNAreaNeeded, &needed_rect, NULL); XGetICValues(xic, XNStatusAttributes, status_list, NULL); XFree(status_list); status_area.width = needed_rect->width; } else status_area.width = gui.char_width * Columns; status_area.x = 0; status_area.y = gui.char_height * Rows + gui.border_offset; if (gui.which_scrollbars[SBAR_BOTTOM]) status_area.y += gui.scrollbar_height; #ifdef FEAT_MENU if (gui.menu_is_active) status_area.y += gui.menu_height; #endif status_area.height = gui.char_height; status_list = XVaCreateNestedList(0, XNArea, &status_area, NULL); } else { status_area.x = 0; status_area.y = gui.char_height * Rows + gui.border_offset; if (gui.which_scrollbars[SBAR_BOTTOM]) status_area.y += gui.scrollbar_height; #ifdef FEAT_MENU if (gui.menu_is_active) status_area.y += gui.menu_height; #endif status_area.width = 0; status_area.height = gui.char_height; } if (input_style & XIMPreeditArea) /* off-the-spot */ { pre_area.x = status_area.x + status_area.width; pre_area.y = gui.char_height * Rows + gui.border_offset; pre_area.width = gui.char_width * Columns - pre_area.x; if (gui.which_scrollbars[SBAR_BOTTOM]) pre_area.y += gui.scrollbar_height; #ifdef FEAT_MENU if (gui.menu_is_active) pre_area.y += gui.menu_height; #endif pre_area.height = gui.char_height; preedit_list = XVaCreateNestedList(0, XNArea, &pre_area, NULL); } else if (input_style & XIMPreeditPosition) /* over-the-spot */ { pre_area.x = 0; pre_area.y = 0; pre_area.height = gui.char_height * Rows; pre_area.width = gui.char_width * Columns; preedit_list = XVaCreateNestedList(0, XNArea, &pre_area, NULL); } if (preedit_list && status_list) list = XVaCreateNestedList(0, XNPreeditAttributes, preedit_list, XNStatusAttributes, status_list, NULL); else if (preedit_list) list = XVaCreateNestedList(0, XNPreeditAttributes, preedit_list, NULL); else if (status_list) list = XVaCreateNestedList(0, XNStatusAttributes, status_list, NULL); else list = NULL; if (list) { XSetICValues(xic, XNVaNestedList, list, NULL); XFree(list); } if (status_list) XFree(status_list); if (preedit_list) XFree(preedit_list); } int xim_get_status_area_height() { if (status_area_enabled) return gui.char_height; return 0; } # endif #endif /* FEAT_XIM */ #if defined(FEAT_MBYTE) || defined(PROTO) /* * Setup "vcp" for conversion from "from" to "to". * The names must have been made canonical with enc_canonize(). * vcp->vc_type must have been initialized to CONV_NONE. * Note: cannot be used for conversion from/to ucs-2 and ucs-4 (will use utf-8 * instead). * Afterwards invoke with "from" and "to" equal to NULL to cleanup. * Return FAIL when conversion is not supported, OK otherwise. */ int convert_setup(vcp, from, to) vimconv_T *vcp; char_u *from; char_u *to; { return convert_setup_ext(vcp, from, TRUE, to, TRUE); } /* * As convert_setup(), but only when from_unicode_is_utf8 is TRUE will all * "from" unicode charsets be considered utf-8. Same for "to". */ int convert_setup_ext(vcp, from, from_unicode_is_utf8, to, to_unicode_is_utf8) vimconv_T *vcp; char_u *from; int from_unicode_is_utf8; char_u *to; int to_unicode_is_utf8; { int from_prop; int to_prop; int from_is_utf8; int to_is_utf8; /* Reset to no conversion. */ # ifdef USE_ICONV if (vcp->vc_type == CONV_ICONV && vcp->vc_fd != (iconv_t)-1) iconv_close(vcp->vc_fd); # endif vcp->vc_type = CONV_NONE; vcp->vc_factor = 1; vcp->vc_fail = FALSE; /* No conversion when one of the names is empty or they are equal. */ if (from == NULL || *from == NUL || to == NULL || *to == NUL || STRCMP(from, to) == 0) return OK; from_prop = enc_canon_props(from); to_prop = enc_canon_props(to); if (from_unicode_is_utf8) from_is_utf8 = from_prop & ENC_UNICODE; else from_is_utf8 = from_prop == ENC_UNICODE; if (to_unicode_is_utf8) to_is_utf8 = to_prop & ENC_UNICODE; else to_is_utf8 = to_prop == ENC_UNICODE; if ((from_prop & ENC_LATIN1) && to_is_utf8) { /* Internal latin1 -> utf-8 conversion. */ vcp->vc_type = CONV_TO_UTF8; vcp->vc_factor = 2; /* up to twice as long */ } else if ((from_prop & ENC_LATIN9) && to_is_utf8) { /* Internal latin9 -> utf-8 conversion. */ vcp->vc_type = CONV_9_TO_UTF8; vcp->vc_factor = 3; /* up to three as long (euro sign) */ } else if (from_is_utf8 && (to_prop & ENC_LATIN1)) { /* Internal utf-8 -> latin1 conversion. */ vcp->vc_type = CONV_TO_LATIN1; } else if (from_is_utf8 && (to_prop & ENC_LATIN9)) { /* Internal utf-8 -> latin9 conversion. */ vcp->vc_type = CONV_TO_LATIN9; } #ifdef WIN3264 /* Win32-specific codepage <-> codepage conversion without iconv. */ else if ((from_is_utf8 || encname2codepage(from) > 0) && (to_is_utf8 || encname2codepage(to) > 0)) { vcp->vc_type = CONV_CODEPAGE; vcp->vc_factor = 2; /* up to twice as long */ vcp->vc_cpfrom = from_is_utf8 ? 0 : encname2codepage(from); vcp->vc_cpto = to_is_utf8 ? 0 : encname2codepage(to); } #endif #ifdef MACOS_X else if ((from_prop & ENC_MACROMAN) && (to_prop & ENC_LATIN1)) { vcp->vc_type = CONV_MAC_LATIN1; } else if ((from_prop & ENC_MACROMAN) && to_is_utf8) { vcp->vc_type = CONV_MAC_UTF8; vcp->vc_factor = 2; /* up to twice as long */ } else if ((from_prop & ENC_LATIN1) && (to_prop & ENC_MACROMAN)) { vcp->vc_type = CONV_LATIN1_MAC; } else if (from_is_utf8 && (to_prop & ENC_MACROMAN)) { vcp->vc_type = CONV_UTF8_MAC; } #endif # ifdef USE_ICONV else { /* Use iconv() for conversion. */ vcp->vc_fd = (iconv_t)my_iconv_open( to_is_utf8 ? (char_u *)"utf-8" : to, from_is_utf8 ? (char_u *)"utf-8" : from); if (vcp->vc_fd != (iconv_t)-1) { vcp->vc_type = CONV_ICONV; vcp->vc_factor = 4; /* could be longer too... */ } } # endif if (vcp->vc_type == CONV_NONE) return FAIL; return OK; } #if defined(FEAT_GUI) || defined(AMIGA) || defined(WIN3264) \ || defined(MSDOS) || defined(PROTO) /* * Do conversion on typed input characters in-place. * The input and output are not NUL terminated! * Returns the length after conversion. */ int convert_input(ptr, len, maxlen) char_u *ptr; int len; int maxlen; { return convert_input_safe(ptr, len, maxlen, NULL, NULL); } #endif /* * Like convert_input(), but when there is an incomplete byte sequence at the * end return that as an allocated string in "restp" and set "*restlenp" to * the length. If "restp" is NULL it is not used. */ int convert_input_safe(ptr, len, maxlen, restp, restlenp) char_u *ptr; int len; int maxlen; char_u **restp; int *restlenp; { char_u *d; int dlen = len; int unconvertlen = 0; d = string_convert_ext(&input_conv, ptr, &dlen, restp == NULL ? NULL : &unconvertlen); if (d != NULL) { if (dlen <= maxlen) { if (unconvertlen > 0) { /* Move the unconverted characters to allocated memory. */ *restp = alloc(unconvertlen); if (*restp != NULL) mch_memmove(*restp, ptr + len - unconvertlen, unconvertlen); *restlenp = unconvertlen; } mch_memmove(ptr, d, dlen); } else /* result is too long, keep the unconverted text (the caller must * have done something wrong!) */ dlen = len; vim_free(d); } return dlen; } /* * Convert text "ptr[*lenp]" according to "vcp". * Returns the result in allocated memory and sets "*lenp". * When "lenp" is NULL, use NUL terminated strings. * Illegal chars are often changed to "?", unless vcp->vc_fail is set. * When something goes wrong, NULL is returned and "*lenp" is unchanged. */ char_u * string_convert(vcp, ptr, lenp) vimconv_T *vcp; char_u *ptr; int *lenp; { return string_convert_ext(vcp, ptr, lenp, NULL); } /* * Like string_convert(), but when "unconvlenp" is not NULL and there are is * an incomplete sequence at the end it is not converted and "*unconvlenp" is * set to the number of remaining bytes. */ char_u * string_convert_ext(vcp, ptr, lenp, unconvlenp) vimconv_T *vcp; char_u *ptr; int *lenp; int *unconvlenp; { char_u *retval = NULL; char_u *d; int len; int i; int l; int c; if (lenp == NULL) len = (int)STRLEN(ptr); else len = *lenp; if (len == 0) return vim_strsave((char_u *)""); switch (vcp->vc_type) { case CONV_TO_UTF8: /* latin1 to utf-8 conversion */ retval = alloc(len * 2 + 1); if (retval == NULL) break; d = retval; for (i = 0; i < len; ++i) { c = ptr[i]; if (c < 0x80) *d++ = c; else { *d++ = 0xc0 + ((unsigned)c >> 6); *d++ = 0x80 + (c & 0x3f); } } *d = NUL; if (lenp != NULL) *lenp = (int)(d - retval); break; case CONV_9_TO_UTF8: /* latin9 to utf-8 conversion */ retval = alloc(len * 3 + 1); if (retval == NULL) break; d = retval; for (i = 0; i < len; ++i) { c = ptr[i]; switch (c) { case 0xa4: c = 0x20ac; break; /* euro */ case 0xa6: c = 0x0160; break; /* S hat */ case 0xa8: c = 0x0161; break; /* S -hat */ case 0xb4: c = 0x017d; break; /* Z hat */ case 0xb8: c = 0x017e; break; /* Z -hat */ case 0xbc: c = 0x0152; break; /* OE */ case 0xbd: c = 0x0153; break; /* oe */ case 0xbe: c = 0x0178; break; /* Y */ } d += utf_char2bytes(c, d); } *d = NUL; if (lenp != NULL) *lenp = (int)(d - retval); break; case CONV_TO_LATIN1: /* utf-8 to latin1 conversion */ case CONV_TO_LATIN9: /* utf-8 to latin9 conversion */ retval = alloc(len + 1); if (retval == NULL) break; d = retval; for (i = 0; i < len; ++i) { l = utf_ptr2len_len(ptr + i, len - i); if (l == 0) *d++ = NUL; else if (l == 1) { int l_w = utf8len_tab_zero[ptr[i]]; if (l_w == 0) { /* Illegal utf-8 byte cannot be converted */ vim_free(retval); return NULL; } if (unconvlenp != NULL && l_w > len - i) { /* Incomplete sequence at the end. */ *unconvlenp = len - i; break; } *d++ = ptr[i]; } else { c = utf_ptr2char(ptr + i); if (vcp->vc_type == CONV_TO_LATIN9) switch (c) { case 0x20ac: c = 0xa4; break; /* euro */ case 0x0160: c = 0xa6; break; /* S hat */ case 0x0161: c = 0xa8; break; /* S -hat */ case 0x017d: c = 0xb4; break; /* Z hat */ case 0x017e: c = 0xb8; break; /* Z -hat */ case 0x0152: c = 0xbc; break; /* OE */ case 0x0153: c = 0xbd; break; /* oe */ case 0x0178: c = 0xbe; break; /* Y */ case 0xa4: case 0xa6: case 0xa8: case 0xb4: case 0xb8: case 0xbc: case 0xbd: case 0xbe: c = 0x100; break; /* not in latin9 */ } if (!utf_iscomposing(c)) /* skip composing chars */ { if (c < 0x100) *d++ = c; else if (vcp->vc_fail) { vim_free(retval); return NULL; } else { *d++ = 0xbf; if (utf_char2cells(c) > 1) *d++ = '?'; } } i += l - 1; } } *d = NUL; if (lenp != NULL) *lenp = (int)(d - retval); break; # ifdef MACOS_CONVERT case CONV_MAC_LATIN1: retval = mac_string_convert(ptr, len, lenp, vcp->vc_fail, 'm', 'l', unconvlenp); break; case CONV_LATIN1_MAC: retval = mac_string_convert(ptr, len, lenp, vcp->vc_fail, 'l', 'm', unconvlenp); break; case CONV_MAC_UTF8: retval = mac_string_convert(ptr, len, lenp, vcp->vc_fail, 'm', 'u', unconvlenp); break; case CONV_UTF8_MAC: retval = mac_string_convert(ptr, len, lenp, vcp->vc_fail, 'u', 'm', unconvlenp); break; # endif # ifdef USE_ICONV case CONV_ICONV: /* conversion with output_conv.vc_fd */ retval = iconv_string(vcp, ptr, len, unconvlenp, lenp); break; # endif # ifdef WIN3264 case CONV_CODEPAGE: /* codepage -> codepage */ { int retlen; int tmp_len; short_u *tmp; /* 1. codepage/UTF-8 -> ucs-2. */ if (vcp->vc_cpfrom == 0) tmp_len = utf8_to_utf16(ptr, len, NULL, NULL); else tmp_len = MultiByteToWideChar(vcp->vc_cpfrom, 0, ptr, len, 0, 0); tmp = (short_u *)alloc(sizeof(short_u) * tmp_len); if (tmp == NULL) break; if (vcp->vc_cpfrom == 0) utf8_to_utf16(ptr, len, tmp, unconvlenp); else MultiByteToWideChar(vcp->vc_cpfrom, 0, ptr, len, tmp, tmp_len); /* 2. ucs-2 -> codepage/UTF-8. */ if (vcp->vc_cpto == 0) retlen = utf16_to_utf8(tmp, tmp_len, NULL); else retlen = WideCharToMultiByte(vcp->vc_cpto, 0, tmp, tmp_len, 0, 0, 0, 0); retval = alloc(retlen + 1); if (retval != NULL) { if (vcp->vc_cpto == 0) utf16_to_utf8(tmp, tmp_len, retval); else WideCharToMultiByte(vcp->vc_cpto, 0, tmp, tmp_len, retval, retlen, 0, 0); retval[retlen] = NUL; if (lenp != NULL) *lenp = retlen; } vim_free(tmp); break; } # endif } return retval; } #endif
zyz2011-vim
src/mbyte.c
C
gpl2
151,516
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. */ /* * definition of global variables */ /* * Number of Rows and Columns in the screen. * Must be long to be able to use them as options in option.c. * Note: Use screen_Rows and screen_Columns to access items in ScreenLines[]. * They may have different values when the screen wasn't (re)allocated yet * after setting Rows or Columns (e.g., when starting up). */ EXTERN long Rows /* nr of rows in the screen */ #ifdef DO_INIT # if defined(MSDOS) || defined(WIN3264) || defined(OS2) = 25L # else = 24L # endif #endif ; EXTERN long Columns INIT(= 80); /* nr of columns in the screen */ /* * The characters that are currently on the screen are kept in ScreenLines[]. * It is a single block of characters, the size of the screen plus one line. * The attributes for those characters are kept in ScreenAttrs[]. * * "LineOffset[n]" is the offset from ScreenLines[] for the start of line 'n'. * The same value is used for ScreenLinesUC[] and ScreenAttrs[]. * * Note: before the screen is initialized and when out of memory these can be * NULL. */ EXTERN schar_T *ScreenLines INIT(= NULL); EXTERN sattr_T *ScreenAttrs INIT(= NULL); EXTERN unsigned *LineOffset INIT(= NULL); EXTERN char_u *LineWraps INIT(= NULL); /* line wraps to next line */ #ifdef FEAT_MBYTE /* * When using Unicode characters (in UTF-8 encoding) the character in * ScreenLinesUC[] contains the Unicode for the character at this position, or * NUL when the character in ScreenLines[] is to be used (ASCII char). * The composing characters are to be drawn on top of the original character. * ScreenLinesC[0][off] is only to be used when ScreenLinesUC[off] != 0. * Note: These three are only allocated when enc_utf8 is set! */ EXTERN u8char_T *ScreenLinesUC INIT(= NULL); /* decoded UTF-8 characters */ EXTERN u8char_T *ScreenLinesC[MAX_MCO]; /* composing characters */ EXTERN int Screen_mco INIT(= 0); /* value of p_mco used when allocating ScreenLinesC[] */ /* Only used for euc-jp: Second byte of a character that starts with 0x8e. * These are single-width. */ EXTERN schar_T *ScreenLines2 INIT(= NULL); #endif #ifdef FEAT_WINDOWS /* * Indexes for tab page line: * N > 0 for label of tab page N * N == 0 for no label * N < 0 for closing tab page -N * N == -999 for closing current tab page */ EXTERN short *TabPageIdxs INIT(= NULL); #endif EXTERN int screen_Rows INIT(= 0); /* actual size of ScreenLines[] */ EXTERN int screen_Columns INIT(= 0); /* actual size of ScreenLines[] */ /* * When vgetc() is called, it sets mod_mask to the set of modifiers that are * held down based on the MOD_MASK_* symbols that are read first. */ EXTERN int mod_mask INIT(= 0x0); /* current key modifiers */ /* * Cmdline_row is the row where the command line starts, just below the * last window. * When the cmdline gets longer than the available space the screen gets * scrolled up. After a CTRL-D (show matches), after hitting ':' after * "hit return", and for the :global command, the command line is * temporarily moved. The old position is restored with the next call to * update_screen(). */ EXTERN int cmdline_row; EXTERN int redraw_cmdline INIT(= FALSE); /* cmdline must be redrawn */ EXTERN int clear_cmdline INIT(= FALSE); /* cmdline must be cleared */ EXTERN int mode_displayed INIT(= FALSE); /* mode is being displayed */ #if defined(FEAT_CRYPT) || defined(FEAT_EVAL) EXTERN int cmdline_star INIT(= FALSE); /* cmdline is crypted */ #endif EXTERN int exec_from_reg INIT(= FALSE); /* executing register */ EXTERN int screen_cleared INIT(= FALSE); /* screen has been cleared */ #ifdef FEAT_CRYPT EXTERN int use_crypt_method INIT(= 0); #endif /* * When '$' is included in 'cpoptions' option set: * When a change command is given that deletes only part of a line, a dollar * is put at the end of the changed text. dollar_vcol is set to the virtual * column of this '$'. -1 is used to indicate no $ is being displayed. */ EXTERN colnr_T dollar_vcol INIT(= -1); #ifdef FEAT_INS_EXPAND /* * Variables for Insert mode completion. */ /* Length in bytes of the text being completed (this is deleted to be replaced * by the match.) */ EXTERN int compl_length INIT(= 0); /* Set when character typed while looking for matches and it means we should * stop looking for matches. */ EXTERN int compl_interrupted INIT(= FALSE); /* List of flags for method of completion. */ EXTERN int compl_cont_status INIT(= 0); # define CONT_ADDING 1 /* "normal" or "adding" expansion */ # define CONT_INTRPT (2 + 4) /* a ^X interrupted the current expansion */ /* it's set only iff N_ADDS is set */ # define CONT_N_ADDS 4 /* next ^X<> will add-new or expand-current */ # define CONT_S_IPOS 8 /* next ^X<> will set initial_pos? * if so, word-wise-expansion will set SOL */ # define CONT_SOL 16 /* pattern includes start of line, just for * word-wise expansion, not set for ^X^L */ # define CONT_LOCAL 32 /* for ctrl_x_mode 0, ^X^P/^X^N do a local * expansion, (eg use complete=.) */ #endif /* * Functions for putting characters in the command line, * while keeping ScreenLines[] updated. */ #ifdef FEAT_RIGHTLEFT EXTERN int cmdmsg_rl INIT(= FALSE); /* cmdline is drawn right to left */ #endif EXTERN int msg_col; EXTERN int msg_row; EXTERN int msg_scrolled; /* Number of screen lines that windows have * scrolled because of printing messages. */ EXTERN int msg_scrolled_ign INIT(= FALSE); /* when TRUE don't set need_wait_return in msg_puts_attr() when msg_scrolled is non-zero */ EXTERN char_u *keep_msg INIT(= NULL); /* msg to be shown after redraw */ EXTERN int keep_msg_attr INIT(= 0); /* highlight attr for keep_msg */ EXTERN int keep_msg_more INIT(= FALSE); /* keep_msg was set by msgmore() */ EXTERN int need_fileinfo INIT(= FALSE);/* do fileinfo() after redraw */ EXTERN int msg_scroll INIT(= FALSE); /* msg_start() will scroll */ EXTERN int msg_didout INIT(= FALSE); /* msg_outstr() was used in line */ EXTERN int msg_didany INIT(= FALSE); /* msg_outstr() was used at all */ EXTERN int msg_nowait INIT(= FALSE); /* don't wait for this msg */ EXTERN int emsg_off INIT(= 0); /* don't display errors for now, unless 'debug' is set. */ EXTERN int info_message INIT(= FALSE); /* printing informative message */ EXTERN int msg_hist_off INIT(= FALSE); /* don't add messages to history */ #ifdef FEAT_EVAL EXTERN int need_clr_eos INIT(= FALSE); /* need to clear text before displaying a message. */ EXTERN int emsg_skip INIT(= 0); /* don't display errors for expression that is skipped */ EXTERN int emsg_severe INIT(= FALSE); /* use message of next of several emsg() calls for throw */ EXTERN int did_endif INIT(= FALSE); /* just had ":endif" */ #endif EXTERN int did_emsg; /* set by emsg() when the message is displayed or thrown */ EXTERN int called_emsg; /* always set by emsg() */ EXTERN int ex_exitval INIT(= 0); /* exit value for ex mode */ EXTERN int emsg_on_display INIT(= FALSE); /* there is an error message */ EXTERN int rc_did_emsg INIT(= FALSE); /* vim_regcomp() called emsg() */ EXTERN int no_wait_return INIT(= 0); /* don't wait for return for now */ EXTERN int need_wait_return INIT(= 0); /* need to wait for return later */ EXTERN int did_wait_return INIT(= FALSE); /* wait_return() was used and nothing written since then */ #ifdef FEAT_TITLE EXTERN int need_maketitle INIT(= TRUE); /* call maketitle() soon */ #endif EXTERN int quit_more INIT(= FALSE); /* 'q' hit at "--more--" msg */ #if defined(UNIX) || defined(__EMX__) || defined(VMS) || defined(MACOS_X) EXTERN int newline_on_exit INIT(= FALSE); /* did msg in altern. screen */ EXTERN int intr_char INIT(= 0); /* extra interrupt character */ #endif #if (defined(UNIX) || defined(VMS)) && defined(FEAT_X11) EXTERN int x_no_connect INIT(= FALSE); /* don't connect to X server */ # if defined(FEAT_CLIENTSERVER) EXTERN int x_force_connect INIT(= FALSE); /* Do connect to X server. Overrules x_no_connect and "exclude" in 'clipboard'. */ # endif #endif EXTERN int ex_keep_indent INIT(= FALSE); /* getexmodeline(): keep indent */ EXTERN int vgetc_busy INIT(= 0); /* when inside vgetc() then > 0 */ EXTERN int didset_vim INIT(= FALSE); /* did set $VIM ourselves */ EXTERN int didset_vimruntime INIT(= FALSE); /* idem for $VIMRUNTIME */ /* * Lines left before a "more" message. Ex mode needs to be able to reset this * after you type something. */ EXTERN int lines_left INIT(= -1); /* lines left for listing */ EXTERN int msg_no_more INIT(= FALSE); /* don't use more prompt, truncate messages */ EXTERN char_u *sourcing_name INIT( = NULL);/* name of error message source */ EXTERN linenr_T sourcing_lnum INIT(= 0); /* line number of the source file */ #ifdef FEAT_EVAL EXTERN int ex_nesting_level INIT(= 0); /* nesting level */ EXTERN int debug_break_level INIT(= -1); /* break below this level */ EXTERN int debug_did_msg INIT(= FALSE); /* did "debug mode" message */ EXTERN int debug_tick INIT(= 0); /* breakpoint change count */ # ifdef FEAT_PROFILE EXTERN int do_profiling INIT(= PROF_NONE); /* PROF_ values */ # endif /* * The exception currently being thrown. Used to pass an exception to * a different cstack. Also used for discarding an exception before it is * caught or made pending. Only valid when did_throw is TRUE. */ EXTERN except_T *current_exception; /* * did_throw: An exception is being thrown. Reset when the exception is caught * or as long as it is pending in a finally clause. */ EXTERN int did_throw INIT(= FALSE); /* * need_rethrow: set to TRUE when a throw that cannot be handled in do_cmdline() * must be propagated to the cstack of the previously called do_cmdline(). */ EXTERN int need_rethrow INIT(= FALSE); /* * check_cstack: set to TRUE when a ":finish" or ":return" that cannot be * handled in do_cmdline() must be propagated to the cstack of the previously * called do_cmdline(). */ EXTERN int check_cstack INIT(= FALSE); /* * Number of nested try conditionals (across function calls and ":source" * commands). */ EXTERN int trylevel INIT(= 0); /* * When "force_abort" is TRUE, always skip commands after an error message, * even after the outermost ":endif", ":endwhile" or ":endfor" or for a * function without the "abort" flag. It is set to TRUE when "trylevel" is * non-zero (and ":silent!" was not used) or an exception is being thrown at * the time an error is detected. It is set to FALSE when "trylevel" gets * zero again and there was no error or interrupt or throw. */ EXTERN int force_abort INIT(= FALSE); /* * "msg_list" points to a variable in the stack of do_cmdline() which keeps * the list of arguments of several emsg() calls, one of which is to be * converted to an error exception immediately after the failing command * returns. The message to be used for the exception value is pointed to by * the "throw_msg" field of the first element in the list. It is usually the * same as the "msg" field of that element, but can be identical to the "msg" * field of a later list element, when the "emsg_severe" flag was set when the * emsg() call was made. */ EXTERN struct msglist **msg_list INIT(= NULL); /* * suppress_errthrow: When TRUE, don't convert an error to an exception. Used * when displaying the interrupt message or reporting an exception that is still * uncaught at the top level (which has already been discarded then). Also used * for the error message when no exception can be thrown. */ EXTERN int suppress_errthrow INIT(= FALSE); /* * The stack of all caught and not finished exceptions. The exception on the * top of the stack is the one got by evaluation of v:exception. The complete * stack of all caught and pending exceptions is embedded in the various * cstacks; the pending exceptions, however, are not on the caught stack. */ EXTERN except_T *caught_stack INIT(= NULL); #endif #ifdef FEAT_EVAL /* * Garbage collection can only take place when we are sure there are no Lists * or Dictionaries being used internally. This is flagged with * "may_garbage_collect" when we are at the toplevel. * "want_garbage_collect" is set by the garbagecollect() function, which means * we do garbage collection before waiting for a char at the toplevel. * "garbage_collect_at_exit" indicates garbagecollect(1) was called. */ EXTERN int may_garbage_collect INIT(= FALSE); EXTERN int want_garbage_collect INIT(= FALSE); EXTERN int garbage_collect_at_exit INIT(= FALSE); /* ID of script being sourced or was sourced to define the current function. */ EXTERN scid_T current_SID INIT(= 0); #endif #if defined(FEAT_EVAL) || defined(FEAT_SYN_HL) /* Magic number used for hashitem "hi_key" value indicating a deleted item. * Only the address is used. */ EXTERN char_u hash_removed; #endif EXTERN int scroll_region INIT(= FALSE); /* term supports scroll region */ EXTERN int t_colors INIT(= 0); /* int value of T_CCO */ /* * When highlight_match is TRUE, highlight a match, starting at the cursor * position. Search_match_lines is the number of lines after the match (0 for * a match within one line), search_match_endcol the column number of the * character just after the match in the last line. */ EXTERN int highlight_match INIT(= FALSE); /* show search match pos */ EXTERN linenr_T search_match_lines; /* lines of of matched string */ EXTERN colnr_T search_match_endcol; /* col nr of match end */ EXTERN int no_smartcase INIT(= FALSE); /* don't use 'smartcase' once */ EXTERN int need_check_timestamps INIT(= FALSE); /* need to check file timestamps asap */ EXTERN int did_check_timestamps INIT(= FALSE); /* did check timestamps recently */ EXTERN int no_check_timestamps INIT(= 0); /* Don't check timestamps */ EXTERN int highlight_attr[HLF_COUNT]; /* Highl. attr for each context. */ #ifdef FEAT_STL_OPT # define USER_HIGHLIGHT #endif #ifdef USER_HIGHLIGHT EXTERN int highlight_user[9]; /* User[1-9] attributes */ # ifdef FEAT_STL_OPT EXTERN int highlight_stlnc[9]; /* On top of user */ # endif #endif #ifdef FEAT_GUI EXTERN char_u *use_gvimrc INIT(= NULL); /* "-U" cmdline argument */ #endif EXTERN int cterm_normal_fg_color INIT(= 0); EXTERN int cterm_normal_fg_bold INIT(= 0); EXTERN int cterm_normal_bg_color INIT(= 0); #ifdef FEAT_AUTOCMD EXTERN int autocmd_busy INIT(= FALSE); /* Is apply_autocmds() busy? */ EXTERN int autocmd_no_enter INIT(= FALSE); /* *Enter autocmds disabled */ EXTERN int autocmd_no_leave INIT(= FALSE); /* *Leave autocmds disabled */ EXTERN int modified_was_set; /* did ":set modified" */ EXTERN int did_filetype INIT(= FALSE); /* FileType event found */ EXTERN int keep_filetype INIT(= FALSE); /* value for did_filetype when starting to execute autocommands */ /* When deleting the current buffer, another one must be loaded. If we know * which one is preferred, au_new_curbuf is set to it */ EXTERN buf_T *au_new_curbuf INIT(= NULL); #endif #ifdef FEAT_MOUSE /* * Mouse coordinates, set by check_termcode() */ EXTERN int mouse_row; EXTERN int mouse_col; EXTERN int mouse_past_bottom INIT(= FALSE);/* mouse below last line */ EXTERN int mouse_past_eol INIT(= FALSE); /* mouse right of line */ EXTERN int mouse_dragging INIT(= 0); /* extending Visual area with mouse dragging */ # if defined(FEAT_MOUSE_DEC) /* * When the DEC mouse has been pressed but not yet released we enable * automatic querys for the mouse position. */ EXTERN int WantQueryMouse INIT(= FALSE); # endif # ifdef FEAT_GUI /* When the window layout is about to be changed, need_mouse_correct is set, * so that gui_mouse_correct() is called afterwards, to correct the mouse * pointer when focus-follow-mouse is being used. */ EXTERN int need_mouse_correct INIT(= FALSE); /* When double clicking, topline must be the same */ EXTERN linenr_T gui_prev_topline INIT(= 0); # ifdef FEAT_DIFF EXTERN int gui_prev_topfill INIT(= 0); # endif # endif # ifdef FEAT_MOUSESHAPE EXTERN int drag_status_line INIT(= FALSE); /* dragging the status line */ EXTERN int postponed_mouseshape INIT(= FALSE); /* postponed updating the mouse pointer shape */ # ifdef FEAT_VERTSPLIT EXTERN int drag_sep_line INIT(= FALSE); /* dragging vert separator */ # endif # endif #endif #ifdef FEAT_DIFF /* Value set from 'diffopt'. */ EXTERN int diff_context INIT(= 6); /* context for folds */ EXTERN int diff_foldcolumn INIT(= 2); /* 'foldcolumn' for diff mode */ EXTERN int diff_need_scrollbind INIT(= FALSE); #endif #ifdef FEAT_MENU /* The root of the menu hierarchy. */ EXTERN vimmenu_T *root_menu INIT(= NULL); /* * While defining the system menu, sys_menu is TRUE. This avoids * overruling of menus that the user already defined. */ EXTERN int sys_menu INIT(= FALSE); #endif /* While redrawing the screen this flag is set. It means the screen size * ('lines' and 'rows') must not be changed. */ EXTERN int updating_screen INIT(= FALSE); #ifdef FEAT_GUI # ifdef FEAT_MENU /* Menu item just selected, set by check_termcode() */ EXTERN vimmenu_T *current_menu; /* Set to TRUE after adding/removing menus to ensure they are updated */ EXTERN int force_menu_update INIT(= FALSE); # endif # ifdef FEAT_GUI_TABLINE /* Tab in tab pages line just selected, set by check_termcode() */ EXTERN int current_tab; /* Menu entry in tab pages line menu just selected, set by check_termcode() */ EXTERN int current_tabmenu; # define TABLINE_MENU_CLOSE 1 # define TABLINE_MENU_NEW 2 # define TABLINE_MENU_OPEN 3 # endif /* Scrollbar moved and new value, set by check_termcode() */ EXTERN int current_scrollbar; EXTERN long_u scrollbar_value; /* found "-rv" or "-reverse" in command line args */ EXTERN int found_reverse_arg INIT(= FALSE); /* "-fn" or "-font" command line argument */ EXTERN char *font_argument INIT(= NULL); # ifdef FEAT_GUI_GTK /* "-bg" or "-background" command line argument */ EXTERN char *background_argument INIT(= NULL); /* "-fg" or "-foreground" command line argument */ EXTERN char *foreground_argument INIT(= NULL); # endif /* * While executing external commands or in Ex mode, should not insert GUI * events in the input buffer: Set hold_gui_events to non-zero. * * volatile because it is used in signal handler sig_sysmouse(). */ EXTERN volatile int hold_gui_events INIT(= 0); /* * When resizing the shell is postponed, remember the new size, and call * gui_resize_shell() later. */ EXTERN int new_pixel_width INIT(= 0); EXTERN int new_pixel_height INIT(= 0); /* Window position from ":winpos", to be used when opening the GUI window. */ EXTERN int gui_win_x INIT(= -1); EXTERN int gui_win_y INIT(= -1); #endif #ifdef FEAT_CLIPBOARD EXTERN VimClipboard clip_star; /* PRIMARY selection in X11 */ # ifdef FEAT_X11 EXTERN VimClipboard clip_plus; /* CLIPBOARD selection in X11 */ # else # define clip_plus clip_star /* there is only one clipboard */ # define ONE_CLIPBOARD # endif #define CLIP_UNNAMED 1 #define CLIP_UNNAMED_PLUS 2 EXTERN int clip_unnamed INIT(= 0); /* above two values or'ed */ EXTERN int clip_autoselect INIT(= FALSE); EXTERN int clip_autoselectml INIT(= FALSE); EXTERN int clip_html INIT(= FALSE); EXTERN regprog_T *clip_exclude_prog INIT(= NULL); #endif /* * All windows are linked in a list. firstwin points to the first entry, * lastwin to the last entry (can be the same as firstwin) and curwin to the * currently active window. * Without the FEAT_WINDOWS they are all equal. */ #ifdef FEAT_WINDOWS EXTERN win_T *firstwin; /* first window */ EXTERN win_T *lastwin; /* last window */ EXTERN win_T *prevwin INIT(= NULL); /* previous window */ # define W_NEXT(wp) ((wp)->w_next) # define FOR_ALL_WINDOWS(wp) for (wp = firstwin; wp != NULL; wp = wp->w_next) /* * When using this macro "break" only breaks out of the inner loop. Use "goto" * to break out of the tabpage loop. */ # define FOR_ALL_TAB_WINDOWS(tp, wp) \ for ((tp) = first_tabpage; (tp) != NULL; (tp) = (tp)->tp_next) \ for ((wp) = ((tp) == curtab) \ ? firstwin : (tp)->tp_firstwin; (wp); (wp) = (wp)->w_next) #else # define firstwin curwin # define lastwin curwin # define W_NEXT(wp) NULL # define FOR_ALL_WINDOWS(wp) wp = curwin; # define FOR_ALL_TAB_WINDOWS(tp, wp) wp = curwin; #endif EXTERN win_T *curwin; /* currently active window */ #ifdef FEAT_AUTOCMD EXTERN win_T *aucmd_win; /* window used in aucmd_prepbuf() */ EXTERN int aucmd_win_used INIT(= FALSE); /* aucmd_win is being used */ #endif /* * The window layout is kept in a tree of frames. topframe points to the top * of the tree. */ EXTERN frame_T *topframe; /* top of the window frame tree */ #ifdef FEAT_WINDOWS /* * Tab pages are alternative topframes. "first_tabpage" points to the first * one in the list, "curtab" is the current one. */ EXTERN tabpage_T *first_tabpage; EXTERN tabpage_T *curtab; EXTERN int redraw_tabline INIT(= FALSE); /* need to redraw tabline */ #endif /* * All buffers are linked in a list. 'firstbuf' points to the first entry, * 'lastbuf' to the last entry and 'curbuf' to the currently active buffer. */ EXTERN buf_T *firstbuf INIT(= NULL); /* first buffer */ EXTERN buf_T *lastbuf INIT(= NULL); /* last buffer */ EXTERN buf_T *curbuf INIT(= NULL); /* currently active buffer */ /* Flag that is set when switching off 'swapfile'. It means that all blocks * are to be loaded into memory. Shouldn't be global... */ EXTERN int mf_dont_release INIT(= FALSE); /* don't release blocks */ /* * List of files being edited (global argument list). curwin->w_alist points * to this when the window is using the global argument list. */ EXTERN alist_T global_alist; /* global argument list */ EXTERN int arg_had_last INIT(= FALSE); /* accessed last file in global_alist */ EXTERN int ru_col; /* column for ruler */ #ifdef FEAT_STL_OPT EXTERN int ru_wid; /* 'rulerfmt' width of ruler when non-zero */ #endif EXTERN int sc_col; /* column for shown command */ #ifdef TEMPDIRNAMES EXTERN char_u *vim_tempdir INIT(= NULL); /* Name of Vim's own temp dir. Ends in a slash. */ #endif /* * When starting or exiting some things are done differently (e.g. screen * updating). */ EXTERN int starting INIT(= NO_SCREEN); /* first NO_SCREEN, then NO_BUFFERS and then * set to 0 when starting up finished */ EXTERN int exiting INIT(= FALSE); /* TRUE when planning to exit Vim. Might * still keep on running if there is a changed * buffer. */ EXTERN int really_exiting INIT(= FALSE); /* TRUE when we are sure to exit, e.g., after * a deadly signal */ /* volatile because it is used in signal handler deathtrap(). */ EXTERN volatile int full_screen INIT(= FALSE); /* TRUE when doing full-screen output * otherwise only writing some messages */ EXTERN int restricted INIT(= FALSE); /* TRUE when started as "rvim" */ EXTERN int secure INIT(= FALSE); /* non-zero when only "safe" commands are * allowed, e.g. when sourcing .exrc or .vimrc * in current directory */ EXTERN int textlock INIT(= 0); /* non-zero when changing text and jumping to * another window or buffer is not allowed */ #ifdef FEAT_AUTOCMD EXTERN int curbuf_lock INIT(= 0); /* non-zero when the current buffer can't be * changed. Used for FileChangedRO. */ EXTERN int allbuf_lock INIT(= 0); /* non-zero when no buffer name can be * changed, no buffer can be deleted and * current directory can't be changed. * Used for SwapExists et al. */ #endif #ifdef FEAT_EVAL # define HAVE_SANDBOX EXTERN int sandbox INIT(= 0); /* Non-zero when evaluating an expression in a * "sandbox". Several things are not allowed * then. */ #endif EXTERN int silent_mode INIT(= FALSE); /* set to TRUE when "-s" commandline argument * used for ex */ #ifdef FEAT_VISUAL EXTERN pos_T VIsual; /* start position of active Visual selection */ EXTERN int VIsual_active INIT(= FALSE); /* whether Visual mode is active */ EXTERN int VIsual_select INIT(= FALSE); /* whether Select mode is active */ EXTERN int VIsual_reselect; /* whether to restart the selection after a * Select mode mapping or menu */ EXTERN int VIsual_mode INIT(= 'v'); /* type of Visual mode */ EXTERN int redo_VIsual_busy INIT(= FALSE); /* TRUE when redoing Visual */ #endif #ifdef FEAT_MOUSE /* * When pasting text with the middle mouse button in visual mode with * restart_edit set, remember where it started so we can set Insstart. */ EXTERN pos_T where_paste_started; #endif /* * This flag is used to make auto-indent work right on lines where only a * <RETURN> or <ESC> is typed. It is set when an auto-indent is done, and * reset when any other editing is done on the line. If an <ESC> or <RETURN> * is received, and did_ai is TRUE, the line is truncated. */ EXTERN int did_ai INIT(= FALSE); /* * Column of first char after autoindent. 0 when no autoindent done. Used * when 'backspace' is 0, to avoid backspacing over autoindent. */ EXTERN colnr_T ai_col INIT(= 0); #ifdef FEAT_COMMENTS /* * This is a character which will end a start-middle-end comment when typed as * the first character on a new line. It is taken from the last character of * the "end" comment leader when the COM_AUTO_END flag is given for that * comment end in 'comments'. It is only valid when did_ai is TRUE. */ EXTERN int end_comment_pending INIT(= NUL); #endif #ifdef FEAT_SCROLLBIND /* * This flag is set after a ":syncbind" to let the check_scrollbind() function * know that it should not attempt to perform scrollbinding due to the scroll * that was a result of the ":syncbind." (Otherwise, check_scrollbind() will * undo some of the work done by ":syncbind.") -ralston */ EXTERN int did_syncbind INIT(= FALSE); #endif #ifdef FEAT_SMARTINDENT /* * This flag is set when a smart indent has been performed. When the next typed * character is a '{' the inserted tab will be deleted again. */ EXTERN int did_si INIT(= FALSE); /* * This flag is set after an auto indent. If the next typed character is a '}' * one indent will be removed. */ EXTERN int can_si INIT(= FALSE); /* * This flag is set after an "O" command. If the next typed character is a '{' * one indent will be removed. */ EXTERN int can_si_back INIT(= FALSE); #endif EXTERN pos_T saved_cursor /* w_cursor before formatting text. */ # ifdef DO_INIT = INIT_POS_T(0, 0, 0) # endif ; /* * Stuff for insert mode. */ EXTERN pos_T Insstart; /* This is where the latest * insert/append mode started. */ #ifdef FEAT_VREPLACE /* * Stuff for VREPLACE mode. */ EXTERN int orig_line_count INIT(= 0); /* Line count when "gR" started */ EXTERN int vr_lines_changed INIT(= 0); /* #Lines changed by "gR" so far */ #endif #if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD) /* argument to SETJMP() for handling X IO errors */ EXTERN JMP_BUF x_jump_env; #endif #if defined(HAVE_SETJMP_H) /* * Stuff for setjmp() and longjmp(). * Used to protect areas where we could crash. */ EXTERN JMP_BUF lc_jump_env; /* argument to SETJMP() */ # ifdef SIGHASARG /* volatile because it is used in signal handlers. */ EXTERN volatile int lc_signal; /* caught signal number, 0 when no was signal caught; used for mch_libcall() */ # endif /* volatile because it is used in signal handler deathtrap(). */ EXTERN volatile int lc_active INIT(= FALSE); /* TRUE when lc_jump_env is valid. */ #endif #if defined(FEAT_MBYTE) || defined(FEAT_POSTSCRIPT) /* * These flags are set based upon 'fileencoding'. * Note that "enc_utf8" is also set for "unicode", because the characters are * internally stored as UTF-8 (to avoid trouble with NUL bytes). */ # define DBCS_JPN 932 /* japan */ # define DBCS_JPNU 9932 /* euc-jp */ # define DBCS_KOR 949 /* korea */ # define DBCS_KORU 9949 /* euc-kr */ # define DBCS_CHS 936 /* chinese */ # define DBCS_CHSU 9936 /* euc-cn */ # define DBCS_CHT 950 /* taiwan */ # define DBCS_CHTU 9950 /* euc-tw */ # define DBCS_2BYTE 1 /* 2byte- */ # define DBCS_DEBUG -1 #endif #ifdef FEAT_MBYTE EXTERN int enc_dbcs INIT(= 0); /* One of DBCS_xxx values if DBCS encoding */ EXTERN int enc_unicode INIT(= 0); /* 2: UCS-2 or UTF-16, 4: UCS-4 */ EXTERN int enc_utf8 INIT(= FALSE); /* UTF-8 encoded Unicode */ EXTERN int enc_latin1like INIT(= TRUE); /* 'encoding' is latin1 comp. */ # ifdef WIN3264 /* Codepage nr of 'encoding'. Negative means it's not been set yet, zero * means 'encoding' is not a valid codepage. */ EXTERN int enc_codepage INIT(= -1); EXTERN int enc_latin9 INIT(= FALSE); /* 'encoding' is latin9 */ # endif EXTERN int has_mbyte INIT(= 0); /* any multi-byte encoding */ #if defined(WIN3264) && defined(FEAT_MBYTE) EXTERN int wide_WindowProc INIT(= FALSE); /* use wide WindowProc() */ #endif /* * To speed up BYTELEN() we fill a table with the byte lengths whenever * enc_utf8 or enc_dbcs changes. */ EXTERN char mb_bytelen_tab[256]; /* Variables that tell what conversion is used for keyboard input and display * output. */ EXTERN vimconv_T input_conv; /* type of input conversion */ EXTERN vimconv_T output_conv; /* type of output conversion */ /* * Function pointers, used to quickly get to the right function. Each has * three possible values: latin_ (8-bit), utfc_ or utf_ (utf-8) and dbcs_ * (DBCS). * The value is set in mb_init(); */ /* length of char in bytes, including following composing chars */ EXTERN int (*mb_ptr2len) __ARGS((char_u *p)) INIT(= latin_ptr2len); /* idem, with limit on string length */ EXTERN int (*mb_ptr2len_len) __ARGS((char_u *p, int size)) INIT(= latin_ptr2len_len); /* byte length of char */ EXTERN int (*mb_char2len) __ARGS((int c)) INIT(= latin_char2len); /* convert char to bytes, return the length */ EXTERN int (*mb_char2bytes) __ARGS((int c, char_u *buf)) INIT(= latin_char2bytes); EXTERN int (*mb_ptr2cells) __ARGS((char_u *p)) INIT(= latin_ptr2cells); EXTERN int (*mb_ptr2cells_len) __ARGS((char_u *p, int size)) INIT(= latin_ptr2cells_len); EXTERN int (*mb_char2cells) __ARGS((int c)) INIT(= latin_char2cells); EXTERN int (*mb_off2cells) __ARGS((unsigned off, unsigned max_off)) INIT(= latin_off2cells); EXTERN int (*mb_ptr2char) __ARGS((char_u *p)) INIT(= latin_ptr2char); EXTERN int (*mb_head_off) __ARGS((char_u *base, char_u *p)) INIT(= latin_head_off); # if defined(USE_ICONV) && defined(DYNAMIC_ICONV) /* Pointers to functions and variables to be loaded at runtime */ EXTERN size_t (*iconv) (iconv_t cd, const char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft); EXTERN iconv_t (*iconv_open) (const char *tocode, const char *fromcode); EXTERN int (*iconv_close) (iconv_t cd); EXTERN int (*iconvctl) (iconv_t cd, int request, void *argument); EXTERN int* (*iconv_errno) (void); # endif #endif /* FEAT_MBYTE */ #ifdef FEAT_XIM # ifdef FEAT_GUI_GTK EXTERN GtkIMContext *xic INIT(= NULL); /* * Start and end column of the preedit area in virtual columns from the start * of the text line. When there is no preedit area they are set to MAXCOL. * "preedit_end_col" is needed for coloring the preedited string. Drawing the * color between "preedit_start_col" and curpos did not work, because some XIM * set the cursor position to the first char of the string. */ EXTERN colnr_T preedit_start_col INIT(= MAXCOL); EXTERN colnr_T preedit_end_col INIT(= MAXCOL); /* "xim_changed_while_preediting" is set when changed() can set the 'modified' * flag even while preediting. */ EXTERN int xim_changed_while_preediting INIT(= FALSE); # else EXTERN XIC xic INIT(= NULL); # endif # ifdef FEAT_GUI EXTERN guicolor_T xim_fg_color INIT(= INVALCOLOR); EXTERN guicolor_T xim_bg_color INIT(= INVALCOLOR); # endif #endif #ifdef FEAT_HANGULIN EXTERN int composing_hangul INIT(= 0); EXTERN char_u composing_hangul_buffer[5]; #endif /* * "State" is the main state of Vim. * There are other variables that modify the state: * "Visual_mode" When State is NORMAL or INSERT. * "finish_op" When State is NORMAL, after typing the operator and before * typing the motion command. */ EXTERN int State INIT(= NORMAL); /* This is the current state of the * command interpreter. */ EXTERN int finish_op INIT(= FALSE);/* TRUE while an operator is pending */ EXTERN int opcount INIT(= 0); /* count for pending operator */ /* * ex mode (Q) state */ EXTERN int exmode_active INIT(= 0); /* zero, EXMODE_NORMAL or EXMODE_VIM */ EXTERN int ex_no_reprint INIT(= FALSE); /* no need to print after z or p */ EXTERN int Recording INIT(= FALSE); /* TRUE when recording into a reg. */ EXTERN int Exec_reg INIT(= FALSE); /* TRUE when executing a register */ EXTERN int no_mapping INIT(= FALSE); /* currently no mapping allowed */ EXTERN int no_zero_mapping INIT(= 0); /* mapping zero not allowed */ EXTERN int allow_keys INIT(= FALSE); /* allow key codes when no_mapping * is set */ EXTERN int no_u_sync INIT(= 0); /* Don't call u_sync() */ EXTERN int restart_edit INIT(= 0); /* call edit when next cmd finished */ EXTERN int arrow_used; /* Normally FALSE, set to TRUE after * hitting cursor key in insert mode. * Used by vgetorpeek() to decide when * to call u_sync() */ EXTERN int ins_at_eol INIT(= FALSE); /* put cursor after eol when restarting edit after CTRL-O */ #ifdef FEAT_INS_EXPAND EXTERN char_u *edit_submode INIT(= NULL); /* msg for CTRL-X submode */ EXTERN char_u *edit_submode_pre INIT(= NULL); /* prepended to edit_submode */ EXTERN char_u *edit_submode_extra INIT(= NULL);/* appended to edit_submode */ EXTERN hlf_T edit_submode_highl; /* highl. method for extra info */ EXTERN int ctrl_x_mode INIT(= 0); /* Which Ctrl-X mode are we in? */ #endif EXTERN int no_abbr INIT(= TRUE); /* TRUE when no abbreviations loaded */ #ifdef MSDOS EXTERN int beep_count INIT(= 0); /* nr of beeps since last char typed */ #endif #ifdef USE_EXE_NAME EXTERN char_u *exe_name; /* the name of the executable */ #endif #ifdef USE_ON_FLY_SCROLL EXTERN int dont_scroll INIT(= FALSE);/* don't use scrollbars when TRUE */ #endif EXTERN int mapped_ctrl_c INIT(= FALSE); /* CTRL-C is mapped */ EXTERN int ctrl_c_interrupts INIT(= TRUE); /* CTRL-C sets got_int */ EXTERN cmdmod_T cmdmod; /* Ex command modifiers */ EXTERN int msg_silent INIT(= 0); /* don't print messages */ EXTERN int emsg_silent INIT(= 0); /* don't print error messages */ EXTERN int cmd_silent INIT(= FALSE); /* don't echo the command line */ #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) \ || defined(FEAT_AUTOCMD) # define HAS_SWAP_EXISTS_ACTION EXTERN int swap_exists_action INIT(= SEA_NONE); /* For dialog when swap file already * exists. */ EXTERN int swap_exists_did_quit INIT(= FALSE); /* Selected "quit" at the dialog. */ #endif EXTERN char_u *IObuff; /* sprintf's are done in this buffer, size is IOSIZE */ EXTERN char_u *NameBuff; /* file names are expanded in this * buffer, size is MAXPATHL */ EXTERN char_u msg_buf[MSG_BUF_LEN]; /* small buffer for messages */ /* When non-zero, postpone redrawing. */ EXTERN int RedrawingDisabled INIT(= 0); EXTERN int readonlymode INIT(= FALSE); /* Set to TRUE for "view" */ EXTERN int recoverymode INIT(= FALSE); /* Set to TRUE for "-r" option */ EXTERN struct buffheader stuffbuff /* stuff buffer */ #ifdef DO_INIT = {{NULL, {NUL}}, NULL, 0, 0} #endif ; EXTERN typebuf_T typebuf /* typeahead buffer */ #ifdef DO_INIT = {NULL, NULL, 0, 0, 0, 0, 0, 0, 0} #endif ; #ifdef FEAT_EX_EXTRA EXTERN int ex_normal_busy INIT(= 0); /* recursiveness of ex_normal() */ EXTERN int ex_normal_lock INIT(= 0); /* forbid use of ex_normal() */ #endif #ifdef FEAT_EVAL EXTERN int ignore_script INIT(= FALSE); /* ignore script input */ #endif EXTERN int stop_insert_mode; /* for ":stopinsert" and 'insertmode' */ EXTERN int KeyTyped; /* TRUE if user typed current char */ EXTERN int KeyStuffed; /* TRUE if current char from stuffbuf */ #ifdef USE_IM_CONTROL EXTERN int vgetc_im_active; /* Input Method was active for last character obtained from vgetc() */ #endif EXTERN int maptick INIT(= 0); /* tick for each non-mapped char */ EXTERN char_u chartab[256]; /* table used in charset.c; See init_chartab() for explanation */ EXTERN int must_redraw INIT(= 0); /* type of redraw necessary */ EXTERN int skip_redraw INIT(= FALSE); /* skip redraw once */ EXTERN int do_redraw INIT(= FALSE); /* extra redraw once */ EXTERN int need_highlight_changed INIT(= TRUE); EXTERN char_u *use_viminfo INIT(= NULL); /* name of viminfo file to use */ #define NSCRIPT 15 EXTERN FILE *scriptin[NSCRIPT]; /* streams to read script from */ EXTERN int curscript INIT(= 0); /* index in scriptin[] */ EXTERN FILE *scriptout INIT(= NULL); /* stream to write script to */ EXTERN int read_cmd_fd INIT(= 0); /* fd to read commands from */ /* volatile because it is used in signal handler catch_sigint(). */ EXTERN volatile int got_int INIT(= FALSE); /* set to TRUE when interrupt signal occurred */ #ifdef USE_TERM_CONSOLE EXTERN int term_console INIT(= FALSE); /* set to TRUE when console used */ #endif EXTERN int termcap_active INIT(= FALSE); /* set by starttermcap() */ EXTERN int cur_tmode INIT(= TMODE_COOK); /* input terminal mode */ EXTERN int bangredo INIT(= FALSE); /* set to TRUE with ! command */ EXTERN int searchcmdlen; /* length of previous search cmd */ #ifdef FEAT_SYN_HL EXTERN int reg_do_extmatch INIT(= 0); /* Used when compiling regexp: * REX_SET to allow \z\(...\), * REX_USE to allow \z\1 et al. */ EXTERN reg_extmatch_T *re_extmatch_in INIT(= NULL); /* Used by vim_regexec(): * strings for \z\1...\z\9 */ EXTERN reg_extmatch_T *re_extmatch_out INIT(= NULL); /* Set by vim_regexec() * to store \z\(...\) matches */ #endif EXTERN int did_outofmem_msg INIT(= FALSE); /* set after out of memory msg */ EXTERN int did_swapwrite_msg INIT(= FALSE); /* set after swap write error msg */ EXTERN int undo_off INIT(= FALSE); /* undo switched off for now */ EXTERN int global_busy INIT(= 0); /* set when :global is executing */ EXTERN int listcmd_busy INIT(= FALSE); /* set when :argdo, :windo or :bufdo is executing */ EXTERN int need_start_insertmode INIT(= FALSE); /* start insert mode soon */ EXTERN char_u *last_cmdline INIT(= NULL); /* last command line (for ":) */ EXTERN char_u *repeat_cmdline INIT(= NULL); /* command line for "." */ #ifdef FEAT_CMDHIST EXTERN char_u *new_last_cmdline INIT(= NULL); /* new value for last_cmdline */ #endif #ifdef FEAT_AUTOCMD EXTERN char_u *autocmd_fname INIT(= NULL); /* fname for <afile> on cmdline */ EXTERN int autocmd_fname_full; /* autocmd_fname is full path */ EXTERN int autocmd_bufnr INIT(= 0); /* fnum for <abuf> on cmdline */ EXTERN char_u *autocmd_match INIT(= NULL); /* name for <amatch> on cmdline */ EXTERN int did_cursorhold INIT(= FALSE); /* set when CursorHold t'gerd */ EXTERN pos_T last_cursormoved /* for CursorMoved event */ # ifdef DO_INIT = INIT_POS_T(0, 0, 0) # endif ; #endif #ifdef FEAT_WINDOWS EXTERN int postponed_split INIT(= 0); /* for CTRL-W CTRL-] command */ EXTERN int postponed_split_flags INIT(= 0); /* args for win_split() */ EXTERN int postponed_split_tab INIT(= 0); /* cmdmod.tab */ # ifdef FEAT_QUICKFIX EXTERN int g_do_tagpreview INIT(= 0); /* for tag preview commands: height of preview window */ # endif #endif EXTERN int replace_offset INIT(= 0); /* offset for replace_push() */ EXTERN char_u *escape_chars INIT(= (char_u *)" \t\\\"|"); /* need backslash in cmd line */ EXTERN int keep_help_flag INIT(= FALSE); /* doing :ta from help file */ /* * When a string option is NULL (which only happens in out-of-memory * situations), it is set to empty_option, to avoid having to check for NULL * everywhere. */ EXTERN char_u *empty_option INIT(= (char_u *)""); EXTERN int redir_off INIT(= FALSE); /* no redirection for a moment */ EXTERN FILE *redir_fd INIT(= NULL); /* message redirection file */ #ifdef FEAT_EVAL EXTERN int redir_reg INIT(= 0); /* message redirection register */ EXTERN int redir_vname INIT(= 0); /* message redirection variable */ #endif #ifdef FEAT_LANGMAP EXTERN char_u langmap_mapchar[256]; /* mapping for language keys */ #endif #ifdef FEAT_WILDMENU EXTERN int save_p_ls INIT(= -1); /* Save 'laststatus' setting */ EXTERN int save_p_wmh INIT(= -1); /* Save 'winminheight' setting */ EXTERN int wild_menu_showing INIT(= 0); #define WM_SHOWN 1 /* wildmenu showing */ #define WM_SCROLLED 2 /* wildmenu showing with scroll */ #endif #ifdef MSWIN EXTERN char_u toupper_tab[256]; /* table for toupper() */ EXTERN char_u tolower_tab[256]; /* table for tolower() */ #endif #ifdef FEAT_LINEBREAK EXTERN char breakat_flags[256]; /* which characters are in 'breakat' */ #endif /* these are in version.c */ extern char *Version; #if defined(HAVE_DATE_TIME) && defined(VMS) && defined(VAXC) extern char longVersion[]; #else extern char *longVersion; #endif /* * Some file names are stored in pathdef.c, which is generated from the * Makefile to make their value depend on the Makefile. */ #ifdef HAVE_PATHDEF extern char_u *default_vim_dir; extern char_u *default_vimruntime_dir; extern char_u *all_cflags; extern char_u *all_lflags; # ifdef VMS extern char_u *compiler_version; extern char_u *compiled_arch; # endif extern char_u *compiled_user; extern char_u *compiled_sys; #endif /* When a window has a local directory, the absolute path of the global * current directory is stored here (in allocated memory). If the current * directory is not a local directory, globaldir is NULL. */ EXTERN char_u *globaldir INIT(= NULL); /* Characters from 'listchars' option */ EXTERN int lcs_eol INIT(= '$'); EXTERN int lcs_ext INIT(= NUL); EXTERN int lcs_prec INIT(= NUL); EXTERN int lcs_nbsp INIT(= NUL); EXTERN int lcs_tab1 INIT(= NUL); EXTERN int lcs_tab2 INIT(= NUL); EXTERN int lcs_trail INIT(= NUL); #ifdef FEAT_CONCEAL EXTERN int lcs_conceal INIT(= '-'); #endif #if defined(FEAT_WINDOWS) || defined(FEAT_WILDMENU) || defined(FEAT_STL_OPT) \ || defined(FEAT_FOLDING) /* Characters from 'fillchars' option */ EXTERN int fill_stl INIT(= ' '); EXTERN int fill_stlnc INIT(= ' '); #endif #if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING) EXTERN int fill_vert INIT(= ' '); EXTERN int fill_fold INIT(= '-'); EXTERN int fill_diff INIT(= '-'); #endif #ifdef FEAT_VISUAL /* Whether 'keymodel' contains "stopsel" and "startsel". */ EXTERN int km_stopsel INIT(= FALSE); EXTERN int km_startsel INIT(= FALSE); #endif #ifdef FEAT_CMDWIN EXTERN int cedit_key INIT(= -1); /* key value of 'cedit' option */ EXTERN int cmdwin_type INIT(= 0); /* type of cmdline window or 0 */ EXTERN int cmdwin_result INIT(= 0); /* result of cmdline window or 0 */ #endif EXTERN char_u no_lines_msg[] INIT(= N_("--No lines in buffer--")); /* * When ":global" is used to number of substitutions and changed lines is * accumulated until it's finished. * Also used for ":spellrepall". */ EXTERN long sub_nsubs; /* total number of substitutions */ EXTERN linenr_T sub_nlines; /* total number of lines changed */ /* table to store parsed 'wildmode' */ EXTERN char_u wim_flags[4]; #if defined(FEAT_TITLE) && defined(FEAT_STL_OPT) /* whether titlestring and iconstring contains statusline syntax */ # define STL_IN_ICON 1 # define STL_IN_TITLE 2 EXTERN int stl_syntax INIT(= 0); #endif #ifdef FEAT_SEARCH_EXTRA /* don't use 'hlsearch' temporarily */ EXTERN int no_hlsearch INIT(= FALSE); #endif #if defined(FEAT_BEVAL) && !defined(NO_X11_INCLUDES) EXTERN BalloonEval *balloonEval INIT(= NULL); # if defined(FEAT_NETBEANS_INTG) || defined(FEAT_SUN_WORKSHOP) EXTERN int bevalServers INIT(= 0); # define BEVAL_NETBEANS 0x01 # define BEVAL_WORKSHOP 0x02 # endif #endif #ifdef CURSOR_SHAPE /* the table is in misc2.c, because of initializations */ extern cursorentry_T shape_table[SHAPE_IDX_COUNT]; #endif #ifdef FEAT_PRINTER /* * Printer stuff shared between hardcopy.c and machine-specific printing code. */ # define OPT_PRINT_TOP 0 # define OPT_PRINT_BOT 1 # define OPT_PRINT_LEFT 2 # define OPT_PRINT_RIGHT 3 # define OPT_PRINT_HEADERHEIGHT 4 # define OPT_PRINT_SYNTAX 5 # define OPT_PRINT_NUMBER 6 # define OPT_PRINT_WRAP 7 # define OPT_PRINT_DUPLEX 8 # define OPT_PRINT_PORTRAIT 9 # define OPT_PRINT_PAPER 10 # define OPT_PRINT_COLLATE 11 # define OPT_PRINT_JOBSPLIT 12 # define OPT_PRINT_FORMFEED 13 # define OPT_PRINT_NUM_OPTIONS 14 EXTERN option_table_T printer_opts[OPT_PRINT_NUM_OPTIONS] # ifdef DO_INIT = { {"top", TRUE, 0, NULL, 0, FALSE}, {"bottom", TRUE, 0, NULL, 0, FALSE}, {"left", TRUE, 0, NULL, 0, FALSE}, {"right", TRUE, 0, NULL, 0, FALSE}, {"header", TRUE, 0, NULL, 0, FALSE}, {"syntax", FALSE, 0, NULL, 0, FALSE}, {"number", FALSE, 0, NULL, 0, FALSE}, {"wrap", FALSE, 0, NULL, 0, FALSE}, {"duplex", FALSE, 0, NULL, 0, FALSE}, {"portrait", FALSE, 0, NULL, 0, FALSE}, {"paper", FALSE, 0, NULL, 0, FALSE}, {"collate", FALSE, 0, NULL, 0, FALSE}, {"jobsplit", FALSE, 0, NULL, 0, FALSE}, {"formfeed", FALSE, 0, NULL, 0, FALSE}, } # endif ; /* For prt_get_unit(). */ # define PRT_UNIT_NONE -1 # define PRT_UNIT_PERC 0 # define PRT_UNIT_INCH 1 # define PRT_UNIT_MM 2 # define PRT_UNIT_POINT 3 # define PRT_UNIT_NAMES {"pc", "in", "mm", "pt"} #endif #if (defined(FEAT_PRINTER) && defined(FEAT_STL_OPT)) \ || defined(FEAT_GUI_TABLINE) /* Page number used for %N in 'pageheader' and 'guitablabel'. */ EXTERN linenr_T printer_page_num; #endif #ifdef FEAT_XCLIPBOARD EXTERN char *xterm_display INIT(= NULL); /* xterm display name; points into argv[] */ EXTERN Display *xterm_dpy INIT(= NULL); /* xterm display pointer */ #endif #if defined(FEAT_XCLIPBOARD) || defined(FEAT_GUI_X11) EXTERN XtAppContext app_context INIT(= (XtAppContext)NULL); #endif #ifdef FEAT_GUI_GTK EXTERN guint32 gtk_socket_id INIT(= 0); EXTERN int echo_wid_arg INIT(= FALSE); /* --echo-wid argument */ #endif #ifdef FEAT_GUI_W32 /* * The value of the --windowid argument. * For embedding gvim inside another application. */ EXTERN long_u win_socket_id INIT(= 0); #endif #if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL) EXTERN int typebuf_was_filled INIT(= FALSE); /* received text from client or from feedkeys() */ #endif #ifdef FEAT_CLIENTSERVER EXTERN char_u *serverName INIT(= NULL); /* name of the server */ # ifdef FEAT_X11 EXTERN Window commWindow INIT(= None); EXTERN Window clientWindow INIT(= None); EXTERN Atom commProperty INIT(= None); EXTERN char_u *serverDelayedStartName INIT(= NULL); # else # ifdef PROTO typedef int HWND; # endif EXTERN HWND clientWindow INIT(= 0); # endif #endif #if defined(UNIX) || defined(VMS) EXTERN int term_is_xterm INIT(= FALSE); /* xterm-like 'term' */ #endif #ifdef BACKSLASH_IN_FILENAME EXTERN char psepc INIT(= '\\'); /* normal path separator character */ EXTERN char psepcN INIT(= '/'); /* abnormal path separator character */ EXTERN char pseps[2] /* normal path separator string */ # ifdef DO_INIT = {'\\', 0} # endif ; #endif #ifdef FEAT_VIRTUALEDIT /* Set to TRUE when an operator is being executed with virtual editing, MAYBE * when no operator is being executed, FALSE otherwise. */ EXTERN int virtual_op INIT(= MAYBE); #endif #ifdef FEAT_SYN_HL /* Display tick, incremented for each call to update_screen() */ EXTERN disptick_T display_tick INIT(= 0); #endif #ifdef FEAT_SPELL /* Line in which spell checking wasn't highlighted because it touched the * cursor position in Insert mode. */ EXTERN linenr_T spell_redraw_lnum INIT(= 0); #endif #ifdef FEAT_CONCEAL /* Set when the cursor line needs to be redrawn. */ EXTERN int need_cursor_line_redraw INIT(= FALSE); #endif #ifdef ALT_X_INPUT /* we need to be able to go into the dispatch loop while processing a command * received via alternate input. However, we don't want to process another * command until the first is completed. */ EXTERN int suppress_alternate_input INIT(= FALSE); #endif #ifdef USE_MCH_ERRMSG /* Grow array to collect error messages in until they can be displayed. */ EXTERN garray_T error_ga # ifdef DO_INIT = {0, 0, 0, 0, NULL} # endif ; #endif #ifdef FEAT_NETBEANS_INTG EXTERN char *netbeansArg INIT(= NULL); /* the -nb[:host:port:passwd] arg */ EXTERN int netbeansFireChanges INIT(= 1); /* send buffer changes if != 0 */ EXTERN int netbeansForcedQuit INIT(= 0);/* don't write modified files */ EXTERN int netbeansReadFile INIT(= 1); /* OK to read from disk if != 0 */ EXTERN int netbeansSuppressNoLines INIT(= 0); /* skip "No lines in buffer" */ #endif /* * The error messages that can be shared are included here. * Excluded are errors that are only used once and debugging messages. */ EXTERN char_u e_abort[] INIT(= N_("E470: Command aborted")); EXTERN char_u e_argreq[] INIT(= N_("E471: Argument required")); EXTERN char_u e_backslash[] INIT(= N_("E10: \\ should be followed by /, ? or &")); #ifdef FEAT_CMDWIN EXTERN char_u e_cmdwin[] INIT(= N_("E11: Invalid in command-line window; <CR> executes, CTRL-C quits")); #endif EXTERN char_u e_curdir[] INIT(= N_("E12: Command not allowed from exrc/vimrc in current dir or tag search")); #ifdef FEAT_EVAL EXTERN char_u e_endif[] INIT(= N_("E171: Missing :endif")); EXTERN char_u e_endtry[] INIT(= N_("E600: Missing :endtry")); EXTERN char_u e_endwhile[] INIT(= N_("E170: Missing :endwhile")); EXTERN char_u e_endfor[] INIT(= N_("E170: Missing :endfor")); EXTERN char_u e_while[] INIT(= N_("E588: :endwhile without :while")); EXTERN char_u e_for[] INIT(= N_("E588: :endfor without :for")); #endif EXTERN char_u e_exists[] INIT(= N_("E13: File exists (add ! to override)")); EXTERN char_u e_failed[] INIT(= N_("E472: Command failed")); #if defined(FEAT_GUI) && defined(FEAT_XFONTSET) EXTERN char_u e_fontset[] INIT(= N_("E234: Unknown fontset: %s")); #endif #if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK) || defined(MACOS) \ || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MSWIN) EXTERN char_u e_font[] INIT(= N_("E235: Unknown font: %s")); #endif #if defined(FEAT_GUI_X11) && !defined(FEAT_GUI_GTK) EXTERN char_u e_fontwidth[] INIT(= N_("E236: Font \"%s\" is not fixed-width")); #endif EXTERN char_u e_internal[] INIT(= N_("E473: Internal error")); EXTERN char_u e_interr[] INIT(= N_("Interrupted")); EXTERN char_u e_invaddr[] INIT(= N_("E14: Invalid address")); EXTERN char_u e_invarg[] INIT(= N_("E474: Invalid argument")); EXTERN char_u e_invarg2[] INIT(= N_("E475: Invalid argument: %s")); #ifdef FEAT_EVAL EXTERN char_u e_invexpr2[] INIT(= N_("E15: Invalid expression: %s")); #endif EXTERN char_u e_invrange[] INIT(= N_("E16: Invalid range")); EXTERN char_u e_invcmd[] INIT(= N_("E476: Invalid command")); #if defined(UNIX) || defined(FEAT_SYN_HL) || defined(FEAT_SPELL) EXTERN char_u e_isadir2[] INIT(= N_("E17: \"%s\" is a directory")); #endif #ifdef FEAT_LIBCALL EXTERN char_u e_libcall[] INIT(= N_("E364: Library call failed for \"%s()\"")); #endif #if defined(DYNAMIC_PERL) \ || defined(DYNAMIC_PYTHON) || defined(DYNAMIC_PYTHON3) \ || defined(DYNAMIC_RUBY) \ || defined(DYNAMIC_TCL) \ || defined(DYNAMIC_ICONV) \ || defined(DYNAMIC_GETTEXT) \ || defined(DYNAMIC_MZSCHEME) \ || defined(DYNAMIC_LUA) EXTERN char_u e_loadlib[] INIT(= N_("E370: Could not load library %s")); EXTERN char_u e_loadfunc[] INIT(= N_("E448: Could not load library function %s")); #endif EXTERN char_u e_markinval[] INIT(= N_("E19: Mark has invalid line number")); EXTERN char_u e_marknotset[] INIT(= N_("E20: Mark not set")); EXTERN char_u e_modifiable[] INIT(= N_("E21: Cannot make changes, 'modifiable' is off")); EXTERN char_u e_nesting[] INIT(= N_("E22: Scripts nested too deep")); EXTERN char_u e_noalt[] INIT(= N_("E23: No alternate file")); EXTERN char_u e_noabbr[] INIT(= N_("E24: No such abbreviation")); EXTERN char_u e_nobang[] INIT(= N_("E477: No ! allowed")); #ifndef FEAT_GUI EXTERN char_u e_nogvim[] INIT(= N_("E25: GUI cannot be used: Not enabled at compile time")); #endif #ifndef FEAT_RIGHTLEFT EXTERN char_u e_nohebrew[] INIT(= N_("E26: Hebrew cannot be used: Not enabled at compile time\n")); #endif #ifndef FEAT_FKMAP EXTERN char_u e_nofarsi[] INIT(= N_("E27: Farsi cannot be used: Not enabled at compile time\n")); #endif #ifndef FEAT_ARABIC EXTERN char_u e_noarabic[] INIT(= N_("E800: Arabic cannot be used: Not enabled at compile time\n")); #endif #if defined(FEAT_SEARCH_EXTRA) || defined(FEAT_SYN_HL) EXTERN char_u e_nogroup[] INIT(= N_("E28: No such highlight group name: %s")); #endif EXTERN char_u e_noinstext[] INIT(= N_("E29: No inserted text yet")); EXTERN char_u e_nolastcmd[] INIT(= N_("E30: No previous command line")); EXTERN char_u e_nomap[] INIT(= N_("E31: No such mapping")); EXTERN char_u e_nomatch[] INIT(= N_("E479: No match")); EXTERN char_u e_nomatch2[] INIT(= N_("E480: No match: %s")); EXTERN char_u e_noname[] INIT(= N_("E32: No file name")); EXTERN char_u e_nopresub[] INIT(= N_("E33: No previous substitute regular expression")); EXTERN char_u e_noprev[] INIT(= N_("E34: No previous command")); EXTERN char_u e_noprevre[] INIT(= N_("E35: No previous regular expression")); EXTERN char_u e_norange[] INIT(= N_("E481: No range allowed")); #ifdef FEAT_WINDOWS EXTERN char_u e_noroom[] INIT(= N_("E36: Not enough room")); #endif #ifdef FEAT_CLIENTSERVER EXTERN char_u e_noserver[] INIT(= N_("E247: no registered server named \"%s\"")); #endif EXTERN char_u e_notcreate[] INIT(= N_("E482: Can't create file %s")); EXTERN char_u e_notmp[] INIT(= N_("E483: Can't get temp file name")); EXTERN char_u e_notopen[] INIT(= N_("E484: Can't open file %s")); EXTERN char_u e_notread[] INIT(= N_("E485: Can't read file %s")); EXTERN char_u e_nowrtmsg[] INIT(= N_("E37: No write since last change (add ! to override)")); EXTERN char_u e_null[] INIT(= N_("E38: Null argument")); #ifdef FEAT_DIGRAPHS EXTERN char_u e_number_exp[] INIT(= N_("E39: Number expected")); #endif #ifdef FEAT_QUICKFIX EXTERN char_u e_openerrf[] INIT(= N_("E40: Can't open errorfile %s")); #endif #if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_X11) EXTERN char_u e_opendisp[] INIT(= N_("E233: cannot open display")); #endif EXTERN char_u e_outofmem[] INIT(= N_("E41: Out of memory!")); #ifdef FEAT_INS_EXPAND EXTERN char_u e_patnotf[] INIT(= N_("Pattern not found")); #endif EXTERN char_u e_patnotf2[] INIT(= N_("E486: Pattern not found: %s")); EXTERN char_u e_positive[] INIT(= N_("E487: Argument must be positive")); #if defined(UNIX) || defined(FEAT_SESSION) EXTERN char_u e_prev_dir[] INIT(= N_("E459: Cannot go back to previous directory")); #endif #ifdef FEAT_QUICKFIX EXTERN char_u e_quickfix[] INIT(= N_("E42: No Errors")); EXTERN char_u e_loclist[] INIT(= N_("E776: No location list")); #endif EXTERN char_u e_re_damg[] INIT(= N_("E43: Damaged match string")); EXTERN char_u e_re_corr[] INIT(= N_("E44: Corrupted regexp program")); EXTERN char_u e_readonly[] INIT(= N_("E45: 'readonly' option is set (add ! to override)")); #ifdef FEAT_EVAL EXTERN char_u e_readonlyvar[] INIT(= N_("E46: Cannot change read-only variable \"%s\"")); EXTERN char_u e_readonlysbx[] INIT(= N_("E794: Cannot set variable in the sandbox: \"%s\"")); #endif #ifdef FEAT_QUICKFIX EXTERN char_u e_readerrf[] INIT(= N_("E47: Error while reading errorfile")); #endif #ifdef HAVE_SANDBOX EXTERN char_u e_sandbox[] INIT(= N_("E48: Not allowed in sandbox")); #endif EXTERN char_u e_secure[] INIT(= N_("E523: Not allowed here")); #if defined(AMIGA) || defined(MACOS) || defined(MSWIN) \ || defined(UNIX) || defined(VMS) || defined(OS2) EXTERN char_u e_screenmode[] INIT(= N_("E359: Screen mode setting not supported")); #endif EXTERN char_u e_scroll[] INIT(= N_("E49: Invalid scroll size")); EXTERN char_u e_shellempty[] INIT(= N_("E91: 'shell' option is empty")); #if defined(FEAT_SIGN_ICONS) && !defined(FEAT_GUI_GTK) EXTERN char_u e_signdata[] INIT(= N_("E255: Couldn't read in sign data!")); #endif EXTERN char_u e_swapclose[] INIT(= N_("E72: Close error on swap file")); EXTERN char_u e_tagstack[] INIT(= N_("E73: tag stack empty")); EXTERN char_u e_toocompl[] INIT(= N_("E74: Command too complex")); EXTERN char_u e_longname[] INIT(= N_("E75: Name too long")); EXTERN char_u e_toomsbra[] INIT(= N_("E76: Too many [")); EXTERN char_u e_toomany[] INIT(= N_("E77: Too many file names")); EXTERN char_u e_trailing[] INIT(= N_("E488: Trailing characters")); EXTERN char_u e_umark[] INIT(= N_("E78: Unknown mark")); EXTERN char_u e_wildexpand[] INIT(= N_("E79: Cannot expand wildcards")); #ifdef FEAT_WINDOWS EXTERN char_u e_winheight[] INIT(= N_("E591: 'winheight' cannot be smaller than 'winminheight'")); # ifdef FEAT_VERTSPLIT EXTERN char_u e_winwidth[] INIT(= N_("E592: 'winwidth' cannot be smaller than 'winminwidth'")); # endif #endif EXTERN char_u e_write[] INIT(= N_("E80: Error while writing")); EXTERN char_u e_zerocount[] INIT(= N_("Zero count")); #ifdef FEAT_EVAL EXTERN char_u e_usingsid[] INIT(= N_("E81: Using <SID> not in a script context")); #endif #ifdef FEAT_CLIENTSERVER EXTERN char_u e_invexprmsg[] INIT(= N_("E449: Invalid expression received")); #endif #ifdef FEAT_NETBEANS_INTG EXTERN char_u e_guarded[] INIT(= N_("E463: Region is guarded, cannot modify")); EXTERN char_u e_nbreadonly[] INIT(= N_("E744: NetBeans does not allow changes in read-only files")); #endif EXTERN char_u e_intern2[] INIT(= N_("E685: Internal error: %s")); EXTERN char_u e_maxmempat[] INIT(= N_("E363: pattern uses more memory than 'maxmempattern'")); EXTERN char_u e_emptybuf[] INIT(= N_("E749: empty buffer")); #ifdef FEAT_EX_EXTRA EXTERN char_u e_invalpat[] INIT(= N_("E682: Invalid search pattern or delimiter")); #endif EXTERN char_u e_bufloaded[] INIT(= N_("E139: File is loaded in another buffer")); #if defined(FEAT_SYN_HL) || \ (defined(FEAT_INS_EXPAND) && defined(FEAT_COMPL_FUNC)) EXTERN char_u e_notset[] INIT(= N_("E764: Option '%s' is not set")); #endif #ifndef FEAT_CLIPBOARD EXTERN char_u e_invalidreg[] INIT(= N_("E850: Invalid register name")); #endif #ifdef MACOS_X_UNIX EXTERN short disallow_gui INIT(= FALSE); #endif EXTERN char top_bot_msg[] INIT(= N_("search hit TOP, continuing at BOTTOM")); EXTERN char bot_top_msg[] INIT(= N_("search hit BOTTOM, continuing at TOP")); #ifdef FEAT_CRYPT EXTERN char need_key_msg[] INIT(= N_("Need encryption key for \"%s\"")); #endif /* * Comms. with the session manager (XSMP) */ #ifdef USE_XSMP EXTERN int xsmp_icefd INIT(= -1); /* The actual connection */ #endif /* For undo we need to know the lowest time possible. */ EXTERN time_t starttime; #ifdef STARTUPTIME EXTERN FILE *time_fd INIT(= NULL); /* where to write startup timing */ #endif /* * Some compilers warn for not using a return value, but in some situations we * can't do anything useful with the value. Assign to this variable to avoid * the warning. */ EXTERN int ignored; EXTERN char *ignoredp; /* * Optional Farsi support. Include it here, so EXTERN and INIT are defined. */ #ifdef FEAT_FKMAP # include "farsi.h" #endif /* * Optional Arabic support. Include it here, so EXTERN and INIT are defined. */ #ifdef FEAT_ARABIC # include "arabic.h" #endif
zyz2011-vim
src/globals.h
C
gpl2
59,503
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * * term.c: functions for controlling the terminal * * primitive termcap support for Amiga, MSDOS, and Win32 included * * NOTE: padding and variable substitution is not performed, * when compiling without HAVE_TGETENT, we use tputs() and tgoto() dummies. */ /* * Some systems have a prototype for tgetstr() with (char *) instead of * (char **). This define removes that prototype. We include our own prototype * below. */ #define tgetstr tgetstr_defined_wrong #include "vim.h" #ifdef HAVE_TGETENT # ifdef HAVE_TERMIOS_H # include <termios.h> /* seems to be required for some Linux */ # endif # ifdef HAVE_TERMCAP_H # include <termcap.h> # endif /* * A few linux systems define outfuntype in termcap.h to be used as the third * argument for tputs(). */ # ifdef VMS # define TPUTSFUNCAST # else # ifdef HAVE_OUTFUNTYPE # define TPUTSFUNCAST (outfuntype) # else # define TPUTSFUNCAST (int (*)()) # endif # endif #endif #undef tgetstr /* * Here are the builtin termcap entries. They are not stored as complete * structures with all entries, as such a structure is too big. * * The entries are compact, therefore they normally are included even when * HAVE_TGETENT is defined. When HAVE_TGETENT is defined, the builtin entries * can be accessed with "builtin_amiga", "builtin_ansi", "builtin_debug", etc. * * Each termcap is a list of builtin_term structures. It always starts with * KS_NAME, which separates the entries. See parse_builtin_tcap() for all * details. * bt_entry is either a KS_xxx code (>= 0), or a K_xxx code. * * Entries marked with "guessed" may be wrong. */ struct builtin_term { int bt_entry; char *bt_string; }; /* start of keys that are not directly used by Vim but can be mapped */ #define BT_EXTRA_KEYS 0x101 static struct builtin_term *find_builtin_term __ARGS((char_u *name)); static void parse_builtin_tcap __ARGS((char_u *s)); static void term_color __ARGS((char_u *s, int n)); static void gather_termleader __ARGS((void)); #ifdef FEAT_TERMRESPONSE static void req_codes_from_term __ARGS((void)); static void req_more_codes_from_term __ARGS((void)); static void got_code_from_term __ARGS((char_u *code, int len)); static void check_for_codes_from_term __ARGS((void)); #endif #if defined(FEAT_GUI) \ || (defined(FEAT_MOUSE) && (!defined(UNIX) || defined(FEAT_MOUSE_XTERM) \ || defined(FEAT_MOUSE_GPM) || defined(FEAT_SYSMOUSE))) static int get_bytes_from_buf __ARGS((char_u *, char_u *, int)); #endif static void del_termcode_idx __ARGS((int idx)); static int term_is_builtin __ARGS((char_u *name)); static int term_7to8bit __ARGS((char_u *p)); #ifdef FEAT_TERMRESPONSE static void switch_to_8bit __ARGS((void)); #endif #ifdef HAVE_TGETENT static char_u *tgetent_error __ARGS((char_u *, char_u *)); /* * Here is our own prototype for tgetstr(), any prototypes from the include * files have been disabled by the define at the start of this file. */ char *tgetstr __ARGS((char *, char **)); # ifdef FEAT_TERMRESPONSE /* Request Terminal Version status: */ # define CRV_GET 1 /* send T_CRV when switched to RAW mode */ # define CRV_SENT 2 /* did send T_CRV, waiting for answer */ # define CRV_GOT 3 /* received T_CRV response */ static int crv_status = CRV_GET; # endif /* * Don't declare these variables if termcap.h contains them. * Autoconf checks if these variables should be declared extern (not all * systems have them). * Some versions define ospeed to be speed_t, but that is incompatible with * BSD, where ospeed is short and speed_t is long. */ # ifndef HAVE_OSPEED # ifdef OSPEED_EXTERN extern short ospeed; # else short ospeed; # endif # endif # ifndef HAVE_UP_BC_PC # ifdef UP_BC_PC_EXTERN extern char *UP, *BC, PC; # else char *UP, *BC, PC; # endif # endif # define TGETSTR(s, p) vim_tgetstr((s), (p)) # define TGETENT(b, t) tgetent((char *)(b), (char *)(t)) static char_u *vim_tgetstr __ARGS((char *s, char_u **pp)); #endif /* HAVE_TGETENT */ static int detected_8bit = FALSE; /* detected 8-bit terminal */ static struct builtin_term builtin_termcaps[] = { #if defined(FEAT_GUI) /* * GUI pseudo term-cap. */ {(int)KS_NAME, "gui"}, {(int)KS_CE, IF_EB("\033|$", ESC_STR "|$")}, {(int)KS_AL, IF_EB("\033|i", ESC_STR "|i")}, # ifdef TERMINFO {(int)KS_CAL, IF_EB("\033|%p1%dI", ESC_STR "|%p1%dI")}, # else {(int)KS_CAL, IF_EB("\033|%dI", ESC_STR "|%dI")}, # endif {(int)KS_DL, IF_EB("\033|d", ESC_STR "|d")}, # ifdef TERMINFO {(int)KS_CDL, IF_EB("\033|%p1%dD", ESC_STR "|%p1%dD")}, {(int)KS_CS, IF_EB("\033|%p1%d;%p2%dR", ESC_STR "|%p1%d;%p2%dR")}, # ifdef FEAT_VERTSPLIT {(int)KS_CSV, IF_EB("\033|%p1%d;%p2%dV", ESC_STR "|%p1%d;%p2%dV")}, # endif # else {(int)KS_CDL, IF_EB("\033|%dD", ESC_STR "|%dD")}, {(int)KS_CS, IF_EB("\033|%d;%dR", ESC_STR "|%d;%dR")}, # ifdef FEAT_VERTSPLIT {(int)KS_CSV, IF_EB("\033|%d;%dV", ESC_STR "|%d;%dV")}, # endif # endif {(int)KS_CL, IF_EB("\033|C", ESC_STR "|C")}, /* attributes switched on with 'h', off with * 'H' */ {(int)KS_ME, IF_EB("\033|31H", ESC_STR "|31H")}, /* HL_ALL */ {(int)KS_MR, IF_EB("\033|1h", ESC_STR "|1h")}, /* HL_INVERSE */ {(int)KS_MD, IF_EB("\033|2h", ESC_STR "|2h")}, /* HL_BOLD */ {(int)KS_SE, IF_EB("\033|16H", ESC_STR "|16H")}, /* HL_STANDOUT */ {(int)KS_SO, IF_EB("\033|16h", ESC_STR "|16h")}, /* HL_STANDOUT */ {(int)KS_UE, IF_EB("\033|8H", ESC_STR "|8H")}, /* HL_UNDERLINE */ {(int)KS_US, IF_EB("\033|8h", ESC_STR "|8h")}, /* HL_UNDERLINE */ {(int)KS_UCE, IF_EB("\033|8C", ESC_STR "|8C")}, /* HL_UNDERCURL */ {(int)KS_UCS, IF_EB("\033|8c", ESC_STR "|8c")}, /* HL_UNDERCURL */ {(int)KS_CZR, IF_EB("\033|4H", ESC_STR "|4H")}, /* HL_ITALIC */ {(int)KS_CZH, IF_EB("\033|4h", ESC_STR "|4h")}, /* HL_ITALIC */ {(int)KS_VB, IF_EB("\033|f", ESC_STR "|f")}, {(int)KS_MS, "y"}, {(int)KS_UT, "y"}, {(int)KS_LE, "\b"}, /* cursor-left = BS */ {(int)KS_ND, "\014"}, /* cursor-right = CTRL-L */ # ifdef TERMINFO {(int)KS_CM, IF_EB("\033|%p1%d;%p2%dM", ESC_STR "|%p1%d;%p2%dM")}, # else {(int)KS_CM, IF_EB("\033|%d;%dM", ESC_STR "|%d;%dM")}, # endif /* there are no key sequences here, the GUI sequences are recognized * in check_termcode() */ #endif #ifndef NO_BUILTIN_TCAPS # if defined(AMIGA) || defined(ALL_BUILTIN_TCAPS) /* * Amiga console window, default for Amiga */ {(int)KS_NAME, "amiga"}, {(int)KS_CE, "\033[K"}, {(int)KS_CD, "\033[J"}, {(int)KS_AL, "\033[L"}, # ifdef TERMINFO {(int)KS_CAL, "\033[%p1%dL"}, # else {(int)KS_CAL, "\033[%dL"}, # endif {(int)KS_DL, "\033[M"}, # ifdef TERMINFO {(int)KS_CDL, "\033[%p1%dM"}, # else {(int)KS_CDL, "\033[%dM"}, # endif {(int)KS_CL, "\014"}, {(int)KS_VI, "\033[0 p"}, {(int)KS_VE, "\033[1 p"}, {(int)KS_ME, "\033[0m"}, {(int)KS_MR, "\033[7m"}, {(int)KS_MD, "\033[1m"}, {(int)KS_SE, "\033[0m"}, {(int)KS_SO, "\033[33m"}, {(int)KS_US, "\033[4m"}, {(int)KS_UE, "\033[0m"}, {(int)KS_CZH, "\033[3m"}, {(int)KS_CZR, "\033[0m"}, #if defined(__MORPHOS__) || defined(__AROS__) {(int)KS_CCO, "8"}, /* allow 8 colors */ # ifdef TERMINFO {(int)KS_CAB, "\033[4%p1%dm"},/* set background color */ {(int)KS_CAF, "\033[3%p1%dm"},/* set foreground color */ # else {(int)KS_CAB, "\033[4%dm"}, /* set background color */ {(int)KS_CAF, "\033[3%dm"}, /* set foreground color */ # endif {(int)KS_OP, "\033[m"}, /* reset colors */ #endif {(int)KS_MS, "y"}, {(int)KS_UT, "y"}, /* guessed */ {(int)KS_LE, "\b"}, # ifdef TERMINFO {(int)KS_CM, "\033[%i%p1%d;%p2%dH"}, # else {(int)KS_CM, "\033[%i%d;%dH"}, # endif #if defined(__MORPHOS__) {(int)KS_SR, "\033M"}, #endif # ifdef TERMINFO {(int)KS_CRI, "\033[%p1%dC"}, # else {(int)KS_CRI, "\033[%dC"}, # endif {K_UP, "\233A"}, {K_DOWN, "\233B"}, {K_LEFT, "\233D"}, {K_RIGHT, "\233C"}, {K_S_UP, "\233T"}, {K_S_DOWN, "\233S"}, {K_S_LEFT, "\233 A"}, {K_S_RIGHT, "\233 @"}, {K_S_TAB, "\233Z"}, {K_F1, "\233\060~"},/* some compilers don't dig "\2330" */ {K_F2, "\233\061~"}, {K_F3, "\233\062~"}, {K_F4, "\233\063~"}, {K_F5, "\233\064~"}, {K_F6, "\233\065~"}, {K_F7, "\233\066~"}, {K_F8, "\233\067~"}, {K_F9, "\233\070~"}, {K_F10, "\233\071~"}, {K_S_F1, "\233\061\060~"}, {K_S_F2, "\233\061\061~"}, {K_S_F3, "\233\061\062~"}, {K_S_F4, "\233\061\063~"}, {K_S_F5, "\233\061\064~"}, {K_S_F6, "\233\061\065~"}, {K_S_F7, "\233\061\066~"}, {K_S_F8, "\233\061\067~"}, {K_S_F9, "\233\061\070~"}, {K_S_F10, "\233\061\071~"}, {K_HELP, "\233?~"}, {K_INS, "\233\064\060~"}, /* 101 key keyboard */ {K_PAGEUP, "\233\064\061~"}, /* 101 key keyboard */ {K_PAGEDOWN, "\233\064\062~"}, /* 101 key keyboard */ {K_HOME, "\233\064\064~"}, /* 101 key keyboard */ {K_END, "\233\064\065~"}, /* 101 key keyboard */ {BT_EXTRA_KEYS, ""}, {TERMCAP2KEY('#', '2'), "\233\065\064~"}, /* shifted home key */ {TERMCAP2KEY('#', '3'), "\233\065\060~"}, /* shifted insert key */ {TERMCAP2KEY('*', '7'), "\233\065\065~"}, /* shifted end key */ # endif # if defined(__BEOS__) || defined(ALL_BUILTIN_TCAPS) /* * almost standard ANSI terminal, default for bebox */ {(int)KS_NAME, "beos-ansi"}, {(int)KS_CE, "\033[K"}, {(int)KS_CD, "\033[J"}, {(int)KS_AL, "\033[L"}, # ifdef TERMINFO {(int)KS_CAL, "\033[%p1%dL"}, # else {(int)KS_CAL, "\033[%dL"}, # endif {(int)KS_DL, "\033[M"}, # ifdef TERMINFO {(int)KS_CDL, "\033[%p1%dM"}, # else {(int)KS_CDL, "\033[%dM"}, # endif #ifdef BEOS_PR_OR_BETTER # ifdef TERMINFO {(int)KS_CS, "\033[%i%p1%d;%p2%dr"}, # else {(int)KS_CS, "\033[%i%d;%dr"}, /* scroll region */ # endif #endif {(int)KS_CL, "\033[H\033[2J"}, #ifdef notyet {(int)KS_VI, "[VI]"}, /* cursor invisible, VT320: CSI ? 25 l */ {(int)KS_VE, "[VE]"}, /* cursor visible, VT320: CSI ? 25 h */ #endif {(int)KS_ME, "\033[m"}, /* normal mode */ {(int)KS_MR, "\033[7m"}, /* reverse */ {(int)KS_MD, "\033[1m"}, /* bold */ {(int)KS_SO, "\033[31m"}, /* standout mode: red */ {(int)KS_SE, "\033[m"}, /* standout end */ {(int)KS_CZH, "\033[35m"}, /* italic: purple */ {(int)KS_CZR, "\033[m"}, /* italic end */ {(int)KS_US, "\033[4m"}, /* underscore mode */ {(int)KS_UE, "\033[m"}, /* underscore end */ {(int)KS_CCO, "8"}, /* allow 8 colors */ # ifdef TERMINFO {(int)KS_CAB, "\033[4%p1%dm"},/* set background color */ {(int)KS_CAF, "\033[3%p1%dm"},/* set foreground color */ # else {(int)KS_CAB, "\033[4%dm"}, /* set background color */ {(int)KS_CAF, "\033[3%dm"}, /* set foreground color */ # endif {(int)KS_OP, "\033[m"}, /* reset colors */ {(int)KS_MS, "y"}, /* safe to move cur in reverse mode */ {(int)KS_UT, "y"}, /* guessed */ {(int)KS_LE, "\b"}, # ifdef TERMINFO {(int)KS_CM, "\033[%i%p1%d;%p2%dH"}, # else {(int)KS_CM, "\033[%i%d;%dH"}, # endif {(int)KS_SR, "\033M"}, # ifdef TERMINFO {(int)KS_CRI, "\033[%p1%dC"}, # else {(int)KS_CRI, "\033[%dC"}, # endif #if defined(BEOS_DR8) {(int)KS_DB, ""}, /* hack! see screen.c */ #endif {K_UP, "\033[A"}, {K_DOWN, "\033[B"}, {K_LEFT, "\033[D"}, {K_RIGHT, "\033[C"}, # endif # if defined(UNIX) || defined(ALL_BUILTIN_TCAPS) || defined(SOME_BUILTIN_TCAPS) || defined(__EMX__) /* * standard ANSI terminal, default for unix */ {(int)KS_NAME, "ansi"}, {(int)KS_CE, IF_EB("\033[K", ESC_STR "[K")}, {(int)KS_AL, IF_EB("\033[L", ESC_STR "[L")}, # ifdef TERMINFO {(int)KS_CAL, IF_EB("\033[%p1%dL", ESC_STR "[%p1%dL")}, # else {(int)KS_CAL, IF_EB("\033[%dL", ESC_STR "[%dL")}, # endif {(int)KS_DL, IF_EB("\033[M", ESC_STR "[M")}, # ifdef TERMINFO {(int)KS_CDL, IF_EB("\033[%p1%dM", ESC_STR "[%p1%dM")}, # else {(int)KS_CDL, IF_EB("\033[%dM", ESC_STR "[%dM")}, # endif {(int)KS_CL, IF_EB("\033[H\033[2J", ESC_STR "[H" ESC_STR_nc "[2J")}, {(int)KS_ME, IF_EB("\033[0m", ESC_STR "[0m")}, {(int)KS_MR, IF_EB("\033[7m", ESC_STR "[7m")}, {(int)KS_MS, "y"}, {(int)KS_UT, "y"}, /* guessed */ {(int)KS_LE, "\b"}, # ifdef TERMINFO {(int)KS_CM, IF_EB("\033[%i%p1%d;%p2%dH", ESC_STR "[%i%p1%d;%p2%dH")}, # else {(int)KS_CM, IF_EB("\033[%i%d;%dH", ESC_STR "[%i%d;%dH")}, # endif # ifdef TERMINFO {(int)KS_CRI, IF_EB("\033[%p1%dC", ESC_STR "[%p1%dC")}, # else {(int)KS_CRI, IF_EB("\033[%dC", ESC_STR "[%dC")}, # endif # endif # if defined(MSDOS) || defined(ALL_BUILTIN_TCAPS) || defined(__EMX__) /* * These codes are valid when nansi.sys or equivalent has been installed. * Function keys on a PC are preceded with a NUL. These are converted into * K_NUL '\316' in mch_inchar(), because we cannot handle NULs in key codes. * CTRL-arrow is used instead of SHIFT-arrow. */ #ifdef __EMX__ {(int)KS_NAME, "os2ansi"}, #else {(int)KS_NAME, "pcansi"}, {(int)KS_DL, "\033[M"}, {(int)KS_AL, "\033[L"}, #endif {(int)KS_CE, "\033[K"}, {(int)KS_CL, "\033[2J"}, {(int)KS_ME, "\033[0m"}, {(int)KS_MR, "\033[5m"}, /* reverse: black on lightgrey */ {(int)KS_MD, "\033[1m"}, /* bold: white text */ {(int)KS_SE, "\033[0m"}, /* standout end */ {(int)KS_SO, "\033[31m"}, /* standout: white on blue */ {(int)KS_CZH, "\033[34;43m"}, /* italic mode: blue text on yellow */ {(int)KS_CZR, "\033[0m"}, /* italic mode end */ {(int)KS_US, "\033[36;41m"}, /* underscore mode: cyan text on red */ {(int)KS_UE, "\033[0m"}, /* underscore mode end */ {(int)KS_CCO, "8"}, /* allow 8 colors */ # ifdef TERMINFO {(int)KS_CAB, "\033[4%p1%dm"},/* set background color */ {(int)KS_CAF, "\033[3%p1%dm"},/* set foreground color */ # else {(int)KS_CAB, "\033[4%dm"}, /* set background color */ {(int)KS_CAF, "\033[3%dm"}, /* set foreground color */ # endif {(int)KS_OP, "\033[0m"}, /* reset colors */ {(int)KS_MS, "y"}, {(int)KS_UT, "y"}, /* guessed */ {(int)KS_LE, "\b"}, # ifdef TERMINFO {(int)KS_CM, "\033[%i%p1%d;%p2%dH"}, # else {(int)KS_CM, "\033[%i%d;%dH"}, # endif # ifdef TERMINFO {(int)KS_CRI, "\033[%p1%dC"}, # else {(int)KS_CRI, "\033[%dC"}, # endif {K_UP, "\316H"}, {K_DOWN, "\316P"}, {K_LEFT, "\316K"}, {K_RIGHT, "\316M"}, {K_S_LEFT, "\316s"}, {K_S_RIGHT, "\316t"}, {K_F1, "\316;"}, {K_F2, "\316<"}, {K_F3, "\316="}, {K_F4, "\316>"}, {K_F5, "\316?"}, {K_F6, "\316@"}, {K_F7, "\316A"}, {K_F8, "\316B"}, {K_F9, "\316C"}, {K_F10, "\316D"}, {K_F11, "\316\205"}, /* guessed */ {K_F12, "\316\206"}, /* guessed */ {K_S_F1, "\316T"}, {K_S_F2, "\316U"}, {K_S_F3, "\316V"}, {K_S_F4, "\316W"}, {K_S_F5, "\316X"}, {K_S_F6, "\316Y"}, {K_S_F7, "\316Z"}, {K_S_F8, "\316["}, {K_S_F9, "\316\\"}, {K_S_F10, "\316]"}, {K_S_F11, "\316\207"}, /* guessed */ {K_S_F12, "\316\210"}, /* guessed */ {K_INS, "\316R"}, {K_DEL, "\316S"}, {K_HOME, "\316G"}, {K_END, "\316O"}, {K_PAGEDOWN, "\316Q"}, {K_PAGEUP, "\316I"}, # endif # if defined(MSDOS) /* * These codes are valid for the pc video. The entries that start with ESC | * are translated into conio calls in os_msdos.c. Default for MSDOS. */ {(int)KS_NAME, "pcterm"}, {(int)KS_CE, "\033|K"}, {(int)KS_AL, "\033|L"}, {(int)KS_DL, "\033|M"}, # ifdef TERMINFO {(int)KS_CS, "\033|%i%p1%d;%p2%dr"}, # ifdef FEAT_VERTSPLIT {(int)KS_CSV, "\033|%i%p1%d;%p2%dV"}, # endif # else {(int)KS_CS, "\033|%i%d;%dr"}, # ifdef FEAT_VERTSPLIT {(int)KS_CSV, "\033|%i%d;%dV"}, # endif # endif {(int)KS_CL, "\033|J"}, {(int)KS_ME, "\033|0m"}, /* normal */ {(int)KS_MR, "\033|112m"}, /* reverse: black on lightgrey */ {(int)KS_MD, "\033|15m"}, /* bold: white text */ {(int)KS_SE, "\033|0m"}, /* standout end */ {(int)KS_SO, "\033|31m"}, /* standout: white on blue */ {(int)KS_CZH, "\033|225m"}, /* italic mode: blue text on yellow */ {(int)KS_CZR, "\033|0m"}, /* italic mode end */ {(int)KS_US, "\033|67m"}, /* underscore mode: cyan text on red */ {(int)KS_UE, "\033|0m"}, /* underscore mode end */ {(int)KS_CCO, "16"}, /* allow 16 colors */ # ifdef TERMINFO {(int)KS_CAB, "\033|%p1%db"}, /* set background color */ {(int)KS_CAF, "\033|%p1%df"}, /* set foreground color */ # else {(int)KS_CAB, "\033|%db"}, /* set background color */ {(int)KS_CAF, "\033|%df"}, /* set foreground color */ # endif {(int)KS_MS, "y"}, {(int)KS_UT, "y"}, {(int)KS_LE, "\b"}, # ifdef TERMINFO {(int)KS_CM, "\033|%i%p1%d;%p2%dH"}, # else {(int)KS_CM, "\033|%i%d;%dH"}, # endif #ifdef DJGPP {(int)KS_VB, "\033|B"}, /* visual bell */ #endif {K_UP, "\316H"}, {K_DOWN, "\316P"}, {K_LEFT, "\316K"}, {K_RIGHT, "\316M"}, {K_S_LEFT, "\316s"}, {K_S_RIGHT, "\316t"}, {K_S_TAB, "\316\017"}, {K_F1, "\316;"}, {K_F2, "\316<"}, {K_F3, "\316="}, {K_F4, "\316>"}, {K_F5, "\316?"}, {K_F6, "\316@"}, {K_F7, "\316A"}, {K_F8, "\316B"}, {K_F9, "\316C"}, {K_F10, "\316D"}, {K_F11, "\316\205"}, {K_F12, "\316\206"}, {K_S_F1, "\316T"}, {K_S_F2, "\316U"}, {K_S_F3, "\316V"}, {K_S_F4, "\316W"}, {K_S_F5, "\316X"}, {K_S_F6, "\316Y"}, {K_S_F7, "\316Z"}, {K_S_F8, "\316["}, {K_S_F9, "\316\\"}, {K_S_F10, "\316]"}, {K_S_F11, "\316\207"}, {K_S_F12, "\316\210"}, {K_INS, "\316R"}, {K_DEL, "\316S"}, {K_HOME, "\316G"}, {K_END, "\316O"}, {K_PAGEDOWN, "\316Q"}, {K_PAGEUP, "\316I"}, {K_KPLUS, "\316N"}, {K_KMINUS, "\316J"}, {K_KMULTIPLY, "\3167"}, {K_K0, "\316\332"}, {K_K1, "\316\336"}, {K_K2, "\316\342"}, {K_K3, "\316\346"}, {K_K4, "\316\352"}, {K_K5, "\316\356"}, {K_K6, "\316\362"}, {K_K7, "\316\366"}, {K_K8, "\316\372"}, {K_K9, "\316\376"}, # endif # if defined(WIN3264) || defined(ALL_BUILTIN_TCAPS) || defined(__EMX__) /* * These codes are valid for the Win32 Console . The entries that start with * ESC | are translated into console calls in os_win32.c. The function keys * are also translated in os_win32.c. */ {(int)KS_NAME, "win32"}, {(int)KS_CE, "\033|K"}, /* clear to end of line */ {(int)KS_AL, "\033|L"}, /* add new blank line */ # ifdef TERMINFO {(int)KS_CAL, "\033|%p1%dL"}, /* add number of new blank lines */ # else {(int)KS_CAL, "\033|%dL"}, /* add number of new blank lines */ # endif {(int)KS_DL, "\033|M"}, /* delete line */ # ifdef TERMINFO {(int)KS_CDL, "\033|%p1%dM"}, /* delete number of lines */ # else {(int)KS_CDL, "\033|%dM"}, /* delete number of lines */ # endif {(int)KS_CL, "\033|J"}, /* clear screen */ {(int)KS_CD, "\033|j"}, /* clear to end of display */ {(int)KS_VI, "\033|v"}, /* cursor invisible */ {(int)KS_VE, "\033|V"}, /* cursor visible */ {(int)KS_ME, "\033|0m"}, /* normal */ {(int)KS_MR, "\033|112m"}, /* reverse: black on lightgray */ {(int)KS_MD, "\033|15m"}, /* bold: white on black */ #if 1 {(int)KS_SO, "\033|31m"}, /* standout: white on blue */ {(int)KS_SE, "\033|0m"}, /* standout end */ #else {(int)KS_SO, "\033|F"}, /* standout: high intensity */ {(int)KS_SE, "\033|f"}, /* standout end */ #endif {(int)KS_CZH, "\033|225m"}, /* italic: blue text on yellow */ {(int)KS_CZR, "\033|0m"}, /* italic end */ {(int)KS_US, "\033|67m"}, /* underscore: cyan text on red */ {(int)KS_UE, "\033|0m"}, /* underscore end */ {(int)KS_CCO, "16"}, /* allow 16 colors */ # ifdef TERMINFO {(int)KS_CAB, "\033|%p1%db"}, /* set background color */ {(int)KS_CAF, "\033|%p1%df"}, /* set foreground color */ # else {(int)KS_CAB, "\033|%db"}, /* set background color */ {(int)KS_CAF, "\033|%df"}, /* set foreground color */ # endif {(int)KS_MS, "y"}, /* save to move cur in reverse mode */ {(int)KS_UT, "y"}, {(int)KS_LE, "\b"}, # ifdef TERMINFO {(int)KS_CM, "\033|%i%p1%d;%p2%dH"},/* cursor motion */ # else {(int)KS_CM, "\033|%i%d;%dH"},/* cursor motion */ # endif {(int)KS_VB, "\033|B"}, /* visual bell */ {(int)KS_TI, "\033|S"}, /* put terminal in termcap mode */ {(int)KS_TE, "\033|E"}, /* out of termcap mode */ # ifdef TERMINFO {(int)KS_CS, "\033|%i%p1%d;%p2%dr"},/* scroll region */ # else {(int)KS_CS, "\033|%i%d;%dr"},/* scroll region */ # endif {K_UP, "\316H"}, {K_DOWN, "\316P"}, {K_LEFT, "\316K"}, {K_RIGHT, "\316M"}, {K_S_UP, "\316\304"}, {K_S_DOWN, "\316\317"}, {K_S_LEFT, "\316\311"}, {K_C_LEFT, "\316s"}, {K_S_RIGHT, "\316\313"}, {K_C_RIGHT, "\316t"}, {K_S_TAB, "\316\017"}, {K_F1, "\316;"}, {K_F2, "\316<"}, {K_F3, "\316="}, {K_F4, "\316>"}, {K_F5, "\316?"}, {K_F6, "\316@"}, {K_F7, "\316A"}, {K_F8, "\316B"}, {K_F9, "\316C"}, {K_F10, "\316D"}, {K_F11, "\316\205"}, {K_F12, "\316\206"}, {K_S_F1, "\316T"}, {K_S_F2, "\316U"}, {K_S_F3, "\316V"}, {K_S_F4, "\316W"}, {K_S_F5, "\316X"}, {K_S_F6, "\316Y"}, {K_S_F7, "\316Z"}, {K_S_F8, "\316["}, {K_S_F9, "\316\\"}, {K_S_F10, "\316]"}, {K_S_F11, "\316\207"}, {K_S_F12, "\316\210"}, {K_INS, "\316R"}, {K_DEL, "\316S"}, {K_HOME, "\316G"}, {K_S_HOME, "\316\302"}, {K_C_HOME, "\316w"}, {K_END, "\316O"}, {K_S_END, "\316\315"}, {K_C_END, "\316u"}, {K_PAGEDOWN, "\316Q"}, {K_PAGEUP, "\316I"}, {K_KPLUS, "\316N"}, {K_KMINUS, "\316J"}, {K_KMULTIPLY, "\316\067"}, {K_K0, "\316\332"}, {K_K1, "\316\336"}, {K_K2, "\316\342"}, {K_K3, "\316\346"}, {K_K4, "\316\352"}, {K_K5, "\316\356"}, {K_K6, "\316\362"}, {K_K7, "\316\366"}, {K_K8, "\316\372"}, {K_K9, "\316\376"}, # endif # if defined(VMS) || defined(ALL_BUILTIN_TCAPS) /* * VT320 is working as an ANSI terminal compatible DEC terminal. * (it covers VT1x0, VT2x0 and VT3x0 up to VT320 on VMS as well) * Note: K_F1...K_F5 are for internal use, should not be defined. * TODO:- rewrite ESC[ codes to CSI * - keyboard languages (CSI ? 26 n) */ {(int)KS_NAME, "vt320"}, {(int)KS_CE, IF_EB("\033[K", ESC_STR "[K")}, {(int)KS_AL, IF_EB("\033[L", ESC_STR "[L")}, # ifdef TERMINFO {(int)KS_CAL, IF_EB("\033[%p1%dL", ESC_STR "[%p1%dL")}, # else {(int)KS_CAL, IF_EB("\033[%dL", ESC_STR "[%dL")}, # endif {(int)KS_DL, IF_EB("\033[M", ESC_STR "[M")}, # ifdef TERMINFO {(int)KS_CDL, IF_EB("\033[%p1%dM", ESC_STR "[%p1%dM")}, # else {(int)KS_CDL, IF_EB("\033[%dM", ESC_STR "[%dM")}, # endif {(int)KS_CL, IF_EB("\033[H\033[2J", ESC_STR "[H" ESC_STR_nc "[2J")}, {(int)KS_CD, IF_EB("\033[J", ESC_STR "[J")}, {(int)KS_CCO, "8"}, /* allow 8 colors */ {(int)KS_ME, IF_EB("\033[0m", ESC_STR "[0m")}, {(int)KS_MR, IF_EB("\033[7m", ESC_STR "[7m")}, {(int)KS_MD, IF_EB("\033[1m", ESC_STR "[1m")}, /* bold mode */ {(int)KS_SE, IF_EB("\033[22m", ESC_STR "[22m")},/* normal mode */ {(int)KS_UE, IF_EB("\033[24m", ESC_STR "[24m")},/* exit underscore mode */ {(int)KS_US, IF_EB("\033[4m", ESC_STR "[4m")}, /* underscore mode */ {(int)KS_CZH, IF_EB("\033[34;43m", ESC_STR "[34;43m")}, /* italic mode: blue text on yellow */ {(int)KS_CZR, IF_EB("\033[0m", ESC_STR "[0m")}, /* italic mode end */ {(int)KS_CAB, IF_EB("\033[4%dm", ESC_STR "[4%dm")}, /* set background color (ANSI) */ {(int)KS_CAF, IF_EB("\033[3%dm", ESC_STR "[3%dm")}, /* set foreground color (ANSI) */ {(int)KS_CSB, IF_EB("\033[102;%dm", ESC_STR "[102;%dm")}, /* set screen background color */ {(int)KS_CSF, IF_EB("\033[101;%dm", ESC_STR "[101;%dm")}, /* set screen foreground color */ {(int)KS_MS, "y"}, {(int)KS_UT, "y"}, {(int)KS_LE, "\b"}, # ifdef TERMINFO {(int)KS_CM, IF_EB("\033[%i%p1%d;%p2%dH", ESC_STR "[%i%p1%d;%p2%dH")}, # else {(int)KS_CM, IF_EB("\033[%i%d;%dH", ESC_STR "[%i%d;%dH")}, # endif # ifdef TERMINFO {(int)KS_CRI, IF_EB("\033[%p1%dC", ESC_STR "[%p1%dC")}, # else {(int)KS_CRI, IF_EB("\033[%dC", ESC_STR "[%dC")}, # endif {K_UP, IF_EB("\033[A", ESC_STR "[A")}, {K_DOWN, IF_EB("\033[B", ESC_STR "[B")}, {K_RIGHT, IF_EB("\033[C", ESC_STR "[C")}, {K_LEFT, IF_EB("\033[D", ESC_STR "[D")}, {K_F1, IF_EB("\033[11~", ESC_STR "[11~")}, {K_F2, IF_EB("\033[12~", ESC_STR "[12~")}, {K_F3, IF_EB("\033[13~", ESC_STR "[13~")}, {K_F4, IF_EB("\033[14~", ESC_STR "[14~")}, {K_F5, IF_EB("\033[15~", ESC_STR "[15~")}, {K_F6, IF_EB("\033[17~", ESC_STR "[17~")}, {K_F7, IF_EB("\033[18~", ESC_STR "[18~")}, {K_F8, IF_EB("\033[19~", ESC_STR "[19~")}, {K_F9, IF_EB("\033[20~", ESC_STR "[20~")}, {K_F10, IF_EB("\033[21~", ESC_STR "[21~")}, {K_F11, IF_EB("\033[23~", ESC_STR "[23~")}, {K_F12, IF_EB("\033[24~", ESC_STR "[24~")}, {K_F13, IF_EB("\033[25~", ESC_STR "[25~")}, {K_F14, IF_EB("\033[26~", ESC_STR "[26~")}, {K_F15, IF_EB("\033[28~", ESC_STR "[28~")}, /* Help */ {K_F16, IF_EB("\033[29~", ESC_STR "[29~")}, /* Select */ {K_F17, IF_EB("\033[31~", ESC_STR "[31~")}, {K_F18, IF_EB("\033[32~", ESC_STR "[32~")}, {K_F19, IF_EB("\033[33~", ESC_STR "[33~")}, {K_F20, IF_EB("\033[34~", ESC_STR "[34~")}, {K_INS, IF_EB("\033[2~", ESC_STR "[2~")}, {K_DEL, IF_EB("\033[3~", ESC_STR "[3~")}, {K_HOME, IF_EB("\033[1~", ESC_STR "[1~")}, {K_END, IF_EB("\033[4~", ESC_STR "[4~")}, {K_PAGEUP, IF_EB("\033[5~", ESC_STR "[5~")}, {K_PAGEDOWN, IF_EB("\033[6~", ESC_STR "[6~")}, {K_KPLUS, IF_EB("\033Ok", ESC_STR "Ok")}, /* keypad plus */ {K_KMINUS, IF_EB("\033Om", ESC_STR "Om")}, /* keypad minus */ {K_KDIVIDE, IF_EB("\033Oo", ESC_STR "Oo")}, /* keypad / */ {K_KMULTIPLY, IF_EB("\033Oj", ESC_STR "Oj")}, /* keypad * */ {K_KENTER, IF_EB("\033OM", ESC_STR "OM")}, /* keypad Enter */ {K_BS, "\x7f"}, /* for some reason 0177 doesn't work */ # endif # if defined(ALL_BUILTIN_TCAPS) || defined(__MINT__) /* * Ordinary vt52 */ {(int)KS_NAME, "vt52"}, {(int)KS_CE, IF_EB("\033K", ESC_STR "K")}, {(int)KS_CD, IF_EB("\033J", ESC_STR "J")}, {(int)KS_CM, IF_EB("\033Y%+ %+ ", ESC_STR "Y%+ %+ ")}, {(int)KS_LE, "\b"}, # ifdef __MINT__ {(int)KS_AL, IF_EB("\033L", ESC_STR "L")}, {(int)KS_DL, IF_EB("\033M", ESC_STR "M")}, {(int)KS_CL, IF_EB("\033E", ESC_STR "E")}, {(int)KS_SR, IF_EB("\033I", ESC_STR "I")}, {(int)KS_VE, IF_EB("\033e", ESC_STR "e")}, {(int)KS_VI, IF_EB("\033f", ESC_STR "f")}, {(int)KS_SO, IF_EB("\033p", ESC_STR "p")}, {(int)KS_SE, IF_EB("\033q", ESC_STR "q")}, {K_UP, IF_EB("\033A", ESC_STR "A")}, {K_DOWN, IF_EB("\033B", ESC_STR "B")}, {K_LEFT, IF_EB("\033D", ESC_STR "D")}, {K_RIGHT, IF_EB("\033C", ESC_STR "C")}, {K_S_UP, IF_EB("\033a", ESC_STR "a")}, {K_S_DOWN, IF_EB("\033b", ESC_STR "b")}, {K_S_LEFT, IF_EB("\033d", ESC_STR "d")}, {K_S_RIGHT, IF_EB("\033c", ESC_STR "c")}, {K_F1, IF_EB("\033P", ESC_STR "P")}, {K_F2, IF_EB("\033Q", ESC_STR "Q")}, {K_F3, IF_EB("\033R", ESC_STR "R")}, {K_F4, IF_EB("\033S", ESC_STR "S")}, {K_F5, IF_EB("\033T", ESC_STR "T")}, {K_F6, IF_EB("\033U", ESC_STR "U")}, {K_F7, IF_EB("\033V", ESC_STR "V")}, {K_F8, IF_EB("\033W", ESC_STR "W")}, {K_F9, IF_EB("\033X", ESC_STR "X")}, {K_F10, IF_EB("\033Y", ESC_STR "Y")}, {K_S_F1, IF_EB("\033p", ESC_STR "p")}, {K_S_F2, IF_EB("\033q", ESC_STR "q")}, {K_S_F3, IF_EB("\033r", ESC_STR "r")}, {K_S_F4, IF_EB("\033s", ESC_STR "s")}, {K_S_F5, IF_EB("\033t", ESC_STR "t")}, {K_S_F6, IF_EB("\033u", ESC_STR "u")}, {K_S_F7, IF_EB("\033v", ESC_STR "v")}, {K_S_F8, IF_EB("\033w", ESC_STR "w")}, {K_S_F9, IF_EB("\033x", ESC_STR "x")}, {K_S_F10, IF_EB("\033y", ESC_STR "y")}, {K_INS, IF_EB("\033I", ESC_STR "I")}, {K_HOME, IF_EB("\033E", ESC_STR "E")}, {K_PAGEDOWN, IF_EB("\033b", ESC_STR "b")}, {K_PAGEUP, IF_EB("\033a", ESC_STR "a")}, # else {(int)KS_AL, IF_EB("\033T", ESC_STR "T")}, {(int)KS_DL, IF_EB("\033U", ESC_STR "U")}, {(int)KS_CL, IF_EB("\033H\033J", ESC_STR "H" ESC_STR_nc "J")}, {(int)KS_ME, IF_EB("\033SO", ESC_STR "SO")}, {(int)KS_MR, IF_EB("\033S2", ESC_STR "S2")}, {(int)KS_MS, "y"}, # endif # endif # if defined(UNIX) || defined(ALL_BUILTIN_TCAPS) || defined(SOME_BUILTIN_TCAPS) || defined(__EMX__) {(int)KS_NAME, "xterm"}, {(int)KS_CE, IF_EB("\033[K", ESC_STR "[K")}, {(int)KS_AL, IF_EB("\033[L", ESC_STR "[L")}, # ifdef TERMINFO {(int)KS_CAL, IF_EB("\033[%p1%dL", ESC_STR "[%p1%dL")}, # else {(int)KS_CAL, IF_EB("\033[%dL", ESC_STR "[%dL")}, # endif {(int)KS_DL, IF_EB("\033[M", ESC_STR "[M")}, # ifdef TERMINFO {(int)KS_CDL, IF_EB("\033[%p1%dM", ESC_STR "[%p1%dM")}, # else {(int)KS_CDL, IF_EB("\033[%dM", ESC_STR "[%dM")}, # endif # ifdef TERMINFO {(int)KS_CS, IF_EB("\033[%i%p1%d;%p2%dr", ESC_STR "[%i%p1%d;%p2%dr")}, # else {(int)KS_CS, IF_EB("\033[%i%d;%dr", ESC_STR "[%i%d;%dr")}, # endif {(int)KS_CL, IF_EB("\033[H\033[2J", ESC_STR "[H" ESC_STR_nc "[2J")}, {(int)KS_CD, IF_EB("\033[J", ESC_STR "[J")}, {(int)KS_ME, IF_EB("\033[m", ESC_STR "[m")}, {(int)KS_MR, IF_EB("\033[7m", ESC_STR "[7m")}, {(int)KS_MD, IF_EB("\033[1m", ESC_STR "[1m")}, {(int)KS_UE, IF_EB("\033[m", ESC_STR "[m")}, {(int)KS_US, IF_EB("\033[4m", ESC_STR "[4m")}, {(int)KS_MS, "y"}, {(int)KS_UT, "y"}, {(int)KS_LE, "\b"}, # ifdef TERMINFO {(int)KS_CM, IF_EB("\033[%i%p1%d;%p2%dH", ESC_STR "[%i%p1%d;%p2%dH")}, # else {(int)KS_CM, IF_EB("\033[%i%d;%dH", ESC_STR "[%i%d;%dH")}, # endif {(int)KS_SR, IF_EB("\033M", ESC_STR "M")}, # ifdef TERMINFO {(int)KS_CRI, IF_EB("\033[%p1%dC", ESC_STR "[%p1%dC")}, # else {(int)KS_CRI, IF_EB("\033[%dC", ESC_STR "[%dC")}, # endif {(int)KS_KS, IF_EB("\033[?1h\033=", ESC_STR "[?1h" ESC_STR_nc "=")}, {(int)KS_KE, IF_EB("\033[?1l\033>", ESC_STR "[?1l" ESC_STR_nc ">")}, # ifdef FEAT_XTERM_SAVE {(int)KS_TI, IF_EB("\0337\033[?47h", ESC_STR "7" ESC_STR_nc "[?47h")}, {(int)KS_TE, IF_EB("\033[2J\033[?47l\0338", ESC_STR "[2J" ESC_STR_nc "[?47l" ESC_STR_nc "8")}, # endif {(int)KS_CIS, IF_EB("\033]1;", ESC_STR "]1;")}, {(int)KS_CIE, "\007"}, {(int)KS_TS, IF_EB("\033]2;", ESC_STR "]2;")}, {(int)KS_FS, "\007"}, # ifdef TERMINFO {(int)KS_CWS, IF_EB("\033[8;%p1%d;%p2%dt", ESC_STR "[8;%p1%d;%p2%dt")}, {(int)KS_CWP, IF_EB("\033[3;%p1%d;%p2%dt", ESC_STR "[3;%p1%d;%p2%dt")}, # else {(int)KS_CWS, IF_EB("\033[8;%d;%dt", ESC_STR "[8;%d;%dt")}, {(int)KS_CWP, IF_EB("\033[3;%d;%dt", ESC_STR "[3;%d;%dt")}, # endif {(int)KS_CRV, IF_EB("\033[>c", ESC_STR "[>c")}, {K_UP, IF_EB("\033O*A", ESC_STR "O*A")}, {K_DOWN, IF_EB("\033O*B", ESC_STR "O*B")}, {K_RIGHT, IF_EB("\033O*C", ESC_STR "O*C")}, {K_LEFT, IF_EB("\033O*D", ESC_STR "O*D")}, /* An extra set of cursor keys for vt100 mode */ {K_XUP, IF_EB("\033[1;*A", ESC_STR "[1;*A")}, {K_XDOWN, IF_EB("\033[1;*B", ESC_STR "[1;*B")}, {K_XRIGHT, IF_EB("\033[1;*C", ESC_STR "[1;*C")}, {K_XLEFT, IF_EB("\033[1;*D", ESC_STR "[1;*D")}, /* An extra set of function keys for vt100 mode */ {K_XF1, IF_EB("\033O*P", ESC_STR "O*P")}, {K_XF2, IF_EB("\033O*Q", ESC_STR "O*Q")}, {K_XF3, IF_EB("\033O*R", ESC_STR "O*R")}, {K_XF4, IF_EB("\033O*S", ESC_STR "O*S")}, {K_F1, IF_EB("\033[11;*~", ESC_STR "[11;*~")}, {K_F2, IF_EB("\033[12;*~", ESC_STR "[12;*~")}, {K_F3, IF_EB("\033[13;*~", ESC_STR "[13;*~")}, {K_F4, IF_EB("\033[14;*~", ESC_STR "[14;*~")}, {K_F5, IF_EB("\033[15;*~", ESC_STR "[15;*~")}, {K_F6, IF_EB("\033[17;*~", ESC_STR "[17;*~")}, {K_F7, IF_EB("\033[18;*~", ESC_STR "[18;*~")}, {K_F8, IF_EB("\033[19;*~", ESC_STR "[19;*~")}, {K_F9, IF_EB("\033[20;*~", ESC_STR "[20;*~")}, {K_F10, IF_EB("\033[21;*~", ESC_STR "[21;*~")}, {K_F11, IF_EB("\033[23;*~", ESC_STR "[23;*~")}, {K_F12, IF_EB("\033[24;*~", ESC_STR "[24;*~")}, {K_S_TAB, IF_EB("\033[Z", ESC_STR "[Z")}, {K_HELP, IF_EB("\033[28;*~", ESC_STR "[28;*~")}, {K_UNDO, IF_EB("\033[26;*~", ESC_STR "[26;*~")}, {K_INS, IF_EB("\033[2;*~", ESC_STR "[2;*~")}, {K_HOME, IF_EB("\033[1;*H", ESC_STR "[1;*H")}, /* {K_S_HOME, IF_EB("\033O2H", ESC_STR "O2H")}, */ /* {K_C_HOME, IF_EB("\033O5H", ESC_STR "O5H")}, */ {K_KHOME, IF_EB("\033[1;*~", ESC_STR "[1;*~")}, {K_XHOME, IF_EB("\033O*H", ESC_STR "O*H")}, /* other Home */ {K_ZHOME, IF_EB("\033[7;*~", ESC_STR "[7;*~")}, /* other Home */ {K_END, IF_EB("\033[1;*F", ESC_STR "[1;*F")}, /* {K_S_END, IF_EB("\033O2F", ESC_STR "O2F")}, */ /* {K_C_END, IF_EB("\033O5F", ESC_STR "O5F")}, */ {K_KEND, IF_EB("\033[4;*~", ESC_STR "[4;*~")}, {K_XEND, IF_EB("\033O*F", ESC_STR "O*F")}, /* other End */ {K_ZEND, IF_EB("\033[8;*~", ESC_STR "[8;*~")}, {K_PAGEUP, IF_EB("\033[5;*~", ESC_STR "[5;*~")}, {K_PAGEDOWN, IF_EB("\033[6;*~", ESC_STR "[6;*~")}, {K_KPLUS, IF_EB("\033O*k", ESC_STR "O*k")}, /* keypad plus */ {K_KMINUS, IF_EB("\033O*m", ESC_STR "O*m")}, /* keypad minus */ {K_KDIVIDE, IF_EB("\033O*o", ESC_STR "O*o")}, /* keypad / */ {K_KMULTIPLY, IF_EB("\033O*j", ESC_STR "O*j")}, /* keypad * */ {K_KENTER, IF_EB("\033O*M", ESC_STR "O*M")}, /* keypad Enter */ {K_KPOINT, IF_EB("\033O*n", ESC_STR "O*n")}, /* keypad . */ {K_KDEL, IF_EB("\033[3;*~", ESC_STR "[3;*~")}, /* keypad Del */ {BT_EXTRA_KEYS, ""}, {TERMCAP2KEY('k', '0'), IF_EB("\033[10;*~", ESC_STR "[10;*~")}, /* F0 */ {TERMCAP2KEY('F', '3'), IF_EB("\033[25;*~", ESC_STR "[25;*~")}, /* F13 */ /* F14 and F15 are missing, because they send the same codes as the undo * and help key, although they don't work on all keyboards. */ {TERMCAP2KEY('F', '6'), IF_EB("\033[29;*~", ESC_STR "[29;*~")}, /* F16 */ {TERMCAP2KEY('F', '7'), IF_EB("\033[31;*~", ESC_STR "[31;*~")}, /* F17 */ {TERMCAP2KEY('F', '8'), IF_EB("\033[32;*~", ESC_STR "[32;*~")}, /* F18 */ {TERMCAP2KEY('F', '9'), IF_EB("\033[33;*~", ESC_STR "[33;*~")}, /* F19 */ {TERMCAP2KEY('F', 'A'), IF_EB("\033[34;*~", ESC_STR "[34;*~")}, /* F20 */ {TERMCAP2KEY('F', 'B'), IF_EB("\033[42;*~", ESC_STR "[42;*~")}, /* F21 */ {TERMCAP2KEY('F', 'C'), IF_EB("\033[43;*~", ESC_STR "[43;*~")}, /* F22 */ {TERMCAP2KEY('F', 'D'), IF_EB("\033[44;*~", ESC_STR "[44;*~")}, /* F23 */ {TERMCAP2KEY('F', 'E'), IF_EB("\033[45;*~", ESC_STR "[45;*~")}, /* F24 */ {TERMCAP2KEY('F', 'F'), IF_EB("\033[46;*~", ESC_STR "[46;*~")}, /* F25 */ {TERMCAP2KEY('F', 'G'), IF_EB("\033[47;*~", ESC_STR "[47;*~")}, /* F26 */ {TERMCAP2KEY('F', 'H'), IF_EB("\033[48;*~", ESC_STR "[48;*~")}, /* F27 */ {TERMCAP2KEY('F', 'I'), IF_EB("\033[49;*~", ESC_STR "[49;*~")}, /* F28 */ {TERMCAP2KEY('F', 'J'), IF_EB("\033[50;*~", ESC_STR "[50;*~")}, /* F29 */ {TERMCAP2KEY('F', 'K'), IF_EB("\033[51;*~", ESC_STR "[51;*~")}, /* F30 */ {TERMCAP2KEY('F', 'L'), IF_EB("\033[52;*~", ESC_STR "[52;*~")}, /* F31 */ {TERMCAP2KEY('F', 'M'), IF_EB("\033[53;*~", ESC_STR "[53;*~")}, /* F32 */ {TERMCAP2KEY('F', 'N'), IF_EB("\033[54;*~", ESC_STR "[54;*~")}, /* F33 */ {TERMCAP2KEY('F', 'O'), IF_EB("\033[55;*~", ESC_STR "[55;*~")}, /* F34 */ {TERMCAP2KEY('F', 'P'), IF_EB("\033[56;*~", ESC_STR "[56;*~")}, /* F35 */ {TERMCAP2KEY('F', 'Q'), IF_EB("\033[57;*~", ESC_STR "[57;*~")}, /* F36 */ {TERMCAP2KEY('F', 'R'), IF_EB("\033[58;*~", ESC_STR "[58;*~")}, /* F37 */ # endif # if defined(UNIX) || defined(ALL_BUILTIN_TCAPS) /* * iris-ansi for Silicon Graphics machines. */ {(int)KS_NAME, "iris-ansi"}, {(int)KS_CE, "\033[K"}, {(int)KS_CD, "\033[J"}, {(int)KS_AL, "\033[L"}, # ifdef TERMINFO {(int)KS_CAL, "\033[%p1%dL"}, # else {(int)KS_CAL, "\033[%dL"}, # endif {(int)KS_DL, "\033[M"}, # ifdef TERMINFO {(int)KS_CDL, "\033[%p1%dM"}, # else {(int)KS_CDL, "\033[%dM"}, # endif #if 0 /* The scroll region is not working as Vim expects. */ # ifdef TERMINFO {(int)KS_CS, "\033[%i%p1%d;%p2%dr"}, # else {(int)KS_CS, "\033[%i%d;%dr"}, # endif #endif {(int)KS_CL, "\033[H\033[2J"}, {(int)KS_VE, "\033[9/y\033[12/y"}, /* These aren't documented */ {(int)KS_VS, "\033[10/y\033[=1h\033[=2l"}, /* These aren't documented */ {(int)KS_TI, "\033[=6h"}, {(int)KS_TE, "\033[=6l"}, {(int)KS_SE, "\033[21;27m"}, {(int)KS_SO, "\033[1;7m"}, {(int)KS_ME, "\033[m"}, {(int)KS_MR, "\033[7m"}, {(int)KS_MD, "\033[1m"}, {(int)KS_CCO, "8"}, /* allow 8 colors */ {(int)KS_CZH, "\033[3m"}, /* italic mode on */ {(int)KS_CZR, "\033[23m"}, /* italic mode off */ {(int)KS_US, "\033[4m"}, /* underline on */ {(int)KS_UE, "\033[24m"}, /* underline off */ # ifdef TERMINFO {(int)KS_CAB, "\033[4%p1%dm"}, /* set background color (ANSI) */ {(int)KS_CAF, "\033[3%p1%dm"}, /* set foreground color (ANSI) */ {(int)KS_CSB, "\033[102;%p1%dm"}, /* set screen background color */ {(int)KS_CSF, "\033[101;%p1%dm"}, /* set screen foreground color */ # else {(int)KS_CAB, "\033[4%dm"}, /* set background color (ANSI) */ {(int)KS_CAF, "\033[3%dm"}, /* set foreground color (ANSI) */ {(int)KS_CSB, "\033[102;%dm"}, /* set screen background color */ {(int)KS_CSF, "\033[101;%dm"}, /* set screen foreground color */ # endif {(int)KS_MS, "y"}, /* guessed */ {(int)KS_UT, "y"}, /* guessed */ {(int)KS_LE, "\b"}, # ifdef TERMINFO {(int)KS_CM, "\033[%i%p1%d;%p2%dH"}, # else {(int)KS_CM, "\033[%i%d;%dH"}, # endif {(int)KS_SR, "\033M"}, # ifdef TERMINFO {(int)KS_CRI, "\033[%p1%dC"}, # else {(int)KS_CRI, "\033[%dC"}, # endif {(int)KS_CIS, "\033P3.y"}, {(int)KS_CIE, "\234"}, /* ST "String Terminator" */ {(int)KS_TS, "\033P1.y"}, {(int)KS_FS, "\234"}, /* ST "String Terminator" */ # ifdef TERMINFO {(int)KS_CWS, "\033[203;%p1%d;%p2%d/y"}, {(int)KS_CWP, "\033[205;%p1%d;%p2%d/y"}, # else {(int)KS_CWS, "\033[203;%d;%d/y"}, {(int)KS_CWP, "\033[205;%d;%d/y"}, # endif {K_UP, "\033[A"}, {K_DOWN, "\033[B"}, {K_LEFT, "\033[D"}, {K_RIGHT, "\033[C"}, {K_S_UP, "\033[161q"}, {K_S_DOWN, "\033[164q"}, {K_S_LEFT, "\033[158q"}, {K_S_RIGHT, "\033[167q"}, {K_F1, "\033[001q"}, {K_F2, "\033[002q"}, {K_F3, "\033[003q"}, {K_F4, "\033[004q"}, {K_F5, "\033[005q"}, {K_F6, "\033[006q"}, {K_F7, "\033[007q"}, {K_F8, "\033[008q"}, {K_F9, "\033[009q"}, {K_F10, "\033[010q"}, {K_F11, "\033[011q"}, {K_F12, "\033[012q"}, {K_S_F1, "\033[013q"}, {K_S_F2, "\033[014q"}, {K_S_F3, "\033[015q"}, {K_S_F4, "\033[016q"}, {K_S_F5, "\033[017q"}, {K_S_F6, "\033[018q"}, {K_S_F7, "\033[019q"}, {K_S_F8, "\033[020q"}, {K_S_F9, "\033[021q"}, {K_S_F10, "\033[022q"}, {K_S_F11, "\033[023q"}, {K_S_F12, "\033[024q"}, {K_INS, "\033[139q"}, {K_HOME, "\033[H"}, {K_END, "\033[146q"}, {K_PAGEUP, "\033[150q"}, {K_PAGEDOWN, "\033[154q"}, # endif # if defined(DEBUG) || defined(ALL_BUILTIN_TCAPS) /* * for debugging */ {(int)KS_NAME, "debug"}, {(int)KS_CE, "[CE]"}, {(int)KS_CD, "[CD]"}, {(int)KS_AL, "[AL]"}, # ifdef TERMINFO {(int)KS_CAL, "[CAL%p1%d]"}, # else {(int)KS_CAL, "[CAL%d]"}, # endif {(int)KS_DL, "[DL]"}, # ifdef TERMINFO {(int)KS_CDL, "[CDL%p1%d]"}, # else {(int)KS_CDL, "[CDL%d]"}, # endif # ifdef TERMINFO {(int)KS_CS, "[%p1%dCS%p2%d]"}, # else {(int)KS_CS, "[%dCS%d]"}, # endif # ifdef FEAT_VERTSPLIT # ifdef TERMINFO {(int)KS_CSV, "[%p1%dCSV%p2%d]"}, # else {(int)KS_CSV, "[%dCSV%d]"}, # endif # endif # ifdef TERMINFO {(int)KS_CAB, "[CAB%p1%d]"}, {(int)KS_CAF, "[CAF%p1%d]"}, {(int)KS_CSB, "[CSB%p1%d]"}, {(int)KS_CSF, "[CSF%p1%d]"}, # else {(int)KS_CAB, "[CAB%d]"}, {(int)KS_CAF, "[CAF%d]"}, {(int)KS_CSB, "[CSB%d]"}, {(int)KS_CSF, "[CSF%d]"}, # endif {(int)KS_OP, "[OP]"}, {(int)KS_LE, "[LE]"}, {(int)KS_CL, "[CL]"}, {(int)KS_VI, "[VI]"}, {(int)KS_VE, "[VE]"}, {(int)KS_VS, "[VS]"}, {(int)KS_ME, "[ME]"}, {(int)KS_MR, "[MR]"}, {(int)KS_MB, "[MB]"}, {(int)KS_MD, "[MD]"}, {(int)KS_SE, "[SE]"}, {(int)KS_SO, "[SO]"}, {(int)KS_UE, "[UE]"}, {(int)KS_US, "[US]"}, {(int)KS_UCE, "[UCE]"}, {(int)KS_UCS, "[UCS]"}, {(int)KS_MS, "[MS]"}, {(int)KS_UT, "[UT]"}, # ifdef TERMINFO {(int)KS_CM, "[%p1%dCM%p2%d]"}, # else {(int)KS_CM, "[%dCM%d]"}, # endif {(int)KS_SR, "[SR]"}, # ifdef TERMINFO {(int)KS_CRI, "[CRI%p1%d]"}, # else {(int)KS_CRI, "[CRI%d]"}, # endif {(int)KS_VB, "[VB]"}, {(int)KS_KS, "[KS]"}, {(int)KS_KE, "[KE]"}, {(int)KS_TI, "[TI]"}, {(int)KS_TE, "[TE]"}, {(int)KS_CIS, "[CIS]"}, {(int)KS_CIE, "[CIE]"}, {(int)KS_TS, "[TS]"}, {(int)KS_FS, "[FS]"}, # ifdef TERMINFO {(int)KS_CWS, "[%p1%dCWS%p2%d]"}, {(int)KS_CWP, "[%p1%dCWP%p2%d]"}, # else {(int)KS_CWS, "[%dCWS%d]"}, {(int)KS_CWP, "[%dCWP%d]"}, # endif {(int)KS_CRV, "[CRV]"}, {K_UP, "[KU]"}, {K_DOWN, "[KD]"}, {K_LEFT, "[KL]"}, {K_RIGHT, "[KR]"}, {K_XUP, "[xKU]"}, {K_XDOWN, "[xKD]"}, {K_XLEFT, "[xKL]"}, {K_XRIGHT, "[xKR]"}, {K_S_UP, "[S-KU]"}, {K_S_DOWN, "[S-KD]"}, {K_S_LEFT, "[S-KL]"}, {K_C_LEFT, "[C-KL]"}, {K_S_RIGHT, "[S-KR]"}, {K_C_RIGHT, "[C-KR]"}, {K_F1, "[F1]"}, {K_XF1, "[xF1]"}, {K_F2, "[F2]"}, {K_XF2, "[xF2]"}, {K_F3, "[F3]"}, {K_XF3, "[xF3]"}, {K_F4, "[F4]"}, {K_XF4, "[xF4]"}, {K_F5, "[F5]"}, {K_F6, "[F6]"}, {K_F7, "[F7]"}, {K_F8, "[F8]"}, {K_F9, "[F9]"}, {K_F10, "[F10]"}, {K_F11, "[F11]"}, {K_F12, "[F12]"}, {K_S_F1, "[S-F1]"}, {K_S_XF1, "[S-xF1]"}, {K_S_F2, "[S-F2]"}, {K_S_XF2, "[S-xF2]"}, {K_S_F3, "[S-F3]"}, {K_S_XF3, "[S-xF3]"}, {K_S_F4, "[S-F4]"}, {K_S_XF4, "[S-xF4]"}, {K_S_F5, "[S-F5]"}, {K_S_F6, "[S-F6]"}, {K_S_F7, "[S-F7]"}, {K_S_F8, "[S-F8]"}, {K_S_F9, "[S-F9]"}, {K_S_F10, "[S-F10]"}, {K_S_F11, "[S-F11]"}, {K_S_F12, "[S-F12]"}, {K_HELP, "[HELP]"}, {K_UNDO, "[UNDO]"}, {K_BS, "[BS]"}, {K_INS, "[INS]"}, {K_KINS, "[KINS]"}, {K_DEL, "[DEL]"}, {K_KDEL, "[KDEL]"}, {K_HOME, "[HOME]"}, {K_S_HOME, "[C-HOME]"}, {K_C_HOME, "[C-HOME]"}, {K_KHOME, "[KHOME]"}, {K_XHOME, "[XHOME]"}, {K_ZHOME, "[ZHOME]"}, {K_END, "[END]"}, {K_S_END, "[C-END]"}, {K_C_END, "[C-END]"}, {K_KEND, "[KEND]"}, {K_XEND, "[XEND]"}, {K_ZEND, "[ZEND]"}, {K_PAGEUP, "[PAGEUP]"}, {K_PAGEDOWN, "[PAGEDOWN]"}, {K_KPAGEUP, "[KPAGEUP]"}, {K_KPAGEDOWN, "[KPAGEDOWN]"}, {K_MOUSE, "[MOUSE]"}, {K_KPLUS, "[KPLUS]"}, {K_KMINUS, "[KMINUS]"}, {K_KDIVIDE, "[KDIVIDE]"}, {K_KMULTIPLY, "[KMULTIPLY]"}, {K_KENTER, "[KENTER]"}, {K_KPOINT, "[KPOINT]"}, {K_K0, "[K0]"}, {K_K1, "[K1]"}, {K_K2, "[K2]"}, {K_K3, "[K3]"}, {K_K4, "[K4]"}, {K_K5, "[K5]"}, {K_K6, "[K6]"}, {K_K7, "[K7]"}, {K_K8, "[K8]"}, {K_K9, "[K9]"}, # endif #endif /* NO_BUILTIN_TCAPS */ /* * The most minimal terminal: only clear screen and cursor positioning * Always included. */ {(int)KS_NAME, "dumb"}, {(int)KS_CL, "\014"}, #ifdef TERMINFO {(int)KS_CM, IF_EB("\033[%i%p1%d;%p2%dH", ESC_STR "[%i%p1%d;%p2%dH")}, #else {(int)KS_CM, IF_EB("\033[%i%d;%dH", ESC_STR "[%i%d;%dH")}, #endif /* * end marker */ {(int)KS_NAME, NULL} }; /* end of builtin_termcaps */ /* * DEFAULT_TERM is used, when no terminal is specified with -T option or $TERM. */ #ifdef AMIGA # define DEFAULT_TERM (char_u *)"amiga" #endif #ifdef MSWIN # define DEFAULT_TERM (char_u *)"win32" #endif #ifdef MSDOS # define DEFAULT_TERM (char_u *)"pcterm" #endif #if defined(UNIX) && !defined(__MINT__) # define DEFAULT_TERM (char_u *)"ansi" #endif #ifdef __MINT__ # define DEFAULT_TERM (char_u *)"vt52" #endif #ifdef __EMX__ # define DEFAULT_TERM (char_u *)"os2ansi" #endif #ifdef VMS # define DEFAULT_TERM (char_u *)"vt320" #endif #ifdef __BEOS__ # undef DEFAULT_TERM # define DEFAULT_TERM (char_u *)"beos-ansi" #endif #ifndef DEFAULT_TERM # define DEFAULT_TERM (char_u *)"dumb" #endif /* * Term_strings contains currently used terminal output strings. * It is initialized with the default values by parse_builtin_tcap(). * The values can be changed by setting the option with the same name. */ char_u *(term_strings[(int)KS_LAST + 1]); static int need_gather = FALSE; /* need to fill termleader[] */ static char_u termleader[256 + 1]; /* for check_termcode() */ #ifdef FEAT_TERMRESPONSE static int check_for_codes = FALSE; /* check for key code response */ #endif static struct builtin_term * find_builtin_term(term) char_u *term; { struct builtin_term *p; p = builtin_termcaps; while (p->bt_string != NULL) { if (p->bt_entry == (int)KS_NAME) { #ifdef UNIX if (STRCMP(p->bt_string, "iris-ansi") == 0 && vim_is_iris(term)) return p; else if (STRCMP(p->bt_string, "xterm") == 0 && vim_is_xterm(term)) return p; else #endif #ifdef VMS if (STRCMP(p->bt_string, "vt320") == 0 && vim_is_vt300(term)) return p; else #endif if (STRCMP(term, p->bt_string) == 0) return p; } ++p; } return p; } /* * Parsing of the builtin termcap entries. * Caller should check if 'name' is a valid builtin term. * The terminal's name is not set, as this is already done in termcapinit(). */ static void parse_builtin_tcap(term) char_u *term; { struct builtin_term *p; char_u name[2]; int term_8bit; p = find_builtin_term(term); term_8bit = term_is_8bit(term); /* Do not parse if builtin term not found */ if (p->bt_string == NULL) return; for (++p; p->bt_entry != (int)KS_NAME && p->bt_entry != BT_EXTRA_KEYS; ++p) { if ((int)p->bt_entry >= 0) /* KS_xx entry */ { /* Only set the value if it wasn't set yet. */ if (term_strings[p->bt_entry] == NULL || term_strings[p->bt_entry] == empty_option) { /* 8bit terminal: use CSI instead of <Esc>[ */ if (term_8bit && term_7to8bit((char_u *)p->bt_string) != 0) { char_u *s, *t; s = vim_strsave((char_u *)p->bt_string); if (s != NULL) { for (t = s; *t; ++t) if (term_7to8bit(t)) { *t = term_7to8bit(t); STRCPY(t + 1, t + 2); } term_strings[p->bt_entry] = s; set_term_option_alloced(&term_strings[p->bt_entry]); } } else term_strings[p->bt_entry] = (char_u *)p->bt_string; } } else { name[0] = KEY2TERMCAP0((int)p->bt_entry); name[1] = KEY2TERMCAP1((int)p->bt_entry); if (find_termcode(name) == NULL) add_termcode(name, (char_u *)p->bt_string, term_8bit); } } } #if defined(HAVE_TGETENT) || defined(FEAT_TERMRESPONSE) static void set_color_count __ARGS((int nr)); /* * Set number of colors. * Store it as a number in t_colors. * Store it as a string in T_CCO (using nr_colors[]). */ static void set_color_count(nr) int nr; { char_u nr_colors[20]; /* string for number of colors */ t_colors = nr; if (t_colors > 1) sprintf((char *)nr_colors, "%d", t_colors); else *nr_colors = NUL; set_string_option_direct((char_u *)"t_Co", -1, nr_colors, OPT_FREE, 0); } #endif #ifdef HAVE_TGETENT static char *(key_names[]) = { #ifdef FEAT_TERMRESPONSE /* Do this one first, it may cause a screen redraw. */ "Co", #endif "ku", "kd", "kr", "kl", # ifdef ARCHIE "su", "sd", /* Termcap code made up! */ # endif "#2", "#4", "%i", "*7", "k1", "k2", "k3", "k4", "k5", "k6", "k7", "k8", "k9", "k;", "F1", "F2", "%1", "&8", "kb", "kI", "kD", "kh", "@7", "kP", "kN", "K1", "K3", "K4", "K5", "kB", NULL }; #endif /* * Set terminal options for terminal "term". * Return OK if terminal 'term' was found in a termcap, FAIL otherwise. * * While doing this, until ttest(), some options may be NULL, be careful. */ int set_termname(term) char_u *term; { struct builtin_term *termp; #ifdef HAVE_TGETENT int builtin_first = p_tbi; int try; int termcap_cleared = FALSE; #endif int width = 0, height = 0; char_u *error_msg = NULL; char_u *bs_p, *del_p; /* In silect mode (ex -s) we don't use the 'term' option. */ if (silent_mode) return OK; detected_8bit = FALSE; /* reset 8-bit detection */ if (term_is_builtin(term)) { term += 8; #ifdef HAVE_TGETENT builtin_first = 1; #endif } /* * If HAVE_TGETENT is not defined, only the builtin termcap is used, otherwise: * If builtin_first is TRUE: * 0. try builtin termcap * 1. try external termcap * 2. if both fail default to a builtin terminal * If builtin_first is FALSE: * 1. try external termcap * 2. try builtin termcap, if both fail default to a builtin terminal */ #ifdef HAVE_TGETENT for (try = builtin_first ? 0 : 1; try < 3; ++try) { /* * Use external termcap */ if (try == 1) { char_u *p; static char_u tstrbuf[TBUFSZ]; int i; char_u tbuf[TBUFSZ]; char_u *tp; static struct { enum SpecialKey dest; /* index in term_strings[] */ char *name; /* termcap name for string */ } string_names[] = { {KS_CE, "ce"}, {KS_AL, "al"}, {KS_CAL,"AL"}, {KS_DL, "dl"}, {KS_CDL,"DL"}, {KS_CS, "cs"}, {KS_CL, "cl"}, {KS_CD, "cd"}, {KS_VI, "vi"}, {KS_VE, "ve"}, {KS_MB, "mb"}, {KS_VS, "vs"}, {KS_ME, "me"}, {KS_MR, "mr"}, {KS_MD, "md"}, {KS_SE, "se"}, {KS_SO, "so"}, {KS_CZH,"ZH"}, {KS_CZR,"ZR"}, {KS_UE, "ue"}, {KS_US, "us"}, {KS_UCE, "Ce"}, {KS_UCS, "Cs"}, {KS_CM, "cm"}, {KS_SR, "sr"}, {KS_CRI,"RI"}, {KS_VB, "vb"}, {KS_KS, "ks"}, {KS_KE, "ke"}, {KS_TI, "ti"}, {KS_TE, "te"}, {KS_BC, "bc"}, {KS_CSB,"Sb"}, {KS_CSF,"Sf"}, {KS_CAB,"AB"}, {KS_CAF,"AF"}, {KS_LE, "le"}, {KS_ND, "nd"}, {KS_OP, "op"}, {KS_CRV, "RV"}, {KS_CIS, "IS"}, {KS_CIE, "IE"}, {KS_TS, "ts"}, {KS_FS, "fs"}, {KS_CWP, "WP"}, {KS_CWS, "WS"}, {KS_CSI, "SI"}, {KS_CEI, "EI"}, {(enum SpecialKey)0, NULL} }; /* * If the external termcap does not have a matching entry, try the * builtin ones. */ if ((error_msg = tgetent_error(tbuf, term)) == NULL) { tp = tstrbuf; if (!termcap_cleared) { clear_termoptions(); /* clear old options */ termcap_cleared = TRUE; } /* get output strings */ for (i = 0; string_names[i].name != NULL; ++i) { if (term_str(string_names[i].dest) == NULL || term_str(string_names[i].dest) == empty_option) term_str(string_names[i].dest) = TGETSTR(string_names[i].name, &tp); } /* tgetflag() returns 1 if the flag is present, 0 if not and * possibly -1 if the flag doesn't exist. */ if ((T_MS == NULL || T_MS == empty_option) && tgetflag("ms") > 0) T_MS = (char_u *)"y"; if ((T_XS == NULL || T_XS == empty_option) && tgetflag("xs") > 0) T_XS = (char_u *)"y"; if ((T_DB == NULL || T_DB == empty_option) && tgetflag("db") > 0) T_DB = (char_u *)"y"; if ((T_DA == NULL || T_DA == empty_option) && tgetflag("da") > 0) T_DA = (char_u *)"y"; if ((T_UT == NULL || T_UT == empty_option) && tgetflag("ut") > 0) T_UT = (char_u *)"y"; /* * get key codes */ for (i = 0; key_names[i] != NULL; ++i) { if (find_termcode((char_u *)key_names[i]) == NULL) { p = TGETSTR(key_names[i], &tp); /* if cursor-left == backspace, ignore it (televideo * 925) */ if (p != NULL && (*p != Ctrl_H || key_names[i][0] != 'k' || key_names[i][1] != 'l')) add_termcode((char_u *)key_names[i], p, FALSE); } } if (height == 0) height = tgetnum("li"); if (width == 0) width = tgetnum("co"); /* * Get number of colors (if not done already). */ if (term_str(KS_CCO) == NULL || term_str(KS_CCO) == empty_option) set_color_count(tgetnum("Co")); # ifndef hpux BC = (char *)TGETSTR("bc", &tp); UP = (char *)TGETSTR("up", &tp); p = TGETSTR("pc", &tp); if (p) PC = *p; # endif /* hpux */ } } else /* try == 0 || try == 2 */ #endif /* HAVE_TGETENT */ /* * Use builtin termcap */ { #ifdef HAVE_TGETENT /* * If builtin termcap was already used, there is no need to search * for the builtin termcap again, quit now. */ if (try == 2 && builtin_first && termcap_cleared) break; #endif /* * search for 'term' in builtin_termcaps[] */ termp = find_builtin_term(term); if (termp->bt_string == NULL) /* did not find it */ { #ifdef HAVE_TGETENT /* * If try == 0, first try the external termcap. If that is not * found we'll get back here with try == 2. * If termcap_cleared is set we used the external termcap, * don't complain about not finding the term in the builtin * termcap. */ if (try == 0) /* try external one */ continue; if (termcap_cleared) /* found in external termcap */ break; #endif mch_errmsg("\r\n"); if (error_msg != NULL) { mch_errmsg((char *)error_msg); mch_errmsg("\r\n"); } mch_errmsg("'"); mch_errmsg((char *)term); mch_errmsg(_("' not known. Available builtin terminals are:")); mch_errmsg("\r\n"); for (termp = &(builtin_termcaps[0]); termp->bt_string != NULL; ++termp) { if (termp->bt_entry == (int)KS_NAME) { #ifdef HAVE_TGETENT mch_errmsg(" builtin_"); #else mch_errmsg(" "); #endif mch_errmsg(termp->bt_string); mch_errmsg("\r\n"); } } /* when user typed :set term=xxx, quit here */ if (starting != NO_SCREEN) { screen_start(); /* don't know where cursor is now */ wait_return(TRUE); return FAIL; } term = DEFAULT_TERM; mch_errmsg(_("defaulting to '")); mch_errmsg((char *)term); mch_errmsg("'\r\n"); if (emsg_silent == 0) { screen_start(); /* don't know where cursor is now */ out_flush(); ui_delay(2000L, TRUE); } set_string_option_direct((char_u *)"term", -1, term, OPT_FREE, 0); display_errors(); } out_flush(); #ifdef HAVE_TGETENT if (!termcap_cleared) { #endif clear_termoptions(); /* clear old options */ #ifdef HAVE_TGETENT termcap_cleared = TRUE; } #endif parse_builtin_tcap(term); #ifdef FEAT_GUI if (term_is_gui(term)) { out_flush(); gui_init(); /* If starting the GUI failed, don't do any of the other * things for this terminal */ if (!gui.in_use) return FAIL; #ifdef HAVE_TGETENT break; /* don't try using external termcap */ #endif } #endif /* FEAT_GUI */ } #ifdef HAVE_TGETENT } #endif /* * special: There is no info in the termcap about whether the cursor * positioning is relative to the start of the screen or to the start of the * scrolling region. We just guess here. Only msdos pcterm is known to do it * relative. */ if (STRCMP(term, "pcterm") == 0) T_CCS = (char_u *)"yes"; else T_CCS = empty_option; #ifdef UNIX /* * Any "stty" settings override the default for t_kb from the termcap. * This is in os_unix.c, because it depends a lot on the version of unix that * is being used. * Don't do this when the GUI is active, it uses "t_kb" and "t_kD" directly. */ #ifdef FEAT_GUI if (!gui.in_use) #endif get_stty(); #endif /* * If the termcap has no entry for 'bs' and/or 'del' and the ioctl() also * didn't work, use the default CTRL-H * The default for t_kD is DEL, unless t_kb is DEL. * The vim_strsave'd strings are probably lost forever, well it's only two * bytes. Don't do this when the GUI is active, it uses "t_kb" and "t_kD" * directly. */ #ifdef FEAT_GUI if (!gui.in_use) #endif { bs_p = find_termcode((char_u *)"kb"); del_p = find_termcode((char_u *)"kD"); if (bs_p == NULL || *bs_p == NUL) add_termcode((char_u *)"kb", (bs_p = (char_u *)CTRL_H_STR), FALSE); if ((del_p == NULL || *del_p == NUL) && (bs_p == NULL || *bs_p != DEL)) add_termcode((char_u *)"kD", (char_u *)DEL_STR, FALSE); } #if defined(UNIX) || defined(VMS) term_is_xterm = vim_is_xterm(term); #endif #ifdef FEAT_MOUSE # if defined(UNIX) || defined(VMS) # ifdef FEAT_MOUSE_TTY /* * For Unix, set the 'ttymouse' option to the type of mouse to be used. * The termcode for the mouse is added as a side effect in option.c. */ { char_u *p; p = (char_u *)""; # ifdef FEAT_MOUSE_XTERM # ifdef FEAT_CLIPBOARD # ifdef FEAT_GUI if (!gui.in_use) # endif clip_init(FALSE); # endif if (use_xterm_like_mouse(term)) { if (use_xterm_mouse()) p = NULL; /* keep existing value, might be "xterm2" */ else p = (char_u *)"xterm"; } # endif if (p != NULL) set_option_value((char_u *)"ttym", 0L, p, 0); if (p == NULL # ifdef FEAT_GUI || gui.in_use # endif ) check_mouse_termcode(); /* set mouse termcode anyway */ } # endif # else set_mouse_termcode(KS_MOUSE, (char_u *)"\233M"); # endif #endif /* FEAT_MOUSE */ #ifdef FEAT_SNIFF { char_u name[2]; name[0] = (int)KS_EXTRA; name[1] = (int)KE_SNIFF; add_termcode(name, (char_u *)"\233sniff", FALSE); } #endif #ifdef USE_TERM_CONSOLE /* DEFAULT_TERM indicates that it is the machine console. */ if (STRCMP(term, DEFAULT_TERM) != 0) term_console = FALSE; else { term_console = TRUE; # ifdef AMIGA win_resize_on(); /* enable window resizing reports */ # endif } #endif #if defined(UNIX) || defined(VMS) /* * 'ttyfast' is default on for xterm, iris-ansi and a few others. */ if (vim_is_fastterm(term)) p_tf = TRUE; #endif #ifdef USE_TERM_CONSOLE /* * 'ttyfast' is default on consoles */ if (term_console) p_tf = TRUE; #endif ttest(TRUE); /* make sure we have a valid set of terminal codes */ full_screen = TRUE; /* we can use termcap codes from now on */ set_term_defaults(); /* use current values as defaults */ #ifdef FEAT_TERMRESPONSE crv_status = CRV_GET; /* Get terminal version later */ #endif /* * Initialize the terminal with the appropriate termcap codes. * Set the mouse and window title if possible. * Don't do this when starting, need to parse the .vimrc first, because it * may redefine t_TI etc. */ if (starting != NO_SCREEN) { starttermcap(); /* may change terminal mode */ #ifdef FEAT_MOUSE setmouse(); /* may start using the mouse */ #endif #ifdef FEAT_TITLE maketitle(); /* may display window title */ #endif } /* display initial screen after ttest() checking. jw. */ if (width <= 0 || height <= 0) { /* termcap failed to report size */ /* set defaults, in case ui_get_shellsize() also fails */ width = 80; #if defined(MSDOS) || defined(WIN3264) height = 25; /* console is often 25 lines */ #else height = 24; /* most terminals are 24 lines */ #endif } set_shellsize(width, height, FALSE); /* may change Rows */ if (starting != NO_SCREEN) { if (scroll_region) scroll_region_reset(); /* In case Rows changed */ check_map_keycodes(); /* check mappings for terminal codes used */ #ifdef FEAT_AUTOCMD { buf_T *old_curbuf; /* * Execute the TermChanged autocommands for each buffer that is * loaded. */ old_curbuf = curbuf; for (curbuf = firstbuf; curbuf != NULL; curbuf = curbuf->b_next) { if (curbuf->b_ml.ml_mfp != NULL) apply_autocmds(EVENT_TERMCHANGED, NULL, NULL, FALSE, curbuf); } if (buf_valid(old_curbuf)) curbuf = old_curbuf; } #endif } #ifdef FEAT_TERMRESPONSE may_req_termresponse(); #endif return OK; } #if defined(FEAT_MOUSE) || defined(PROTO) # ifdef FEAT_MOUSE_TTY # define HMT_NORMAL 1 # define HMT_NETTERM 2 # define HMT_DEC 4 # define HMT_JSBTERM 8 # define HMT_PTERM 16 # define HMT_URXVT 32 static int has_mouse_termcode = 0; # endif # if (!defined(UNIX) || defined(FEAT_MOUSE_TTY)) || defined(PROTO) void set_mouse_termcode(n, s) int n; /* KS_MOUSE, KS_NETTERM_MOUSE or KS_DEC_MOUSE */ char_u *s; { char_u name[2]; name[0] = n; name[1] = KE_FILLER; add_termcode(name, s, FALSE); # ifdef FEAT_MOUSE_TTY # ifdef FEAT_MOUSE_JSB if (n == KS_JSBTERM_MOUSE) has_mouse_termcode |= HMT_JSBTERM; else # endif # ifdef FEAT_MOUSE_NET if (n == KS_NETTERM_MOUSE) has_mouse_termcode |= HMT_NETTERM; else # endif # ifdef FEAT_MOUSE_DEC if (n == KS_DEC_MOUSE) has_mouse_termcode |= HMT_DEC; else # endif # ifdef FEAT_MOUSE_PTERM if (n == KS_PTERM_MOUSE) has_mouse_termcode |= HMT_PTERM; else # endif # ifdef FEAT_MOUSE_URXVT if (n == KS_URXVT_MOUSE) has_mouse_termcode |= HMT_URXVT; else # endif has_mouse_termcode |= HMT_NORMAL; # endif } # endif # if ((defined(UNIX) || defined(VMS) || defined(OS2)) \ && defined(FEAT_MOUSE_TTY)) || defined(PROTO) void del_mouse_termcode(n) int n; /* KS_MOUSE, KS_NETTERM_MOUSE or KS_DEC_MOUSE */ { char_u name[2]; name[0] = n; name[1] = KE_FILLER; del_termcode(name); # ifdef FEAT_MOUSE_TTY # ifdef FEAT_MOUSE_JSB if (n == KS_JSBTERM_MOUSE) has_mouse_termcode &= ~HMT_JSBTERM; else # endif # ifdef FEAT_MOUSE_NET if (n == KS_NETTERM_MOUSE) has_mouse_termcode &= ~HMT_NETTERM; else # endif # ifdef FEAT_MOUSE_DEC if (n == KS_DEC_MOUSE) has_mouse_termcode &= ~HMT_DEC; else # endif # ifdef FEAT_MOUSE_PTERM if (n == KS_PTERM_MOUSE) has_mouse_termcode &= ~HMT_PTERM; else # endif # ifdef FEAT_MOUSE_URXVT if (n == KS_URXVT_MOUSE) has_mouse_termcode &= ~HMT_URXVT; else # endif has_mouse_termcode &= ~HMT_NORMAL; # endif } # endif #endif #ifdef HAVE_TGETENT /* * Call tgetent() * Return error message if it fails, NULL if it's OK. */ static char_u * tgetent_error(tbuf, term) char_u *tbuf; char_u *term; { int i; i = TGETENT(tbuf, term); if (i < 0 /* -1 is always an error */ # ifdef TGETENT_ZERO_ERR || i == 0 /* sometimes zero is also an error */ # endif ) { /* On FreeBSD tputs() gets a SEGV after a tgetent() which fails. Call * tgetent() with the always existing "dumb" entry to avoid a crash or * hang. */ (void)TGETENT(tbuf, "dumb"); if (i < 0) # ifdef TGETENT_ZERO_ERR return (char_u *)_("E557: Cannot open termcap file"); if (i == 0) # endif #ifdef TERMINFO return (char_u *)_("E558: Terminal entry not found in terminfo"); #else return (char_u *)_("E559: Terminal entry not found in termcap"); #endif } return NULL; } /* * Some versions of tgetstr() have been reported to return -1 instead of NULL. * Fix that here. */ static char_u * vim_tgetstr(s, pp) char *s; char_u **pp; { char *p; p = tgetstr(s, (char **)pp); if (p == (char *)-1) p = NULL; return (char_u *)p; } #endif /* HAVE_TGETENT */ #if defined(HAVE_TGETENT) && (defined(UNIX) || defined(__EMX__) || defined(VMS) || defined(MACOS_X)) /* * Get Columns and Rows from the termcap. Used after a window signal if the * ioctl() fails. It doesn't make sense to call tgetent each time if the "co" * and "li" entries never change. But on some systems this works. * Errors while getting the entries are ignored. */ void getlinecol(cp, rp) long *cp; /* pointer to columns */ long *rp; /* pointer to rows */ { char_u tbuf[TBUFSZ]; if (T_NAME != NULL && *T_NAME != NUL && tgetent_error(tbuf, T_NAME) == NULL) { if (*cp == 0) *cp = tgetnum("co"); if (*rp == 0) *rp = tgetnum("li"); } } #endif /* defined(HAVE_TGETENT) && defined(UNIX) */ /* * Get a string entry from the termcap and add it to the list of termcodes. * Used for <t_xx> special keys. * Give an error message for failure when not sourcing. * If force given, replace an existing entry. * Return FAIL if the entry was not found, OK if the entry was added. */ int add_termcap_entry(name, force) char_u *name; int force; { char_u *term; int key; struct builtin_term *termp; #ifdef HAVE_TGETENT char_u *string; int i; int builtin_first; char_u tbuf[TBUFSZ]; char_u tstrbuf[TBUFSZ]; char_u *tp = tstrbuf; char_u *error_msg = NULL; #endif /* * If the GUI is running or will start in a moment, we only support the keys * that the GUI can produce. */ #ifdef FEAT_GUI if (gui.in_use || gui.starting) return gui_mch_haskey(name); #endif if (!force && find_termcode(name) != NULL) /* it's already there */ return OK; term = T_NAME; if (term == NULL || *term == NUL) /* 'term' not defined yet */ return FAIL; if (term_is_builtin(term)) /* name starts with "builtin_" */ { term += 8; #ifdef HAVE_TGETENT builtin_first = TRUE; #endif } #ifdef HAVE_TGETENT else builtin_first = p_tbi; #endif #ifdef HAVE_TGETENT /* * We can get the entry from the builtin termcap and from the external one. * If 'ttybuiltin' is on or the terminal name starts with "builtin_", try * builtin termcap first. * If 'ttybuiltin' is off, try external termcap first. */ for (i = 0; i < 2; ++i) { if (!builtin_first == i) #endif /* * Search in builtin termcap */ { termp = find_builtin_term(term); if (termp->bt_string != NULL) /* found it */ { key = TERMCAP2KEY(name[0], name[1]); while (termp->bt_entry != (int)KS_NAME) { if ((int)termp->bt_entry == key) { add_termcode(name, (char_u *)termp->bt_string, term_is_8bit(term)); return OK; } ++termp; } } } #ifdef HAVE_TGETENT else /* * Search in external termcap */ { error_msg = tgetent_error(tbuf, term); if (error_msg == NULL) { string = TGETSTR((char *)name, &tp); if (string != NULL && *string != NUL) { add_termcode(name, string, FALSE); return OK; } } } } #endif if (sourcing_name == NULL) { #ifdef HAVE_TGETENT if (error_msg != NULL) EMSG(error_msg); else #endif EMSG2(_("E436: No \"%s\" entry in termcap"), name); } return FAIL; } static int term_is_builtin(name) char_u *name; { return (STRNCMP(name, "builtin_", (size_t)8) == 0); } /* * Return TRUE if terminal "name" uses CSI instead of <Esc>[. * Assume that the terminal is using 8-bit controls when the name contains * "8bit", like in "xterm-8bit". */ int term_is_8bit(name) char_u *name; { return (detected_8bit || strstr((char *)name, "8bit") != NULL); } /* * Translate terminal control chars from 7-bit to 8-bit: * <Esc>[ -> CSI * <Esc>] -> <M-C-]> * <Esc>O -> <M-C-O> */ static int term_7to8bit(p) char_u *p; { if (*p == ESC) { if (p[1] == '[') return CSI; if (p[1] == ']') return 0x9d; if (p[1] == 'O') return 0x8f; } return 0; } #ifdef FEAT_GUI int term_is_gui(name) char_u *name; { return (STRCMP(name, "builtin_gui") == 0 || STRCMP(name, "gui") == 0); } #endif #if !defined(HAVE_TGETENT) || defined(AMIGA) || defined(PROTO) char_u * tltoa(i) unsigned long i; { static char_u buf[16]; char_u *p; p = buf + 15; *p = '\0'; do { --p; *p = (char_u) (i % 10 + '0'); i /= 10; } while (i > 0 && p > buf); return p; } #endif #ifndef HAVE_TGETENT /* * minimal tgoto() implementation. * no padding and we only parse for %i %d and %+char */ static char *tgoto __ARGS((char *, int, int)); static char * tgoto(cm, x, y) char *cm; int x, y; { static char buf[30]; char *p, *s, *e; if (!cm) return "OOPS"; e = buf + 29; for (s = buf; s < e && *cm; cm++) { if (*cm != '%') { *s++ = *cm; continue; } switch (*++cm) { case 'd': p = (char *)tltoa((unsigned long)y); y = x; while (*p) *s++ = *p++; break; case 'i': x++; y++; break; case '+': *s++ = (char)(*++cm + y); y = x; break; case '%': *s++ = *cm; break; default: return "OOPS"; } } *s = '\0'; return buf; } #endif /* HAVE_TGETENT */ /* * Set the terminal name and initialize the terminal options. * If "name" is NULL or empty, get the terminal name from the environment. * If that fails, use the default terminal name. */ void termcapinit(name) char_u *name; { char_u *term; if (name != NULL && *name == NUL) name = NULL; /* empty name is equal to no name */ term = name; #ifdef __BEOS__ /* * TERM environment variable is normally set to 'ansi' on the Bebox; * Since the BeBox doesn't quite support full ANSI yet, we use our * own custom 'ansi-beos' termcap instead, unless the -T option has * been given on the command line. */ if (term == NULL && strcmp((char *)mch_getenv((char_u *)"TERM"), "ansi") == 0) term = DEFAULT_TERM; #endif #ifndef MSWIN if (term == NULL) term = mch_getenv((char_u *)"TERM"); #endif if (term == NULL || *term == NUL) term = DEFAULT_TERM; set_string_option_direct((char_u *)"term", -1, term, OPT_FREE, 0); /* Set the default terminal name. */ set_string_default("term", term); set_string_default("ttytype", term); /* * Avoid using "term" here, because the next mch_getenv() may overwrite it. */ set_termname(T_NAME != NULL ? T_NAME : term); } /* * the number of calls to ui_write is reduced by using the buffer "out_buf" */ #ifdef DOS16 # define OUT_SIZE 255 /* only have 640K total... */ #else # ifdef FEAT_GUI_W16 # define OUT_SIZE 1023 /* Save precious 1K near data */ # else # define OUT_SIZE 2047 # endif #endif /* Add one to allow mch_write() in os_win32.c to append a NUL */ static char_u out_buf[OUT_SIZE + 1]; static int out_pos = 0; /* number of chars in out_buf */ /* * out_flush(): flush the output buffer */ void out_flush() { int len; if (out_pos != 0) { /* set out_pos to 0 before ui_write, to avoid recursiveness */ len = out_pos; out_pos = 0; ui_write(out_buf, len); } } #if defined(FEAT_MBYTE) || defined(PROTO) /* * Sometimes a byte out of a multi-byte character is written with out_char(). * To avoid flushing half of the character, call this function first. */ void out_flush_check() { if (enc_dbcs != 0 && out_pos >= OUT_SIZE - MB_MAXBYTES) out_flush(); } #endif #ifdef FEAT_GUI /* * out_trash(): Throw away the contents of the output buffer */ void out_trash() { out_pos = 0; } #endif /* * out_char(c): put a byte into the output buffer. * Flush it if it becomes full. * This should not be used for outputting text on the screen (use functions * like msg_puts() and screen_putchar() for that). */ void out_char(c) unsigned c; { #if defined(UNIX) || defined(VMS) || defined(AMIGA) || defined(MACOS_X_UNIX) if (c == '\n') /* turn LF into CR-LF (CRMOD doesn't seem to do this) */ out_char('\r'); #endif out_buf[out_pos++] = c; /* For testing we flush each time. */ if (out_pos >= OUT_SIZE || p_wd) out_flush(); } static void out_char_nf __ARGS((unsigned)); /* * out_char_nf(c): like out_char(), but don't flush when p_wd is set */ static void out_char_nf(c) unsigned c; { #if defined(UNIX) || defined(VMS) || defined(AMIGA) || defined(MACOS_X_UNIX) if (c == '\n') /* turn LF into CR-LF (CRMOD doesn't seem to do this) */ out_char_nf('\r'); #endif out_buf[out_pos++] = c; if (out_pos >= OUT_SIZE) out_flush(); } #if defined(FEAT_TITLE) || defined(FEAT_MOUSE_TTY) || defined(FEAT_GUI) \ || defined(FEAT_TERMRESPONSE) || defined(PROTO) /* * A never-padding out_str. * use this whenever you don't want to run the string through tputs. * tputs above is harmless, but tputs from the termcap library * is likely to strip off leading digits, that it mistakes for padding * information, and "%i", "%d", etc. * This should only be used for writing terminal codes, not for outputting * normal text (use functions like msg_puts() and screen_putchar() for that). */ void out_str_nf(s) char_u *s; { if (out_pos > OUT_SIZE - 20) /* avoid terminal strings being split up */ out_flush(); while (*s) out_char_nf(*s++); /* For testing we write one string at a time. */ if (p_wd) out_flush(); } #endif /* * out_str(s): Put a character string a byte at a time into the output buffer. * If HAVE_TGETENT is defined use the termcap parser. (jw) * This should only be used for writing terminal codes, not for outputting * normal text (use functions like msg_puts() and screen_putchar() for that). */ void out_str(s) char_u *s; { if (s != NULL && *s) { #ifdef FEAT_GUI /* Don't use tputs() when GUI is used, ncurses crashes. */ if (gui.in_use) { out_str_nf(s); return; } #endif /* avoid terminal strings being split up */ if (out_pos > OUT_SIZE - 20) out_flush(); #ifdef HAVE_TGETENT tputs((char *)s, 1, TPUTSFUNCAST out_char_nf); #else while (*s) out_char_nf(*s++); #endif /* For testing we write one string at a time. */ if (p_wd) out_flush(); } } /* * cursor positioning using termcap parser. (jw) */ void term_windgoto(row, col) int row; int col; { OUT_STR(tgoto((char *)T_CM, col, row)); } void term_cursor_right(i) int i; { OUT_STR(tgoto((char *)T_CRI, 0, i)); } void term_append_lines(line_count) int line_count; { OUT_STR(tgoto((char *)T_CAL, 0, line_count)); } void term_delete_lines(line_count) int line_count; { OUT_STR(tgoto((char *)T_CDL, 0, line_count)); } #if defined(HAVE_TGETENT) || defined(PROTO) void term_set_winpos(x, y) int x; int y; { /* Can't handle a negative value here */ if (x < 0) x = 0; if (y < 0) y = 0; OUT_STR(tgoto((char *)T_CWP, y, x)); } void term_set_winsize(width, height) int width; int height; { OUT_STR(tgoto((char *)T_CWS, height, width)); } #endif void term_fg_color(n) int n; { /* Use "AF" termcap entry if present, "Sf" entry otherwise */ if (*T_CAF) term_color(T_CAF, n); else if (*T_CSF) term_color(T_CSF, n); } void term_bg_color(n) int n; { /* Use "AB" termcap entry if present, "Sb" entry otherwise */ if (*T_CAB) term_color(T_CAB, n); else if (*T_CSB) term_color(T_CSB, n); } static void term_color(s, n) char_u *s; int n; { char buf[20]; int i = 2; /* index in s[] just after <Esc>[ or CSI */ /* Special handling of 16 colors, because termcap can't handle it */ /* Also accept "\e[3%dm" for TERMINFO, it is sometimes used */ /* Also accept CSI instead of <Esc>[ */ if (n >= 8 && t_colors >= 16 && ((s[0] == ESC && s[1] == '[') || (s[0] == CSI && (i = 1) == 1)) && s[i] != NUL && (STRCMP(s + i + 1, "%p1%dm") == 0 || STRCMP(s + i + 1, "%dm") == 0) && (s[i] == '3' || s[i] == '4')) { sprintf(buf, #ifdef TERMINFO "%s%s%%p1%%dm", #else "%s%s%%dm", #endif i == 2 ? IF_EB("\033[", ESC_STR "[") : "\233", s[i] == '3' ? (n >= 16 ? "38;5;" : "9") : (n >= 16 ? "48;5;" : "10")); OUT_STR(tgoto(buf, 0, n >= 16 ? n : n - 8)); } else OUT_STR(tgoto((char *)s, 0, n)); } #if (defined(FEAT_TITLE) && (defined(UNIX) || defined(OS2) || defined(VMS) || defined(MACOS_X))) || defined(PROTO) /* * Generic function to set window title, using t_ts and t_fs. */ void term_settitle(title) char_u *title; { /* t_ts takes one argument: column in status line */ OUT_STR(tgoto((char *)T_TS, 0, 0)); /* set title start */ out_str_nf(title); out_str(T_FS); /* set title end */ out_flush(); } #endif /* * Make sure we have a valid set or terminal options. * Replace all entries that are NULL by empty_option */ void ttest(pairs) int pairs; { check_options(); /* make sure no options are NULL */ /* * MUST have "cm": cursor motion. */ if (*T_CM == NUL) EMSG(_("E437: terminal capability \"cm\" required")); /* * if "cs" defined, use a scroll region, it's faster. */ if (*T_CS != NUL) scroll_region = TRUE; else scroll_region = FALSE; if (pairs) { /* * optional pairs */ /* TP goes to normal mode for TI (invert) and TB (bold) */ if (*T_ME == NUL) T_ME = T_MR = T_MD = T_MB = empty_option; if (*T_SO == NUL || *T_SE == NUL) T_SO = T_SE = empty_option; if (*T_US == NUL || *T_UE == NUL) T_US = T_UE = empty_option; if (*T_CZH == NUL || *T_CZR == NUL) T_CZH = T_CZR = empty_option; /* T_VE is needed even though T_VI is not defined */ if (*T_VE == NUL) T_VI = empty_option; /* if 'mr' or 'me' is not defined use 'so' and 'se' */ if (*T_ME == NUL) { T_ME = T_SE; T_MR = T_SO; T_MD = T_SO; } /* if 'so' or 'se' is not defined use 'mr' and 'me' */ if (*T_SO == NUL) { T_SE = T_ME; if (*T_MR == NUL) T_SO = T_MD; else T_SO = T_MR; } /* if 'ZH' or 'ZR' is not defined use 'mr' and 'me' */ if (*T_CZH == NUL) { T_CZR = T_ME; if (*T_MR == NUL) T_CZH = T_MD; else T_CZH = T_MR; } /* "Sb" and "Sf" come in pairs */ if (*T_CSB == NUL || *T_CSF == NUL) { T_CSB = empty_option; T_CSF = empty_option; } /* "AB" and "AF" come in pairs */ if (*T_CAB == NUL || *T_CAF == NUL) { T_CAB = empty_option; T_CAF = empty_option; } /* if 'Sb' and 'AB' are not defined, reset "Co" */ if (*T_CSB == NUL && *T_CAB == NUL) free_one_termoption(T_CCO); /* Set 'weirdinvert' according to value of 't_xs' */ p_wiv = (*T_XS != NUL); } need_gather = TRUE; /* Set t_colors to the value of t_Co. */ t_colors = atoi((char *)T_CCO); } #if (defined(FEAT_GUI) && (defined(FEAT_MENU) || !defined(USE_ON_FLY_SCROLL))) \ || defined(PROTO) /* * Represent the given long_u as individual bytes, with the most significant * byte first, and store them in dst. */ void add_long_to_buf(val, dst) long_u val; char_u *dst; { int i; int shift; for (i = 1; i <= (int)sizeof(long_u); i++) { shift = 8 * (sizeof(long_u) - i); dst[i - 1] = (char_u) ((val >> shift) & 0xff); } } static int get_long_from_buf __ARGS((char_u *buf, long_u *val)); /* * Interpret the next string of bytes in buf as a long integer, with the most * significant byte first. Note that it is assumed that buf has been through * inchar(), so that NUL and K_SPECIAL will be represented as three bytes each. * Puts result in val, and returns the number of bytes read from buf * (between sizeof(long_u) and 2 * sizeof(long_u)), or -1 if not enough bytes * were present. */ static int get_long_from_buf(buf, val) char_u *buf; long_u *val; { int len; char_u bytes[sizeof(long_u)]; int i; int shift; *val = 0; len = get_bytes_from_buf(buf, bytes, (int)sizeof(long_u)); if (len != -1) { for (i = 0; i < (int)sizeof(long_u); i++) { shift = 8 * (sizeof(long_u) - 1 - i); *val += (long_u)bytes[i] << shift; } } return len; } #endif #if defined(FEAT_GUI) \ || (defined(FEAT_MOUSE) && (!defined(UNIX) || defined(FEAT_MOUSE_XTERM) \ || defined(FEAT_MOUSE_GPM) || defined(FEAT_SYSMOUSE))) /* * Read the next num_bytes bytes from buf, and store them in bytes. Assume * that buf has been through inchar(). Returns the actual number of bytes used * from buf (between num_bytes and num_bytes*2), or -1 if not enough bytes were * available. */ static int get_bytes_from_buf(buf, bytes, num_bytes) char_u *buf; char_u *bytes; int num_bytes; { int len = 0; int i; char_u c; for (i = 0; i < num_bytes; i++) { if ((c = buf[len++]) == NUL) return -1; if (c == K_SPECIAL) { if (buf[len] == NUL || buf[len + 1] == NUL) /* cannot happen? */ return -1; if (buf[len++] == (int)KS_ZERO) c = NUL; ++len; /* skip KE_FILLER */ /* else it should be KS_SPECIAL, and c already equals K_SPECIAL */ } else if (c == CSI && buf[len] == KS_EXTRA && buf[len + 1] == (int)KE_CSI) /* CSI is stored as CSI KS_SPECIAL KE_CSI to avoid confusion with * the start of a special key, see add_to_input_buf_csi(). */ len += 2; bytes[i] = c; } return len; } #endif /* * Check if the new shell size is valid, correct it if it's too small. */ void check_shellsize() { if (Columns < MIN_COLUMNS) Columns = MIN_COLUMNS; if (Rows < min_rows()) /* need room for one window and command line */ Rows = min_rows(); } /* * Invoked just before the screen structures are going to be (re)allocated. */ void win_new_shellsize() { static int old_Rows = 0; static int old_Columns = 0; if (old_Rows != Rows || old_Columns != Columns) ui_new_shellsize(); if (old_Rows != Rows) { /* if 'window' uses the whole screen, keep it using that */ if (p_window == old_Rows - 1 || old_Rows == 0) p_window = Rows - 1; old_Rows = Rows; shell_new_rows(); /* update window sizes */ } if (old_Columns != Columns) { old_Columns = Columns; #ifdef FEAT_VERTSPLIT shell_new_columns(); /* update window sizes */ #endif } } /* * Call this function when the Vim shell has been resized in any way. * Will obtain the current size and redraw (also when size didn't change). */ void shell_resized() { set_shellsize(0, 0, FALSE); } /* * Check if the shell size changed. Handle a resize. * When the size didn't change, nothing happens. */ void shell_resized_check() { int old_Rows = Rows; int old_Columns = Columns; if (!exiting) { (void)ui_get_shellsize(); check_shellsize(); if (old_Rows != Rows || old_Columns != Columns) shell_resized(); } } /* * Set size of the Vim shell. * If 'mustset' is TRUE, we must set Rows and Columns, do not get the real * window size (this is used for the :win command). * If 'mustset' is FALSE, we may try to get the real window size and if * it fails use 'width' and 'height'. */ void set_shellsize(width, height, mustset) int width, height; int mustset; { static int busy = FALSE; /* * Avoid recursiveness, can happen when setting the window size causes * another window-changed signal. */ if (busy) return; if (width < 0 || height < 0) /* just checking... */ return; if (State == HITRETURN || State == SETWSIZE) { /* postpone the resizing */ State = SETWSIZE; return; } /* curwin->w_buffer can be NULL when we are closing a window and the * buffer has already been closed and removing a scrollbar causes a resize * event. Don't resize then, it will happen after entering another buffer. */ if (curwin->w_buffer == NULL) return; ++busy; #ifdef AMIGA out_flush(); /* must do this before mch_get_shellsize() for some obscure reason */ #endif if (mustset || (ui_get_shellsize() == FAIL && height != 0)) { Rows = height; Columns = width; check_shellsize(); ui_set_shellsize(mustset); } else check_shellsize(); /* The window layout used to be adjusted here, but it now happens in * screenalloc() (also invoked from screenclear()). That is because the * "busy" check above may skip this, but not screenalloc(). */ if (State != ASKMORE && State != EXTERNCMD && State != CONFIRM) screenclear(); else screen_start(); /* don't know where cursor is now */ if (starting != NO_SCREEN) { #ifdef FEAT_TITLE maketitle(); #endif changed_line_abv_curs(); invalidate_botline(); /* * We only redraw when it's needed: * - While at the more prompt or executing an external command, don't * redraw, but position the cursor. * - While editing the command line, only redraw that. * - in Ex mode, don't redraw anything. * - Otherwise, redraw right now, and position the cursor. * Always need to call update_screen() or screenalloc(), to make * sure Rows/Columns and the size of ScreenLines[] is correct! */ if (State == ASKMORE || State == EXTERNCMD || State == CONFIRM || exmode_active) { screenalloc(FALSE); repeat_message(); } else { #ifdef FEAT_SCROLLBIND if (curwin->w_p_scb) do_check_scrollbind(TRUE); #endif if (State & CMDLINE) { update_screen(NOT_VALID); redrawcmdline(); } else { update_topline(); #if defined(FEAT_INS_EXPAND) if (pum_visible()) { redraw_later(NOT_VALID); ins_compl_show_pum(); /* This includes the redraw. */ } else #endif update_screen(NOT_VALID); if (redrawing()) setcursor(); } } cursor_on(); /* redrawing may have switched it off */ } out_flush(); --busy; } /* * Set the terminal to TMODE_RAW (for Normal mode) or TMODE_COOK (for external * commands and Ex mode). */ void settmode(tmode) int tmode; { #ifdef FEAT_GUI /* don't set the term where gvim was started to any mode */ if (gui.in_use) return; #endif if (full_screen) { /* * When returning after calling a shell we want to really set the * terminal to raw mode, even though we think it already is, because * the shell program may have reset the terminal mode. * When we think the terminal is normal, don't try to set it to * normal again, because that causes problems (logout!) on some * machines. */ if (tmode != TMODE_COOK || cur_tmode != TMODE_COOK) { #ifdef FEAT_TERMRESPONSE # ifdef FEAT_GUI if (!gui.in_use && !gui.starting) # endif { /* May need to check for T_CRV response and termcodes, it * doesn't work in Cooked mode, an external program may get * them. */ if (tmode != TMODE_RAW && crv_status == CRV_SENT) (void)vpeekc_nomap(); check_for_codes_from_term(); } #endif #ifdef FEAT_MOUSE_TTY if (tmode != TMODE_RAW) mch_setmouse(FALSE); /* switch mouse off */ #endif out_flush(); mch_settmode(tmode); /* machine specific function */ cur_tmode = tmode; #ifdef FEAT_MOUSE if (tmode == TMODE_RAW) setmouse(); /* may switch mouse on */ #endif out_flush(); } #ifdef FEAT_TERMRESPONSE may_req_termresponse(); #endif } } void starttermcap() { if (full_screen && !termcap_active) { out_str(T_TI); /* start termcap mode */ out_str(T_KS); /* start "keypad transmit" mode */ out_flush(); termcap_active = TRUE; screen_start(); /* don't know where cursor is now */ #ifdef FEAT_TERMRESPONSE # ifdef FEAT_GUI if (!gui.in_use && !gui.starting) # endif { may_req_termresponse(); /* Immediately check for a response. If t_Co changes, we don't * want to redraw with wrong colors first. */ if (crv_status != CRV_GET) check_for_codes_from_term(); } #endif } } void stoptermcap() { screen_stop_highlight(); reset_cterm_colors(); if (termcap_active) { #ifdef FEAT_TERMRESPONSE # ifdef FEAT_GUI if (!gui.in_use && !gui.starting) # endif { /* May need to check for T_CRV response. */ if (crv_status == CRV_SENT) (void)vpeekc_nomap(); /* Check for termcodes first, otherwise an external program may * get them. */ check_for_codes_from_term(); } #endif out_str(T_KE); /* stop "keypad transmit" mode */ out_flush(); termcap_active = FALSE; cursor_on(); /* just in case it is still off */ out_str(T_TE); /* stop termcap mode */ screen_start(); /* don't know where cursor is now */ out_flush(); } } #if defined(FEAT_TERMRESPONSE) || defined(PROTO) /* * Request version string (for xterm) when needed. * Only do this after switching to raw mode, otherwise the result will be * echoed. * Only do this after startup has finished, to avoid that the response comes * while executing "-c !cmd" or even after "-c quit". * Only do this after termcap mode has been started, otherwise the codes for * the cursor keys may be wrong. * Only do this when 'esckeys' is on, otherwise the response causes trouble in * Insert mode. * On Unix only do it when both output and input are a tty (avoid writing * request to terminal while reading from a file). * The result is caught in check_termcode(). */ void may_req_termresponse() { if (crv_status == CRV_GET && cur_tmode == TMODE_RAW && starting == 0 && termcap_active && p_ek # ifdef UNIX && isatty(1) && isatty(read_cmd_fd) # endif && *T_CRV != NUL) { out_str(T_CRV); crv_status = CRV_SENT; /* check for the characters now, otherwise they might be eaten by * get_keystroke() */ out_flush(); (void)vpeekc_nomap(); } } #endif /* * Return TRUE when saving and restoring the screen. */ int swapping_screen() { return (full_screen && *T_TI != NUL); } #ifdef FEAT_MOUSE /* * setmouse() - switch mouse on/off depending on current mode and 'mouse' */ void setmouse() { # ifdef FEAT_MOUSE_TTY int checkfor; # endif # ifdef FEAT_MOUSESHAPE update_mouseshape(-1); # endif # ifdef FEAT_MOUSE_TTY /* Should be outside proc, but may break MOUSESHAPE */ # ifdef FEAT_GUI /* In the GUI the mouse is always enabled. */ if (gui.in_use) return; # endif /* be quick when mouse is off */ if (*p_mouse == NUL || has_mouse_termcode == 0) return; /* don't switch mouse on when not in raw mode (Ex mode) */ if (cur_tmode != TMODE_RAW) { mch_setmouse(FALSE); return; } # ifdef FEAT_VISUAL if (VIsual_active) checkfor = MOUSE_VISUAL; else # endif if (State == HITRETURN || State == ASKMORE || State == SETWSIZE) checkfor = MOUSE_RETURN; else if (State & INSERT) checkfor = MOUSE_INSERT; else if (State & CMDLINE) checkfor = MOUSE_COMMAND; else if (State == CONFIRM || State == EXTERNCMD) checkfor = ' '; /* don't use mouse for ":confirm" or ":!cmd" */ else checkfor = MOUSE_NORMAL; /* assume normal mode */ if (mouse_has(checkfor)) mch_setmouse(TRUE); else mch_setmouse(FALSE); # endif } /* * Return TRUE if * - "c" is in 'mouse', or * - 'a' is in 'mouse' and "c" is in MOUSE_A, or * - the current buffer is a help file and 'h' is in 'mouse' and we are in a * normal editing mode (not at hit-return message). */ int mouse_has(c) int c; { char_u *p; for (p = p_mouse; *p; ++p) switch (*p) { case 'a': if (vim_strchr((char_u *)MOUSE_A, c) != NULL) return TRUE; break; case MOUSE_HELP: if (c != MOUSE_RETURN && curbuf->b_help) return TRUE; break; default: if (c == *p) return TRUE; break; } return FALSE; } /* * Return TRUE when 'mousemodel' is set to "popup" or "popup_setpos". */ int mouse_model_popup() { return (p_mousem[0] == 'p'); } #endif /* * By outputting the 'cursor very visible' termcap code, for some windowed * terminals this makes the screen scrolled to the correct position. * Used when starting Vim or returning from a shell. */ void scroll_start() { if (*T_VS != NUL) { out_str(T_VS); out_str(T_VE); screen_start(); /* don't know where cursor is now */ } } static int cursor_is_off = FALSE; /* * Enable the cursor. */ void cursor_on() { if (cursor_is_off) { out_str(T_VE); cursor_is_off = FALSE; } } /* * Disable the cursor. */ void cursor_off() { if (full_screen) { if (!cursor_is_off) out_str(T_VI); /* disable cursor */ cursor_is_off = TRUE; } } #if defined(CURSOR_SHAPE) || defined(PROTO) /* * Set cursor shape to match Insert mode. */ void term_cursor_shape() { static int showing_insert_mode = MAYBE; if (!full_screen || *T_CSI == NUL || *T_CEI == NUL) return; if (State & INSERT) { if (showing_insert_mode != TRUE) out_str(T_CSI); /* Insert mode cursor */ showing_insert_mode = TRUE; } else { if (showing_insert_mode != FALSE) out_str(T_CEI); /* non-Insert mode cursor */ showing_insert_mode = FALSE; } } #endif /* * Set scrolling region for window 'wp'. * The region starts 'off' lines from the start of the window. * Also set the vertical scroll region for a vertically split window. Always * the full width of the window, excluding the vertical separator. */ void scroll_region_set(wp, off) win_T *wp; int off; { OUT_STR(tgoto((char *)T_CS, W_WINROW(wp) + wp->w_height - 1, W_WINROW(wp) + off)); #ifdef FEAT_VERTSPLIT if (*T_CSV != NUL && wp->w_width != Columns) OUT_STR(tgoto((char *)T_CSV, W_WINCOL(wp) + wp->w_width - 1, W_WINCOL(wp))); #endif screen_start(); /* don't know where cursor is now */ } /* * Reset scrolling region to the whole screen. */ void scroll_region_reset() { OUT_STR(tgoto((char *)T_CS, (int)Rows - 1, 0)); #ifdef FEAT_VERTSPLIT if (*T_CSV != NUL) OUT_STR(tgoto((char *)T_CSV, (int)Columns - 1, 0)); #endif screen_start(); /* don't know where cursor is now */ } /* * List of terminal codes that are currently recognized. */ static struct termcode { char_u name[2]; /* termcap name of entry */ char_u *code; /* terminal code (in allocated memory) */ int len; /* STRLEN(code) */ int modlen; /* length of part before ";*~". */ } *termcodes = NULL; static int tc_max_len = 0; /* number of entries that termcodes[] can hold */ static int tc_len = 0; /* current number of entries in termcodes[] */ static int termcode_star __ARGS((char_u *code, int len)); void clear_termcodes() { while (tc_len > 0) vim_free(termcodes[--tc_len].code); vim_free(termcodes); termcodes = NULL; tc_max_len = 0; #ifdef HAVE_TGETENT BC = (char *)empty_option; UP = (char *)empty_option; PC = NUL; /* set pad character to NUL */ ospeed = 0; #endif need_gather = TRUE; /* need to fill termleader[] */ } #define ATC_FROM_TERM 55 /* * Add a new entry to the list of terminal codes. * The list is kept alphabetical for ":set termcap" * "flags" is TRUE when replacing 7-bit by 8-bit controls is desired. * "flags" can also be ATC_FROM_TERM for got_code_from_term(). */ void add_termcode(name, string, flags) char_u *name; char_u *string; int flags; { struct termcode *new_tc; int i, j; char_u *s; int len; if (string == NULL || *string == NUL) { del_termcode(name); return; } s = vim_strsave(string); if (s == NULL) return; /* Change leading <Esc>[ to CSI, change <Esc>O to <M-O>. */ if (flags != 0 && flags != ATC_FROM_TERM && term_7to8bit(string) != 0) { STRMOVE(s, s + 1); s[0] = term_7to8bit(string); } len = (int)STRLEN(s); need_gather = TRUE; /* need to fill termleader[] */ /* * need to make space for more entries */ if (tc_len == tc_max_len) { tc_max_len += 20; new_tc = (struct termcode *)alloc( (unsigned)(tc_max_len * sizeof(struct termcode))); if (new_tc == NULL) { tc_max_len -= 20; return; } for (i = 0; i < tc_len; ++i) new_tc[i] = termcodes[i]; vim_free(termcodes); termcodes = new_tc; } /* * Look for existing entry with the same name, it is replaced. * Look for an existing entry that is alphabetical higher, the new entry * is inserted in front of it. */ for (i = 0; i < tc_len; ++i) { if (termcodes[i].name[0] < name[0]) continue; if (termcodes[i].name[0] == name[0]) { if (termcodes[i].name[1] < name[1]) continue; /* * Exact match: May replace old code. */ if (termcodes[i].name[1] == name[1]) { if (flags == ATC_FROM_TERM && (j = termcode_star( termcodes[i].code, termcodes[i].len)) > 0) { /* Don't replace ESC[123;*X or ESC O*X with another when * invoked from got_code_from_term(). */ if (len == termcodes[i].len - j && STRNCMP(s, termcodes[i].code, len - 1) == 0 && s[len - 1] == termcodes[i].code[termcodes[i].len - 1]) { /* They are equal but for the ";*": don't add it. */ vim_free(s); return; } } else { /* Replace old code. */ vim_free(termcodes[i].code); --tc_len; break; } } } /* * Found alphabetical larger entry, move rest to insert new entry */ for (j = tc_len; j > i; --j) termcodes[j] = termcodes[j - 1]; break; } termcodes[i].name[0] = name[0]; termcodes[i].name[1] = name[1]; termcodes[i].code = s; termcodes[i].len = len; /* For xterm we recognize special codes like "ESC[42;*X" and "ESC O*X" that * accept modifiers. */ termcodes[i].modlen = 0; j = termcode_star(s, len); if (j > 0) termcodes[i].modlen = len - 1 - j; ++tc_len; } /* * Check termcode "code[len]" for ending in ;*X, <Esc>O*X or <M-O>*X. * The "X" can be any character. * Return 0 if not found, 2 for ;*X and 1 for O*X and <M-O>*X. */ static int termcode_star(code, len) char_u *code; int len; { /* Shortest is <M-O>*X. With ; shortest is <CSI>1;*X */ if (len >= 3 && code[len - 2] == '*') { if (len >= 5 && code[len - 3] == ';') return 2; if ((len >= 4 && code[len - 3] == 'O') || code[len - 3] == 'O' + 128) return 1; } return 0; } char_u * find_termcode(name) char_u *name; { int i; for (i = 0; i < tc_len; ++i) if (termcodes[i].name[0] == name[0] && termcodes[i].name[1] == name[1]) return termcodes[i].code; return NULL; } #if defined(FEAT_CMDL_COMPL) || defined(PROTO) char_u * get_termcode(i) int i; { if (i >= tc_len) return NULL; return &termcodes[i].name[0]; } #endif void del_termcode(name) char_u *name; { int i; if (termcodes == NULL) /* nothing there yet */ return; need_gather = TRUE; /* need to fill termleader[] */ for (i = 0; i < tc_len; ++i) if (termcodes[i].name[0] == name[0] && termcodes[i].name[1] == name[1]) { del_termcode_idx(i); return; } /* not found. Give error message? */ } static void del_termcode_idx(idx) int idx; { int i; vim_free(termcodes[idx].code); --tc_len; for (i = idx; i < tc_len; ++i) termcodes[i] = termcodes[i + 1]; } #ifdef FEAT_TERMRESPONSE /* * Called when detected that the terminal sends 8-bit codes. * Convert all 7-bit codes to their 8-bit equivalent. */ static void switch_to_8bit() { int i; int c; /* Only need to do something when not already using 8-bit codes. */ if (!term_is_8bit(T_NAME)) { for (i = 0; i < tc_len; ++i) { c = term_7to8bit(termcodes[i].code); if (c != 0) { STRMOVE(termcodes[i].code + 1, termcodes[i].code + 2); termcodes[i].code[0] = c; } } need_gather = TRUE; /* need to fill termleader[] */ } detected_8bit = TRUE; } #endif #ifdef CHECK_DOUBLE_CLICK static linenr_T orig_topline = 0; # ifdef FEAT_DIFF static int orig_topfill = 0; # endif #endif #if (defined(FEAT_WINDOWS) && defined(CHECK_DOUBLE_CLICK)) || defined(PROTO) /* * Checking for double clicks ourselves. * "orig_topline" is used to avoid detecting a double-click when the window * contents scrolled (e.g., when 'scrolloff' is non-zero). */ /* * Set orig_topline. Used when jumping to another window, so that a double * click still works. */ void set_mouse_topline(wp) win_T *wp; { orig_topline = wp->w_topline; # ifdef FEAT_DIFF orig_topfill = wp->w_topfill; # endif } #endif /* * Check if typebuf.tb_buf[] contains a terminal key code. * Check from typebuf.tb_buf[typebuf.tb_off] to typebuf.tb_buf[typebuf.tb_off * + max_offset]. * Return 0 for no match, -1 for partial match, > 0 for full match. * Return KEYLEN_REMOVED when a key code was deleted. * With a match, the match is removed, the replacement code is inserted in * typebuf.tb_buf[] and the number of characters in typebuf.tb_buf[] is * returned. * When "buf" is not NULL, buf[bufsize] is used instead of typebuf.tb_buf[]. * "buflen" is then the length of the string in buf[] and is updated for * inserts and deletes. */ int check_termcode(max_offset, buf, bufsize, buflen) int max_offset; char_u *buf; int bufsize; int *buflen; { char_u *tp; char_u *p; int slen = 0; /* init for GCC */ int modslen; int len; int retval = 0; int offset; char_u key_name[2]; int modifiers; int key; int new_slen; int extra; char_u string[MAX_KEY_CODE_LEN + 1]; int i, j; int idx = 0; #ifdef FEAT_MOUSE # if !defined(UNIX) || defined(FEAT_MOUSE_XTERM) || defined(FEAT_GUI) \ || defined(FEAT_MOUSE_GPM) || defined(FEAT_SYSMOUSE) char_u bytes[6]; int num_bytes; # endif int mouse_code = 0; /* init for GCC */ int is_click, is_drag; int wheel_code = 0; int current_button; static int held_button = MOUSE_RELEASE; static int orig_num_clicks = 1; static int orig_mouse_code = 0x0; # ifdef CHECK_DOUBLE_CLICK static int orig_mouse_col = 0; static int orig_mouse_row = 0; static struct timeval orig_mouse_time = {0, 0}; /* time of previous mouse click */ struct timeval mouse_time; /* time of current mouse click */ long timediff; /* elapsed time in msec */ # endif #endif int cpo_koffset; #ifdef FEAT_MOUSE_GPM extern int gpm_flag; /* gpm library variable */ #endif cpo_koffset = (vim_strchr(p_cpo, CPO_KOFFSET) != NULL); /* * Speed up the checks for terminal codes by gathering all first bytes * used in termleader[]. Often this is just a single <Esc>. */ if (need_gather) gather_termleader(); /* * Check at several positions in typebuf.tb_buf[], to catch something like * "x<Up>" that can be mapped. Stop at max_offset, because characters * after that cannot be used for mapping, and with @r commands * typebuf.tb_buf[] * can become very long. * This is used often, KEEP IT FAST! */ for (offset = 0; offset < max_offset; ++offset) { if (buf == NULL) { if (offset >= typebuf.tb_len) break; tp = typebuf.tb_buf + typebuf.tb_off + offset; len = typebuf.tb_len - offset; /* length of the input */ } else { if (offset >= *buflen) break; tp = buf + offset; len = *buflen - offset; } /* * Don't check characters after K_SPECIAL, those are already * translated terminal chars (avoid translating ~@^Hx). */ if (*tp == K_SPECIAL) { offset += 2; /* there are always 2 extra characters */ continue; } /* * Skip this position if the character does not appear as the first * character in term_strings. This speeds up a lot, since most * termcodes start with the same character (ESC or CSI). */ i = *tp; for (p = termleader; *p && *p != i; ++p) ; if (*p == NUL) continue; /* * Skip this position if p_ek is not set and tp[0] is an ESC and we * are in Insert mode. */ if (*tp == ESC && !p_ek && (State & INSERT)) continue; key_name[0] = NUL; /* no key name found yet */ key_name[1] = NUL; /* no key name found yet */ modifiers = 0; /* no modifiers yet */ #ifdef FEAT_GUI if (gui.in_use) { /* * GUI special key codes are all of the form [CSI xx]. */ if (*tp == CSI) /* Special key from GUI */ { if (len < 3) return -1; /* Shouldn't happen */ slen = 3; key_name[0] = tp[1]; key_name[1] = tp[2]; } } else #endif /* FEAT_GUI */ { for (idx = 0; idx < tc_len; ++idx) { /* * Ignore the entry if we are not at the start of * typebuf.tb_buf[] * and there are not enough characters to make a match. * But only when the 'K' flag is in 'cpoptions'. */ slen = termcodes[idx].len; if (cpo_koffset && offset && len < slen) continue; if (STRNCMP(termcodes[idx].code, tp, (size_t)(slen > len ? len : slen)) == 0) { if (len < slen) /* got a partial sequence */ return -1; /* need to get more chars */ /* * When found a keypad key, check if there is another key * that matches and use that one. This makes <Home> to be * found instead of <kHome> when they produce the same * key code. */ if (termcodes[idx].name[0] == 'K' && VIM_ISDIGIT(termcodes[idx].name[1])) { for (j = idx + 1; j < tc_len; ++j) if (termcodes[j].len == slen && STRNCMP(termcodes[idx].code, termcodes[j].code, slen) == 0) { idx = j; break; } } key_name[0] = termcodes[idx].name[0]; key_name[1] = termcodes[idx].name[1]; break; } /* * Check for code with modifier, like xterm uses: * <Esc>[123;*X (modslen == slen - 3) * Also <Esc>O*X and <M-O>*X (modslen == slen - 2). * When there is a modifier the * matches a number. * When there is no modifier the ;* or * is omitted. */ if (termcodes[idx].modlen > 0) { modslen = termcodes[idx].modlen; if (cpo_koffset && offset && len < modslen) continue; if (STRNCMP(termcodes[idx].code, tp, (size_t)(modslen > len ? len : modslen)) == 0) { int n; if (len <= modslen) /* got a partial sequence */ return -1; /* need to get more chars */ if (tp[modslen] == termcodes[idx].code[slen - 1]) slen = modslen + 1; /* no modifiers */ else if (tp[modslen] != ';' && modslen == slen - 3) continue; /* no match */ else { /* Skip over the digits, the final char must * follow. */ for (j = slen - 2; j < len && isdigit(tp[j]); ++j) ; ++j; if (len < j) /* got a partial sequence */ return -1; /* need to get more chars */ if (tp[j - 1] != termcodes[idx].code[slen - 1]) continue; /* no match */ /* Match! Convert modifier bits. */ n = atoi((char *)tp + slen - 2) - 1; if (n & 1) modifiers |= MOD_MASK_SHIFT; if (n & 2) modifiers |= MOD_MASK_ALT; if (n & 4) modifiers |= MOD_MASK_CTRL; if (n & 8) modifiers |= MOD_MASK_META; slen = j; } key_name[0] = termcodes[idx].name[0]; key_name[1] = termcodes[idx].name[1]; break; } } } } #ifdef FEAT_TERMRESPONSE if (key_name[0] == NUL /* URXVT mouse uses <ESC>[#;#;#M, but we are matching <ESC>[ */ || key_name[0] == KS_URXVT_MOUSE) { /* Check for xterm version string: "<Esc>[>{x};{vers};{y}c". Also * eat other possible responses to t_RV, rxvt returns * "<Esc>[?1;2c". Also accept CSI instead of <Esc>[. * mrxvt has been reported to have "+" in the version. Assume * the escape sequence ends with a letter or one of "{|}~". */ if (*T_CRV != NUL && ((tp[0] == ESC && tp[1] == '[' && len >= 3) || (tp[0] == CSI && len >= 2))) { j = 0; extra = 0; for (i = 2 + (tp[0] != CSI); i < len && !(tp[i] >= '{' && tp[i] <= '~') && !ASCII_ISALPHA(tp[i]); ++i) if (tp[i] == ';' && ++j == 1) extra = atoi((char *)tp + i + 1); if (i == len) return -1; /* not enough characters */ /* eat it when at least one digit and ending in 'c' */ if (i > 2 + (tp[0] != CSI) && tp[i] == 'c') { crv_status = CRV_GOT; /* If this code starts with CSI, you can bet that the * terminal uses 8-bit codes. */ if (tp[0] == CSI) switch_to_8bit(); /* rxvt sends its version number: "20703" is 2.7.3. * Ignore it for when the user has set 'term' to xterm, * even though it's an rxvt. */ if (extra > 20000) extra = 0; if (tp[1 + (tp[0] != CSI)] == '>' && j == 2) { /* if xterm version >= 95 use mouse dragging */ if (extra >= 95 # ifdef TTYM_URXVT && ttym_flags != TTYM_URXVT # endif ) set_option_value((char_u *)"ttym", 0L, (char_u *)"xterm2", 0); /* if xterm version >= 141 try to get termcap codes */ if (extra >= 141) { check_for_codes = TRUE; need_gather = TRUE; req_codes_from_term(); } } # ifdef FEAT_EVAL set_vim_var_string(VV_TERMRESPONSE, tp, i + 1); # endif # ifdef FEAT_AUTOCMD apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf); # endif key_name[0] = (int)KS_EXTRA; key_name[1] = (int)KE_IGNORE; slen = i + 1; } } /* Check for '<Esc>P1+r<hex bytes><Esc>\'. A "0" instead of the * "1" means an invalid request. */ else if (check_for_codes && ((tp[0] == ESC && tp[1] == 'P' && len >= 2) || tp[0] == DCS)) { j = 1 + (tp[0] != DCS); for (i = j; i < len; ++i) if ((tp[i] == ESC && tp[i + 1] == '\\' && i + 1 < len) || tp[i] == STERM) { if (i - j >= 3 && tp[j + 1] == '+' && tp[j + 2] == 'r') got_code_from_term(tp + j, i); key_name[0] = (int)KS_EXTRA; key_name[1] = (int)KE_IGNORE; slen = i + 1 + (tp[i] == ESC); break; } if (i == len) return -1; /* not enough characters */ } } #endif if (key_name[0] == NUL) continue; /* No match at this position, try next one */ /* We only get here when we have a complete termcode match */ #ifdef FEAT_MOUSE # ifdef FEAT_GUI /* * Only in the GUI: Fetch the pointer coordinates of the scroll event * so that we know which window to scroll later. */ if (gui.in_use && key_name[0] == (int)KS_EXTRA && (key_name[1] == (int)KE_X1MOUSE || key_name[1] == (int)KE_X2MOUSE || key_name[1] == (int)KE_MOUSELEFT || key_name[1] == (int)KE_MOUSERIGHT || key_name[1] == (int)KE_MOUSEDOWN || key_name[1] == (int)KE_MOUSEUP)) { num_bytes = get_bytes_from_buf(tp + slen, bytes, 4); if (num_bytes == -1) /* not enough coordinates */ return -1; mouse_col = 128 * (bytes[0] - ' ' - 1) + bytes[1] - ' ' - 1; mouse_row = 128 * (bytes[2] - ' ' - 1) + bytes[3] - ' ' - 1; slen += num_bytes; } else # endif /* * If it is a mouse click, get the coordinates. */ if (key_name[0] == (int)KS_MOUSE # ifdef FEAT_MOUSE_JSB || key_name[0] == (int)KS_JSBTERM_MOUSE # endif # ifdef FEAT_MOUSE_NET || key_name[0] == (int)KS_NETTERM_MOUSE # endif # ifdef FEAT_MOUSE_DEC || key_name[0] == (int)KS_DEC_MOUSE # endif # ifdef FEAT_MOUSE_PTERM || key_name[0] == (int)KS_PTERM_MOUSE # endif # ifdef FEAT_MOUSE_URXVT || key_name[0] == (int)KS_URXVT_MOUSE # endif ) { is_click = is_drag = FALSE; # if !defined(UNIX) || defined(FEAT_MOUSE_XTERM) || defined(FEAT_GUI) \ || defined(FEAT_MOUSE_GPM) || defined(FEAT_SYSMOUSE) if (key_name[0] == (int)KS_MOUSE) { /* * For xterm and MSDOS we get "<t_mouse>scr", where * s == encoded button state: * 0x20 = left button down * 0x21 = middle button down * 0x22 = right button down * 0x23 = any button release * 0x60 = button 4 down (scroll wheel down) * 0x61 = button 5 down (scroll wheel up) * add 0x04 for SHIFT * add 0x08 for ALT * add 0x10 for CTRL * add 0x20 for mouse drag (0x40 is drag with left button) * c == column + ' ' + 1 == column + 33 * r == row + ' ' + 1 == row + 33 * * The coordinates are passed on through global variables. * Ugly, but this avoids trouble with mouse clicks at an * unexpected moment and allows for mapping them. */ for (;;) { #ifdef FEAT_GUI if (gui.in_use) { /* GUI uses more bits for columns > 223 */ num_bytes = get_bytes_from_buf(tp + slen, bytes, 5); if (num_bytes == -1) /* not enough coordinates */ return -1; mouse_code = bytes[0]; mouse_col = 128 * (bytes[1] - ' ' - 1) + bytes[2] - ' ' - 1; mouse_row = 128 * (bytes[3] - ' ' - 1) + bytes[4] - ' ' - 1; } else #endif { num_bytes = get_bytes_from_buf(tp + slen, bytes, 3); if (num_bytes == -1) /* not enough coordinates */ return -1; mouse_code = bytes[0]; mouse_col = bytes[1] - ' ' - 1; mouse_row = bytes[2] - ' ' - 1; } slen += num_bytes; /* If the following bytes is also a mouse code and it has * the same code, dump this one and get the next. This * makes dragging a whole lot faster. */ #ifdef FEAT_GUI if (gui.in_use) j = 3; else #endif j = termcodes[idx].len; if (STRNCMP(tp, tp + slen, (size_t)j) == 0 && tp[slen + j] == mouse_code && tp[slen + j + 1] != NUL && tp[slen + j + 2] != NUL #ifdef FEAT_GUI && (!gui.in_use || (tp[slen + j + 3] != NUL && tp[slen + j + 4] != NUL)) #endif ) slen += j; else break; } } # ifdef FEAT_MOUSE_URXVT if (key_name[0] == (int)KS_URXVT_MOUSE) { for (;;) { /* URXVT 1015 mouse reporting mode: * Almost identical to xterm mouse mode, except the values * are decimal instead of bytes. * * \033[%d;%d;%dM * ^-- row * ^----- column * ^-------- code */ p = tp + slen; mouse_code = getdigits(&p); if (*p++ != ';') return -1; mouse_col = getdigits(&p) - 1; if (*p++ != ';') return -1; mouse_row = getdigits(&p) - 1; if (*p++ != 'M') return -1; slen += (int)(p - (tp + slen)); /* skip this one if next one has same code (like xterm * case) */ j = termcodes[idx].len; if (STRNCMP(tp, tp + slen, (size_t)j) == 0) { /* check if the command is complete by looking for the * M */ int slen2; int cmd_complete = 0; for (slen2 = slen; slen2 < len; slen2++) { if (tp[slen2] == 'M') { cmd_complete = 1; break; } } p += j; if (cmd_complete && getdigits(&p) == mouse_code) { slen += j; /* skip the \033[ */ continue; } } break; } } # endif if (key_name[0] == (int)KS_MOUSE #ifdef FEAT_MOUSE_URXVT || key_name[0] == (int)KS_URXVT_MOUSE #endif ) { # if !defined(MSWIN) && !defined(MSDOS) /* * Handle mouse events. * Recognize the xterm mouse wheel, but not in the GUI, the * Linux console with GPM and the MS-DOS or Win32 console * (multi-clicks use >= 0x60). */ if (mouse_code >= MOUSEWHEEL_LOW # ifdef FEAT_GUI && !gui.in_use # endif # ifdef FEAT_MOUSE_GPM && gpm_flag == 0 # endif ) { /* Keep the mouse_code before it's changed, so that we * remember that it was a mouse wheel click. */ wheel_code = mouse_code; } # ifdef FEAT_MOUSE_XTERM else if (held_button == MOUSE_RELEASE # ifdef FEAT_GUI && !gui.in_use # endif && (mouse_code == 0x23 || mouse_code == 0x24)) { /* Apparently used by rxvt scroll wheel. */ wheel_code = mouse_code - 0x23 + MOUSEWHEEL_LOW; } # endif # if defined(UNIX) && defined(FEAT_MOUSE_TTY) else if (use_xterm_mouse() > 1) { if (mouse_code & MOUSE_DRAG_XTERM) mouse_code |= MOUSE_DRAG; } # endif # ifdef FEAT_XCLIPBOARD else if (!(mouse_code & MOUSE_DRAG & ~MOUSE_CLICK_MASK)) { if ((mouse_code & MOUSE_RELEASE) == MOUSE_RELEASE) stop_xterm_trace(); else start_xterm_trace(mouse_code); } # endif # endif } # endif /* !UNIX || FEAT_MOUSE_XTERM */ # ifdef FEAT_MOUSE_NET if (key_name[0] == (int)KS_NETTERM_MOUSE) { int mc, mr; /* expect a rather limited sequence like: balancing { * \033}6,45\r * '6' is the row, 45 is the column */ p = tp + slen; mr = getdigits(&p); if (*p++ != ',') return -1; mc = getdigits(&p); if (*p++ != '\r') return -1; mouse_col = mc - 1; mouse_row = mr - 1; mouse_code = MOUSE_LEFT; slen += (int)(p - (tp + slen)); } # endif /* FEAT_MOUSE_NET */ # ifdef FEAT_MOUSE_JSB if (key_name[0] == (int)KS_JSBTERM_MOUSE) { int mult, val, iter, button, status; /* JSBTERM Input Model * \033[0~zw uniq escape sequence * (L-x) Left button pressed - not pressed x not reporting * (M-x) Middle button pressed - not pressed x not reporting * (R-x) Right button pressed - not pressed x not reporting * (SDmdu) Single , Double click, m mouse move d button down * u button up * ### X cursor position padded to 3 digits * ### Y cursor position padded to 3 digits * (s-x) SHIFT key pressed - not pressed x not reporting * (c-x) CTRL key pressed - not pressed x not reporting * \033\\ terminating sequence */ p = tp + slen; button = mouse_code = 0; switch (*p++) { case 'L': button = 1; break; case '-': break; case 'x': break; /* ignore sequence */ default: return -1; /* Unknown Result */ } switch (*p++) { case 'M': button |= 2; break; case '-': break; case 'x': break; /* ignore sequence */ default: return -1; /* Unknown Result */ } switch (*p++) { case 'R': button |= 4; break; case '-': break; case 'x': break; /* ignore sequence */ default: return -1; /* Unknown Result */ } status = *p++; for (val = 0, mult = 100, iter = 0; iter < 3; iter++, mult /= 10, p++) if (*p >= '0' && *p <= '9') val += (*p - '0') * mult; else return -1; mouse_col = val; for (val = 0, mult = 100, iter = 0; iter < 3; iter++, mult /= 10, p++) if (*p >= '0' && *p <= '9') val += (*p - '0') * mult; else return -1; mouse_row = val; switch (*p++) { case 's': button |= 8; break; /* SHIFT key Pressed */ case '-': break; /* Not Pressed */ case 'x': break; /* Not Reporting */ default: return -1; /* Unknown Result */ } switch (*p++) { case 'c': button |= 16; break; /* CTRL key Pressed */ case '-': break; /* Not Pressed */ case 'x': break; /* Not Reporting */ default: return -1; /* Unknown Result */ } if (*p++ != '\033') return -1; if (*p++ != '\\') return -1; switch (status) { case 'D': /* Double Click */ case 'S': /* Single Click */ if (button & 1) mouse_code |= MOUSE_LEFT; if (button & 2) mouse_code |= MOUSE_MIDDLE; if (button & 4) mouse_code |= MOUSE_RIGHT; if (button & 8) mouse_code |= MOUSE_SHIFT; if (button & 16) mouse_code |= MOUSE_CTRL; break; case 'm': /* Mouse move */ if (button & 1) mouse_code |= MOUSE_LEFT; if (button & 2) mouse_code |= MOUSE_MIDDLE; if (button & 4) mouse_code |= MOUSE_RIGHT; if (button & 8) mouse_code |= MOUSE_SHIFT; if (button & 16) mouse_code |= MOUSE_CTRL; if ((button & 7) != 0) { held_button = mouse_code; mouse_code |= MOUSE_DRAG; } is_drag = TRUE; showmode(); break; case 'd': /* Button Down */ if (button & 1) mouse_code |= MOUSE_LEFT; if (button & 2) mouse_code |= MOUSE_MIDDLE; if (button & 4) mouse_code |= MOUSE_RIGHT; if (button & 8) mouse_code |= MOUSE_SHIFT; if (button & 16) mouse_code |= MOUSE_CTRL; break; case 'u': /* Button Up */ if (button & 1) mouse_code |= MOUSE_LEFT | MOUSE_RELEASE; if (button & 2) mouse_code |= MOUSE_MIDDLE | MOUSE_RELEASE; if (button & 4) mouse_code |= MOUSE_RIGHT | MOUSE_RELEASE; if (button & 8) mouse_code |= MOUSE_SHIFT; if (button & 16) mouse_code |= MOUSE_CTRL; break; default: return -1; /* Unknown Result */ } slen += (p - (tp + slen)); } # endif /* FEAT_MOUSE_JSB */ # ifdef FEAT_MOUSE_DEC if (key_name[0] == (int)KS_DEC_MOUSE) { /* The DEC Locator Input Model * Netterm delivers the code sequence: * \033[2;4;24;80&w (left button down) * \033[3;0;24;80&w (left button up) * \033[6;1;24;80&w (right button down) * \033[7;0;24;80&w (right button up) * CSI Pe ; Pb ; Pr ; Pc ; Pp & w * Pe is the event code * Pb is the button code * Pr is the row coordinate * Pc is the column coordinate * Pp is the third coordinate (page number) * Pe, the event code indicates what event caused this report * The following event codes are defined: * 0 - request, the terminal received an explicit request * for a locator report, but the locator is unavailable * 1 - request, the terminal received an explicit request * for a locator report * 2 - left button down * 3 - left button up * 4 - middle button down * 5 - middle button up * 6 - right button down * 7 - right button up * 8 - fourth button down * 9 - fourth button up * 10 - locator outside filter rectangle * Pb, the button code, ASCII decimal 0-15 indicating which * buttons are down if any. The state of the four buttons * on the locator correspond to the low four bits of the * decimal value, * "1" means button depressed * 0 - no buttons down, * 1 - right, * 2 - middle, * 4 - left, * 8 - fourth * Pr is the row coordinate of the locator position in the page, * encoded as an ASCII decimal value. * If Pr is omitted, the locator position is undefined * (outside the terminal window for example). * Pc is the column coordinate of the locator position in the * page, encoded as an ASCII decimal value. * If Pc is omitted, the locator position is undefined * (outside the terminal window for example). * Pp is the page coordinate of the locator position * encoded as an ASCII decimal value. * The page coordinate may be omitted if the locator is on * page one (the default). We ignore it anyway. */ int Pe, Pb, Pr, Pc; p = tp + slen; /* get event status */ Pe = getdigits(&p); if (*p++ != ';') return -1; /* get button status */ Pb = getdigits(&p); if (*p++ != ';') return -1; /* get row status */ Pr = getdigits(&p); if (*p++ != ';') return -1; /* get column status */ Pc = getdigits(&p); /* the page parameter is optional */ if (*p == ';') { p++; (void)getdigits(&p); } if (*p++ != '&') return -1; if (*p++ != 'w') return -1; mouse_code = 0; switch (Pe) { case 0: return -1; /* position request while unavailable */ case 1: /* a response to a locator position request includes the status of all buttons */ Pb &= 7; /* mask off and ignore fourth button */ if (Pb & 4) mouse_code = MOUSE_LEFT; if (Pb & 2) mouse_code = MOUSE_MIDDLE; if (Pb & 1) mouse_code = MOUSE_RIGHT; if (Pb) { held_button = mouse_code; mouse_code |= MOUSE_DRAG; WantQueryMouse = TRUE; } is_drag = TRUE; showmode(); break; case 2: mouse_code = MOUSE_LEFT; WantQueryMouse = TRUE; break; case 3: mouse_code = MOUSE_RELEASE | MOUSE_LEFT; break; case 4: mouse_code = MOUSE_MIDDLE; WantQueryMouse = TRUE; break; case 5: mouse_code = MOUSE_RELEASE | MOUSE_MIDDLE; break; case 6: mouse_code = MOUSE_RIGHT; WantQueryMouse = TRUE; break; case 7: mouse_code = MOUSE_RELEASE | MOUSE_RIGHT; break; case 8: return -1; /* fourth button down */ case 9: return -1; /* fourth button up */ case 10: return -1; /* mouse outside of filter rectangle */ default: return -1; /* should never occur */ } mouse_col = Pc - 1; mouse_row = Pr - 1; slen += (int)(p - (tp + slen)); } # endif /* FEAT_MOUSE_DEC */ # ifdef FEAT_MOUSE_PTERM if (key_name[0] == (int)KS_PTERM_MOUSE) { int button, num_clicks, action; p = tp + slen; action = getdigits(&p); if (*p++ != ';') return -1; mouse_row = getdigits(&p); if (*p++ != ';') return -1; mouse_col = getdigits(&p); if (*p++ != ';') return -1; button = getdigits(&p); mouse_code = 0; switch( button ) { case 4: mouse_code = MOUSE_LEFT; break; case 1: mouse_code = MOUSE_RIGHT; break; case 2: mouse_code = MOUSE_MIDDLE; break; default: return -1; } switch( action ) { case 31: /* Initial press */ if (*p++ != ';') return -1; num_clicks = getdigits(&p); /* Not used */ break; case 32: /* Release */ mouse_code |= MOUSE_RELEASE; break; case 33: /* Drag */ held_button = mouse_code; mouse_code |= MOUSE_DRAG; break; default: return -1; } if (*p++ != 't') return -1; slen += (p - (tp + slen)); } # endif /* FEAT_MOUSE_PTERM */ /* Interpret the mouse code */ current_button = (mouse_code & MOUSE_CLICK_MASK); if (current_button == MOUSE_RELEASE # ifdef FEAT_MOUSE_XTERM && wheel_code == 0 # endif ) { /* * If we get a mouse drag or release event when * there is no mouse button held down (held_button == * MOUSE_RELEASE), produce a K_IGNORE below. * (can happen when you hold down two buttons * and then let them go, or click in the menu bar, but not * on a menu, and drag into the text). */ if ((mouse_code & MOUSE_DRAG) == MOUSE_DRAG) is_drag = TRUE; current_button = held_button; } else if (wheel_code == 0) { # ifdef CHECK_DOUBLE_CLICK # ifdef FEAT_MOUSE_GPM # ifdef FEAT_GUI /* * Only for Unix, when GUI or gpm is not active, we handle * multi-clicks here. */ if (gpm_flag == 0 && !gui.in_use) # else if (gpm_flag == 0) # endif # else # ifdef FEAT_GUI if (!gui.in_use) # endif # endif { /* * Compute the time elapsed since the previous mouse click. */ gettimeofday(&mouse_time, NULL); timediff = (mouse_time.tv_usec - orig_mouse_time.tv_usec) / 1000; if (timediff < 0) --orig_mouse_time.tv_sec; timediff += (mouse_time.tv_sec - orig_mouse_time.tv_sec) * 1000; orig_mouse_time = mouse_time; if (mouse_code == orig_mouse_code && timediff < p_mouset && orig_num_clicks != 4 && orig_mouse_col == mouse_col && orig_mouse_row == mouse_row && ((orig_topline == curwin->w_topline #ifdef FEAT_DIFF && orig_topfill == curwin->w_topfill #endif ) #ifdef FEAT_WINDOWS /* Double click in tab pages line also works * when window contents changes. */ || (mouse_row == 0 && firstwin->w_winrow > 0) #endif ) ) ++orig_num_clicks; else orig_num_clicks = 1; orig_mouse_col = mouse_col; orig_mouse_row = mouse_row; orig_topline = curwin->w_topline; #ifdef FEAT_DIFF orig_topfill = curwin->w_topfill; #endif } # if defined(FEAT_GUI) || defined(FEAT_MOUSE_GPM) else orig_num_clicks = NUM_MOUSE_CLICKS(mouse_code); # endif # else orig_num_clicks = NUM_MOUSE_CLICKS(mouse_code); # endif is_click = TRUE; orig_mouse_code = mouse_code; } if (!is_drag) held_button = mouse_code & MOUSE_CLICK_MASK; /* * Translate the actual mouse event into a pseudo mouse event. * First work out what modifiers are to be used. */ if (orig_mouse_code & MOUSE_SHIFT) modifiers |= MOD_MASK_SHIFT; if (orig_mouse_code & MOUSE_CTRL) modifiers |= MOD_MASK_CTRL; if (orig_mouse_code & MOUSE_ALT) modifiers |= MOD_MASK_ALT; if (orig_num_clicks == 2) modifiers |= MOD_MASK_2CLICK; else if (orig_num_clicks == 3) modifiers |= MOD_MASK_3CLICK; else if (orig_num_clicks == 4) modifiers |= MOD_MASK_4CLICK; /* Work out our pseudo mouse event */ key_name[0] = (int)KS_EXTRA; if (wheel_code != 0) { if (wheel_code & MOUSE_CTRL) modifiers |= MOD_MASK_CTRL; if (wheel_code & MOUSE_ALT) modifiers |= MOD_MASK_ALT; key_name[1] = (wheel_code & 1) ? (int)KE_MOUSEUP : (int)KE_MOUSEDOWN; } else key_name[1] = get_pseudo_mouse_code(current_button, is_click, is_drag); } #endif /* FEAT_MOUSE */ #ifdef FEAT_GUI /* * If using the GUI, then we get menu and scrollbar events. * * A menu event is encoded as K_SPECIAL, KS_MENU, KE_FILLER followed by * four bytes which are to be taken as a pointer to the vimmenu_T * structure. * * A tab line event is encoded as K_SPECIAL KS_TABLINE nr, where "nr" * is one byte with the tab index. * * A scrollbar event is K_SPECIAL, KS_VER_SCROLLBAR, KE_FILLER followed * by one byte representing the scrollbar number, and then four bytes * representing a long_u which is the new value of the scrollbar. * * A horizontal scrollbar event is K_SPECIAL, KS_HOR_SCROLLBAR, * KE_FILLER followed by four bytes representing a long_u which is the * new value of the scrollbar. */ # ifdef FEAT_MENU else if (key_name[0] == (int)KS_MENU) { long_u val; num_bytes = get_long_from_buf(tp + slen, &val); if (num_bytes == -1) return -1; current_menu = (vimmenu_T *)val; slen += num_bytes; /* The menu may have been deleted right after it was used, check * for that. */ if (check_menu_pointer(root_menu, current_menu) == FAIL) { key_name[0] = KS_EXTRA; key_name[1] = (int)KE_IGNORE; } } # endif # ifdef FEAT_GUI_TABLINE else if (key_name[0] == (int)KS_TABLINE) { /* Selecting tabline tab or using its menu. */ num_bytes = get_bytes_from_buf(tp + slen, bytes, 1); if (num_bytes == -1) return -1; current_tab = (int)bytes[0]; if (current_tab == 255) /* -1 in a byte gives 255 */ current_tab = -1; slen += num_bytes; } else if (key_name[0] == (int)KS_TABMENU) { /* Selecting tabline tab or using its menu. */ num_bytes = get_bytes_from_buf(tp + slen, bytes, 2); if (num_bytes == -1) return -1; current_tab = (int)bytes[0]; current_tabmenu = (int)bytes[1]; slen += num_bytes; } # endif # ifndef USE_ON_FLY_SCROLL else if (key_name[0] == (int)KS_VER_SCROLLBAR) { long_u val; /* Get the last scrollbar event in the queue of the same type */ j = 0; for (i = 0; tp[j] == CSI && tp[j + 1] == KS_VER_SCROLLBAR && tp[j + 2] != NUL; ++i) { j += 3; num_bytes = get_bytes_from_buf(tp + j, bytes, 1); if (num_bytes == -1) break; if (i == 0) current_scrollbar = (int)bytes[0]; else if (current_scrollbar != (int)bytes[0]) break; j += num_bytes; num_bytes = get_long_from_buf(tp + j, &val); if (num_bytes == -1) break; scrollbar_value = val; j += num_bytes; slen = j; } if (i == 0) /* not enough characters to make one */ return -1; } else if (key_name[0] == (int)KS_HOR_SCROLLBAR) { long_u val; /* Get the last horiz. scrollbar event in the queue */ j = 0; for (i = 0; tp[j] == CSI && tp[j + 1] == KS_HOR_SCROLLBAR && tp[j + 2] != NUL; ++i) { j += 3; num_bytes = get_long_from_buf(tp + j, &val); if (num_bytes == -1) break; scrollbar_value = val; j += num_bytes; slen = j; } if (i == 0) /* not enough characters to make one */ return -1; } # endif /* !USE_ON_FLY_SCROLL */ #endif /* FEAT_GUI */ /* * Change <xHome> to <Home>, <xUp> to <Up>, etc. */ key = handle_x_keys(TERMCAP2KEY(key_name[0], key_name[1])); /* * Add any modifier codes to our string. */ new_slen = 0; /* Length of what will replace the termcode */ if (modifiers != 0) { /* Some keys have the modifier included. Need to handle that here * to make mappings work. */ key = simplify_key(key, &modifiers); if (modifiers != 0) { string[new_slen++] = K_SPECIAL; string[new_slen++] = (int)KS_MODIFIER; string[new_slen++] = modifiers; } } /* Finally, add the special key code to our string */ key_name[0] = KEY2TERMCAP0(key); key_name[1] = KEY2TERMCAP1(key); if (key_name[0] == KS_KEY) { /* from ":set <M-b>=xx" */ #ifdef FEAT_MBYTE if (has_mbyte) new_slen += (*mb_char2bytes)(key_name[1], string + new_slen); else #endif string[new_slen++] = key_name[1]; } else if (new_slen == 0 && key_name[0] == KS_EXTRA && key_name[1] == KE_IGNORE) { /* Do not put K_IGNORE into the buffer, do return KEYLEN_REMOVED * to indicate what happened. */ retval = KEYLEN_REMOVED; } else { string[new_slen++] = K_SPECIAL; string[new_slen++] = key_name[0]; string[new_slen++] = key_name[1]; } string[new_slen] = NUL; extra = new_slen - slen; if (buf == NULL) { if (extra < 0) /* remove matched chars, taking care of noremap */ del_typebuf(-extra, offset); else if (extra > 0) /* insert the extra space we need */ ins_typebuf(string + slen, REMAP_YES, offset, FALSE, FALSE); /* * Careful: del_typebuf() and ins_typebuf() may have reallocated * typebuf.tb_buf[]! */ mch_memmove(typebuf.tb_buf + typebuf.tb_off + offset, string, (size_t)new_slen); } else { if (extra < 0) /* remove matched characters */ mch_memmove(buf + offset, buf + offset - extra, (size_t)(*buflen + offset + extra)); else if (extra > 0) { /* Insert the extra space we need. If there is insufficient * space return -1. */ if (*buflen + extra + new_slen >= bufsize) return -1; mch_memmove(buf + offset + extra, buf + offset, (size_t)(*buflen - offset)); } mch_memmove(buf + offset, string, (size_t)new_slen); *buflen = *buflen + extra + new_slen; } return retval == 0 ? (len + extra + offset) : retval; } return 0; /* no match found */ } /* * Replace any terminal code strings in from[] with the equivalent internal * vim representation. This is used for the "from" and "to" part of a * mapping, and the "to" part of a menu command. * Any strings like "<C-UP>" are also replaced, unless 'cpoptions' contains * '<'. * K_SPECIAL by itself is replaced by K_SPECIAL KS_SPECIAL KE_FILLER. * * The replacement is done in result[] and finally copied into allocated * memory. If this all works well *bufp is set to the allocated memory and a * pointer to it is returned. If something fails *bufp is set to NULL and from * is returned. * * CTRL-V characters are removed. When "from_part" is TRUE, a trailing CTRL-V * is included, otherwise it is removed (for ":map xx ^V", maps xx to * nothing). When 'cpoptions' does not contain 'B', a backslash can be used * instead of a CTRL-V. */ char_u * replace_termcodes(from, bufp, from_part, do_lt, special) char_u *from; char_u **bufp; int from_part; int do_lt; /* also translate <lt> */ int special; /* always accept <key> notation */ { int i; int slen; int key; int dlen = 0; char_u *src; int do_backslash; /* backslash is a special character */ int do_special; /* recognize <> key codes */ int do_key_code; /* recognize raw key codes */ char_u *result; /* buffer for resulting string */ do_backslash = (vim_strchr(p_cpo, CPO_BSLASH) == NULL); do_special = (vim_strchr(p_cpo, CPO_SPECI) == NULL) || special; do_key_code = (vim_strchr(p_cpo, CPO_KEYCODE) == NULL); /* * Allocate space for the translation. Worst case a single character is * replaced by 6 bytes (shifted special key), plus a NUL at the end. */ result = alloc((unsigned)STRLEN(from) * 6 + 1); if (result == NULL) /* out of memory */ { *bufp = NULL; return from; } src = from; /* * Check for #n at start only: function key n */ if (from_part && src[0] == '#' && VIM_ISDIGIT(src[1])) /* function key */ { result[dlen++] = K_SPECIAL; result[dlen++] = 'k'; if (src[1] == '0') result[dlen++] = ';'; /* #0 is F10 is "k;" */ else result[dlen++] = src[1]; /* #3 is F3 is "k3" */ src += 2; } /* * Copy each byte from *from to result[dlen] */ while (*src != NUL) { /* * If 'cpoptions' does not contain '<', check for special key codes, * like "<C-S-LeftMouse>" */ if (do_special && (do_lt || STRNCMP(src, "<lt>", 4) != 0)) { #ifdef FEAT_EVAL /* * Replace <SID> by K_SNR <script-nr> _. * (room: 5 * 6 = 30 bytes; needed: 3 + <nr> + 1 <= 14) */ if (STRNICMP(src, "<SID>", 5) == 0) { if (current_SID <= 0) EMSG(_(e_usingsid)); else { src += 5; result[dlen++] = K_SPECIAL; result[dlen++] = (int)KS_EXTRA; result[dlen++] = (int)KE_SNR; sprintf((char *)result + dlen, "%ld", (long)current_SID); dlen += (int)STRLEN(result + dlen); result[dlen++] = '_'; continue; } } #endif slen = trans_special(&src, result + dlen, TRUE); if (slen) { dlen += slen; continue; } } /* * If 'cpoptions' does not contain 'k', see if it's an actual key-code. * Note that this is also checked after replacing the <> form. * Single character codes are NOT replaced (e.g. ^H or DEL), because * it could be a character in the file. */ if (do_key_code) { i = find_term_bykeys(src); if (i >= 0) { result[dlen++] = K_SPECIAL; result[dlen++] = termcodes[i].name[0]; result[dlen++] = termcodes[i].name[1]; src += termcodes[i].len; /* If terminal code matched, continue after it. */ continue; } } #ifdef FEAT_EVAL if (do_special) { char_u *p, *s, len; /* * Replace <Leader> by the value of "mapleader". * Replace <LocalLeader> by the value of "maplocalleader". * If "mapleader" or "maplocalleader" isn't set use a backslash. */ if (STRNICMP(src, "<Leader>", 8) == 0) { len = 8; p = get_var_value((char_u *)"g:mapleader"); } else if (STRNICMP(src, "<LocalLeader>", 13) == 0) { len = 13; p = get_var_value((char_u *)"g:maplocalleader"); } else { len = 0; p = NULL; } if (len != 0) { /* Allow up to 8 * 6 characters for "mapleader". */ if (p == NULL || *p == NUL || STRLEN(p) > 8 * 6) s = (char_u *)"\\"; else s = p; while (*s != NUL) result[dlen++] = *s++; src += len; continue; } } #endif /* * Remove CTRL-V and ignore the next character. * For "from" side the CTRL-V at the end is included, for the "to" * part it is removed. * If 'cpoptions' does not contain 'B', also accept a backslash. */ key = *src; if (key == Ctrl_V || (do_backslash && key == '\\')) { ++src; /* skip CTRL-V or backslash */ if (*src == NUL) { if (from_part) result[dlen++] = key; break; } } #ifdef FEAT_MBYTE /* skip multibyte char correctly */ for (i = (*mb_ptr2len)(src); i > 0; --i) #endif { /* * If the character is K_SPECIAL, replace it with K_SPECIAL * KS_SPECIAL KE_FILLER. * If compiled with the GUI replace CSI with K_CSI. */ if (*src == K_SPECIAL) { result[dlen++] = K_SPECIAL; result[dlen++] = KS_SPECIAL; result[dlen++] = KE_FILLER; } # ifdef FEAT_GUI else if (*src == CSI) { result[dlen++] = K_SPECIAL; result[dlen++] = KS_EXTRA; result[dlen++] = (int)KE_CSI; } # endif else result[dlen++] = *src; ++src; } } result[dlen] = NUL; /* * Copy the new string to allocated memory. * If this fails, just return from. */ if ((*bufp = vim_strsave(result)) != NULL) from = *bufp; vim_free(result); return from; } /* * Find a termcode with keys 'src' (must be NUL terminated). * Return the index in termcodes[], or -1 if not found. */ int find_term_bykeys(src) char_u *src; { int i; int slen = (int)STRLEN(src); for (i = 0; i < tc_len; ++i) { if (slen == termcodes[i].len && STRNCMP(termcodes[i].code, src, (size_t)slen) == 0) return i; } return -1; } /* * Gather the first characters in the terminal key codes into a string. * Used to speed up check_termcode(). */ static void gather_termleader() { int i; int len = 0; #ifdef FEAT_GUI if (gui.in_use) termleader[len++] = CSI; /* the GUI codes are not in termcodes[] */ #endif #ifdef FEAT_TERMRESPONSE if (check_for_codes) termleader[len++] = DCS; /* the termcode response starts with DCS in 8-bit mode */ #endif termleader[len] = NUL; for (i = 0; i < tc_len; ++i) if (vim_strchr(termleader, termcodes[i].code[0]) == NULL) { termleader[len++] = termcodes[i].code[0]; termleader[len] = NUL; } need_gather = FALSE; } /* * Show all termcodes (for ":set termcap") * This code looks a lot like showoptions(), but is different. */ void show_termcodes() { int col; int *items; int item_count; int run; int row, rows; int cols; int i; int len; #define INC3 27 /* try to make three columns */ #define INC2 40 /* try to make two columns */ #define GAP 2 /* spaces between columns */ if (tc_len == 0) /* no terminal codes (must be GUI) */ return; items = (int *)alloc((unsigned)(sizeof(int) * tc_len)); if (items == NULL) return; /* Highlight title */ MSG_PUTS_TITLE(_("\n--- Terminal keys ---")); /* * do the loop two times: * 1. display the short items (non-strings and short strings) * 2. display the medium items (medium length strings) * 3. display the long items (remaining strings) */ for (run = 1; run <= 3 && !got_int; ++run) { /* * collect the items in items[] */ item_count = 0; for (i = 0; i < tc_len; i++) { len = show_one_termcode(termcodes[i].name, termcodes[i].code, FALSE); if (len <= INC3 - GAP ? run == 1 : len <= INC2 - GAP ? run == 2 : run == 3) items[item_count++] = i; } /* * display the items */ if (run <= 2) { cols = (Columns + GAP) / (run == 1 ? INC3 : INC2); if (cols == 0) cols = 1; rows = (item_count + cols - 1) / cols; } else /* run == 3 */ rows = item_count; for (row = 0; row < rows && !got_int; ++row) { msg_putchar('\n'); /* go to next line */ if (got_int) /* 'q' typed in more */ break; col = 0; for (i = row; i < item_count; i += rows) { msg_col = col; /* make columns */ show_one_termcode(termcodes[items[i]].name, termcodes[items[i]].code, TRUE); if (run == 2) col += INC2; else col += INC3; } out_flush(); ui_breakcheck(); } } vim_free(items); } /* * Show one termcode entry. * Output goes into IObuff[] */ int show_one_termcode(name, code, printit) char_u *name; char_u *code; int printit; { char_u *p; int len; if (name[0] > '~') { IObuff[0] = ' '; IObuff[1] = ' '; IObuff[2] = ' '; IObuff[3] = ' '; } else { IObuff[0] = 't'; IObuff[1] = '_'; IObuff[2] = name[0]; IObuff[3] = name[1]; } IObuff[4] = ' '; p = get_special_key_name(TERMCAP2KEY(name[0], name[1]), 0); if (p[1] != 't') STRCPY(IObuff + 5, p); else IObuff[5] = NUL; len = (int)STRLEN(IObuff); do IObuff[len++] = ' '; while (len < 17); IObuff[len] = NUL; if (code == NULL) len += 4; else len += vim_strsize(code); if (printit) { msg_puts(IObuff); if (code == NULL) msg_puts((char_u *)"NULL"); else msg_outtrans(code); } return len; } #if defined(FEAT_TERMRESPONSE) || defined(PROTO) /* * For Xterm >= 140 compiled with OPT_TCAP_QUERY: Obtain the actually used * termcap codes from the terminal itself. * We get them one by one to avoid a very long response string. */ static int xt_index_in = 0; static int xt_index_out = 0; static void req_codes_from_term() { xt_index_out = 0; xt_index_in = 0; req_more_codes_from_term(); } static void req_more_codes_from_term() { char buf[11]; int old_idx = xt_index_out; /* Don't do anything when going to exit. */ if (exiting) return; /* Send up to 10 more requests out than we received. Avoid sending too * many, there can be a buffer overflow somewhere. */ while (xt_index_out < xt_index_in + 10 && key_names[xt_index_out] != NULL) { sprintf(buf, "\033P+q%02x%02x\033\\", key_names[xt_index_out][0], key_names[xt_index_out][1]); out_str_nf((char_u *)buf); ++xt_index_out; } /* Send the codes out right away. */ if (xt_index_out != old_idx) out_flush(); } /* * Decode key code response from xterm: '<Esc>P1+r<name>=<string><Esc>\'. * A "0" instead of the "1" indicates a code that isn't supported. * Both <name> and <string> are encoded in hex. * "code" points to the "0" or "1". */ static void got_code_from_term(code, len) char_u *code; int len; { #define XT_LEN 100 char_u name[3]; char_u str[XT_LEN]; int i; int j = 0; int c; /* A '1' means the code is supported, a '0' means it isn't. * When half the length is > XT_LEN we can't use it. * Our names are currently all 2 characters. */ if (code[0] == '1' && code[7] == '=' && len / 2 < XT_LEN) { /* Get the name from the response and find it in the table. */ name[0] = hexhex2nr(code + 3); name[1] = hexhex2nr(code + 5); name[2] = NUL; for (i = 0; key_names[i] != NULL; ++i) { if (STRCMP(key_names[i], name) == 0) { xt_index_in = i; break; } } if (key_names[i] != NULL) { for (i = 8; (c = hexhex2nr(code + i)) >= 0; i += 2) str[j++] = c; str[j] = NUL; if (name[0] == 'C' && name[1] == 'o') { /* Color count is not a key code. */ i = atoi((char *)str); if (i != t_colors) { /* Nr of colors changed, initialize highlighting and * redraw everything. This causes a redraw, which usually * clears the message. Try keeping the message if it * might work. */ set_keep_msg_from_hist(); set_color_count(i); init_highlight(TRUE, FALSE); redraw_later(CLEAR); } } else { /* First delete any existing entry with the same code. */ i = find_term_bykeys(str); if (i >= 0) del_termcode_idx(i); add_termcode(name, str, ATC_FROM_TERM); } } } /* May request more codes now that we received one. */ ++xt_index_in; req_more_codes_from_term(); } /* * Check if there are any unanswered requests and deal with them. * This is called before starting an external program or getting direct * keyboard input. We don't want responses to be send to that program or * handled as typed text. */ static void check_for_codes_from_term() { int c; /* If no codes requested or all are answered, no need to wait. */ if (xt_index_out == 0 || xt_index_out == xt_index_in) return; /* Vgetc() will check for and handle any response. * Keep calling vpeekc() until we don't get any responses. */ ++no_mapping; ++allow_keys; for (;;) { c = vpeekc(); if (c == NUL) /* nothing available */ break; /* If a response is recognized it's replaced with K_IGNORE, must read * it from the input stream. If there is no K_IGNORE we can't do * anything, break here (there might be some responses further on, but * we don't want to throw away any typed chars). */ if (c != K_SPECIAL && c != K_IGNORE) break; c = vgetc(); if (c != K_IGNORE) { vungetc(c); break; } } --no_mapping; --allow_keys; } #endif #if defined(FEAT_CMDL_COMPL) || defined(PROTO) /* * Translate an internal mapping/abbreviation representation into the * corresponding external one recognized by :map/:abbrev commands; * respects the current B/k/< settings of 'cpoption'. * * This function is called when expanding mappings/abbreviations on the * command-line, and for building the "Ambiguous mapping..." error message. * * It uses a growarray to build the translation string since the * latter can be wider than the original description. The caller has to * free the string afterwards. * * Returns NULL when there is a problem. */ char_u * translate_mapping(str, expmap) char_u *str; int expmap; /* TRUE when expanding mappings on command-line */ { garray_T ga; int c; int modifiers; int cpo_bslash; int cpo_special; int cpo_keycode; ga_init(&ga); ga.ga_itemsize = 1; ga.ga_growsize = 40; cpo_bslash = (vim_strchr(p_cpo, CPO_BSLASH) != NULL); cpo_special = (vim_strchr(p_cpo, CPO_SPECI) != NULL); cpo_keycode = (vim_strchr(p_cpo, CPO_KEYCODE) == NULL); for (; *str; ++str) { c = *str; if (c == K_SPECIAL && str[1] != NUL && str[2] != NUL) { modifiers = 0; if (str[1] == KS_MODIFIER) { str++; modifiers = *++str; c = *++str; } if (cpo_special && cpo_keycode && c == K_SPECIAL && !modifiers) { int i; /* try to find special key in termcodes */ for (i = 0; i < tc_len; ++i) if (termcodes[i].name[0] == str[1] && termcodes[i].name[1] == str[2]) break; if (i < tc_len) { ga_concat(&ga, termcodes[i].code); str += 2; continue; /* for (str) */ } } if (c == K_SPECIAL && str[1] != NUL && str[2] != NUL) { if (expmap && cpo_special) { ga_clear(&ga); return NULL; } c = TO_SPECIAL(str[1], str[2]); if (c == K_ZERO) /* display <Nul> as ^@ */ c = NUL; str += 2; } if (IS_SPECIAL(c) || modifiers) /* special key */ { if (expmap && cpo_special) { ga_clear(&ga); return NULL; } ga_concat(&ga, get_special_key_name(c, modifiers)); continue; /* for (str) */ } } if (c == ' ' || c == '\t' || c == Ctrl_J || c == Ctrl_V || (c == '<' && !cpo_special) || (c == '\\' && !cpo_bslash)) ga_append(&ga, cpo_bslash ? Ctrl_V : '\\'); if (c) ga_append(&ga, c); } ga_append(&ga, NUL); return (char_u *)(ga.ga_data); } #endif #if (defined(WIN3264) && !defined(FEAT_GUI)) || defined(PROTO) static char ksme_str[20]; static char ksmr_str[20]; static char ksmd_str[20]; /* * For Win32 console: update termcap codes for existing console attributes. */ void update_tcap(attr) int attr; { struct builtin_term *p; p = find_builtin_term(DEFAULT_TERM); sprintf(ksme_str, IF_EB("\033|%dm", ESC_STR "|%dm"), attr); sprintf(ksmd_str, IF_EB("\033|%dm", ESC_STR "|%dm"), attr | 0x08); /* FOREGROUND_INTENSITY */ sprintf(ksmr_str, IF_EB("\033|%dm", ESC_STR "|%dm"), ((attr & 0x0F) << 4) | ((attr & 0xF0) >> 4)); while (p->bt_string != NULL) { if (p->bt_entry == (int)KS_ME) p->bt_string = &ksme_str[0]; else if (p->bt_entry == (int)KS_MR) p->bt_string = &ksmr_str[0]; else if (p->bt_entry == (int)KS_MD) p->bt_string = &ksmd_str[0]; ++p; } } #endif
zyz2011-vim
src/term.c
C
gpl2
151,574
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * GUI support by Robert Webb * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * Windows GUI: main program (DLL) entry point: * * Ron Aaron <ronaharon@yahoo.com> wrote this and the DLL support code. */ #ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN #endif #include <windows.h> BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { return TRUE; }
zyz2011-vim
src/os_w32dll.c
C
gpl2
623
/* os_vms_conf.h. Replaces auto/config.h for VMS */ #define CASE_INSENSITIVE_FILENAME /* Open VMS is case insensitive */ #define SPACE_IN_FILENAME /* There could be space between user and passwd */ #define FNAME_ILLEGAL "|*#?%" /* Illegal characters in a file name */ #define BINARY_FILE_IO /* Use binary fileio */ #define USE_GETCWD #define USE_SYSTEM /* Define when terminfo support found */ #undef TERMINFO /* Define when termcap.h contains ospeed */ /* #define HAVE_OSPEED */ /* Define when termcap.h contains UP, BC and PC */ /* #define HAVE_UP_BC_PC */ /* Define when termcap.h defines outfuntype */ /*#define HAVE_OUTFUNTYPE */ /* Define when __DATE__ " " __TIME__ can be used */ #define HAVE_DATE_TIME /* Defined to the size of an int */ #define SIZEOF_INT 4 /* #undef USEBCOPY */ #define USEMEMMOVE /* #undef USEMEMCPY */ /* Define when "man -s 2" is to be used */ /* #undef USEMAN_S */ /* Define to empty if the keyword does not work. */ /* #undef const */ /* Define to `int' if <sys/types.h> doesn't define. */ /* #undef mode_t */ /* Define to `long' if <sys/types.h> doesn't define. */ /* #undef off_t */ /* Define to `long' if <sys/types.h> doesn't define. */ /* #undef pid_t */ /* Define to `unsigned' if <sys/types.h> doesn't define. */ /* #undef size_t */ /* Define to `int' if <sys/types.h> doesn't define. */ /* #undef uid_t */ /* Define to `unsigned int' or other type that is 32 bit. */ #define UINT32_T unsigned int /* Define to `int' if <sys/types.h> doesn't define. */ /* #undef gid_t */ /* Define to `long' if <sys/types.h> doesn't define. */ /* #undef ino_t */ /* Define if you have the nanosleep() function. */ /* #undef HAVE_NANOSLEEP */ /* Define if you can safely include both <sys/time.h> and <time.h>. */ #define TIME_WITH_SYS_TIME /* Define if you can safely include both <sys/time.h> and <sys/select.h>. */ /* #undef SYS_SELECT_WITH_SYS_TIME */ /* Define as the return type of signal handlers (int or void). */ #define RETSIGTYPE void /* Define as the command at the end of signal handlers ("" or "return 0;"). */ #define SIGRETURN return /* Define if struct sigcontext is present */ #define HAVE_SIGCONTEXT /* Define if toupper/tolower only work on lower/uppercase characters */ /* #define BROKEN_TOUPPER */ /* Define if tgetstr() has a second argument that is (char *) */ /* #undef TGETSTR_CHAR_P */ /* Define if you have the sigset() function. */ /* #undef HAVE_SIGSET */ /* Define if you have the setpgid() function. */ /* #undef HAVE_SETPGID */ /* Define if you have the setsid() function. */ /* #undef HAVE_SETSID */ /* Define if you have the sigset() function. */ /* #undef HAVE_SIGSET */ #define TGETENT_ZERO_ERR #define HAVE_GETCWD #define HAVE_STRCSPN #define HAVE_STRTOL #define HAVE_TGETENT #define HAVE_MEMSET #define HAVE_MEMCMP #define HAVE_STRERROR #define HAVE_FCHOWN #define HAVE_RENAME #define HAVE_QSORT #define HAVE_FSYNC #define HAVE_GETPWUID #define HAVE_GETPWNAM #define HAVE_STDARG_H #define HAVE_STDLIB_H #define HAVE_STRING_H #define HAVE_ERRNO_H #define HAVE_OPENDIR #define HAVE_PUTENV #define HAVE_SETENV #define HAVE_SETJMP_H #define HAVE_MATH_H #define HAVE_FLOAT_FUNCS #undef HAVE_DIRENT_H #undef HAVE_SYS_NDIR_H #undef HAVE_SYS_DIR_H #undef HAVE_NDIR_H #undef HAVE_SYS_WAIT_H #undef HAVE_UNION_WAIT #undef HAVE_SYS_SELECT_H #undef HAVE_SYS_UTSNAME_H #undef HAVE_SYS_SYSTEMINFO_H #undef HAVE_TERMCAP_H #undef HAVE_SGTTY_H #undef HAVE_SYS_IOCTL_H #undef HAVE_TERMIO_H #undef HAVE_STROPTS_H #undef HAVE_SYS_STREAM_H #undef HAVE_SYS_PTEM_H #undef HAVE_TERMIOS_H #undef HAVE_LIBC_H #undef HAVE_SYS_STATFS_H #undef HAVE_SYS_POLL_H #undef HAVE_PWD_H #undef HAVE_FCHDIR /* Hardware specific */ #ifdef VAX #undef HAVE_GETTIMEOFDAY #undef HAVE_USLEEP #undef HAVE_STRCASECMP #undef HAVE_STRINGS_H #undef HAVE_SIGSETJMP #else #define HAVE_GETTIMEOFDAY #define HAVE_USLEEP #define HAVE_STRCASECMP #define HAVE_STRINGS_H #define HAVE_SIGSETJMP #endif /* Compiler specific */ #ifdef VAXC #undef HAVE_SELECT #undef HAVE_FCNTL_H #undef HAVE_UNISTD_H #undef HAVE_SYS_TIME_H #undef HAVE_LOCALE_H #define BROKEN_LOCALE #undef HAVE_ICONV_H #undef HAVE_ICONV #undef DYNAMIC_ICONV #undef HAVE_STRFTIME #else #define HAVE_SELECT #define HAVE_FCNTL_H #define HAVE_UNISTD_H 1 #define HAVE_SYS_TIME_H #define HAVE_LOCALE_H #define BROKEN_LOCALE #undef HAVE_ICONV_H #undef HAVE_ICONV #undef DYNAMIC_ICONV #define HAVE_STRFTIME #endif /* GUI support defines */ #if defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_GTK) #define HAVE_X11 #define USE_FONTSET #undef X_LOCALE #endif
zyz2011-vim
src/os_vms_conf.h
C
gpl2
4,606
Tests for string and html text objects. vim: set ft=vim : Note that the end-of-line moves the cursor to the next test line. Also test match() and matchstr() STARTTEST :so small.vim /^start:/ da" 0va'a'rx 02f`da` 0fXdi" 03f'vi'ry :set quoteescape=+*- di` $F"va"oha"i"rz :" /^<begin jfXdit 0fXdit fXdat 0fXdat :" :put =matchstr(\"abcd\", \".\", 0, 2) " b :put =matchstr(\"abcd\", \"..\", 0, 2) " bc :put =matchstr(\"abcd\", \".\", 2, 0) " c (zero and negative -> first match) :put =matchstr(\"abcd\", \".\", 0, -1) " a :put =match(\"abcd\", \".\", 0, 5) " -1 :put =match(\"abcd\", \".\", 0, -1) " 0 :/^start:/,/^end:/wq! test.out ENDTEST start: "wo\"rd\\" foo 'foo' 'bar' 'piep' bla bla `quote` blah out " in "noXno" "'" 'blah' rep 'buh' bla `s*`d-`+++`l**` b`la voo "nah" sdf " asdf" sdf " sdf" sd <begin> -<b>asdf<i>Xasdf</i>asdf</b>- -<b>asdX<i>a<i />sdf</i>asdf</b>- -<b>asdf<i>Xasdf</i>asdf</b>- -<b>asdX<i>as<b />df</i>asdf</b>- </begin> end:
zyz2011-vim
src/testdir/test53.in
Vim Script
gpl2
952
# # Makefile to run all tests for Vim, on Dos-like machines # with sh.exe or zsh.exe in the path or not. # # Author: Bill McCarthy # # Note that test54 has been removed until it is fixed. # # Requires a set of Unix tools: echo, diff, etc. ifneq (sh.exe, $(SHELL)) DEL = rm -f MV = mv CP = cp DIRSLASH = / else DEL = del MV = rename CP = copy DIRSLASH = \\ endif VIMPROG = ..$(DIRSLASH)vim # Omitted: # test2 "\\tmp" doesn't work. # test10 'errorformat' is different # test12 can't unlink a swap file # test25 uses symbolic link # test27 can't edit file with "*" in file name # test31 16 bit version runs out of memory... SCRIPTS16 = test1.out test19.out test20.out test22.out \ test23.out test24.out test28.out test29.out \ test35.out test36.out test43.out \ test44.out test45.out test46.out test47.out \ test48.out test51.out test53.out \ test55.out test56.out test57.out test58.out test59.out \ test60.out test61.out test62.out test63.out test64.out # Had to remove test54 which doesn't work yet. # test54.out SCRIPTS = test3.out test4.out test5.out test6.out test7.out \ test8.out test9.out test11.out test13.out test14.out \ test15.out test17.out test18.out test21.out test26.out \ test30.out test31.out test32.out test33.out test34.out \ test37.out test38.out test39.out test40.out test41.out \ test42.out test52.out test65.out test66.out test67.out \ test68.out test69.out test71.out test72.out test73.out \ test74.out test75.out test76.out test77.out test78.out \ test79.out test80.out test81.out test82.out test83.out \ test84.out test85.out SCRIPTS32 = test50.out test70.out SCRIPTS_GUI = test16.out .SUFFIXES: .in .out vimall: fixff $(SCRIPTS16) $(SCRIPTS) $(SCRIPTS_GUI) $(SCRIPTS32) echo ALL DONE nongui: fixff $(SCRIPTS16) $(SCRIPTS) echo ALL DONE small: echo ALL DONE gui: fixff $(SCRIPTS16) $(SCRIPTS) $(SCRIPTS_GUI) echo ALL DONE win32: fixff $(SCRIPTS16) $(SCRIPTS) $(SCRIPTS32) echo ALL DONE fixff: -$(VIMPROG) -u dos.vim --noplugin "+argdo set ff=dos|upd" +q *.in *.ok -$(VIMPROG) -u dos.vim --noplugin "+argdo set ff=unix|upd" +q \ dotest.in test60.ok test71.ok test74.ok clean: -$(DEL) *.out -$(DEL) test.ok -$(DEL) small.vim -$(DEL) tiny.vim -$(DEL) mbyte.vim -$(DEL) mzscheme.vim -$(DEL) X* -$(DEL) viminfo .in.out: $(CP) $*.ok test.ok $(VIMPROG) -u dos.vim -U NONE --noplugin -s dotest.in $*.in diff test.out $*.ok -$(DEL) $*.out $(MV) test.out $*.out -$(DEL) X* -$(DEL) test.ok -$(DEL) viminfo
zyz2011-vim
src/testdir/Make_ming.mak
Makefile
gpl2
2,537
" Settings for test script execution " Always use "CMD.EXE", don't use the value of "$SHELL". set shell=CMD.EXE shellquote= shellxquote= shellcmdflag=/c shellredir=>
zyz2011-vim
src/testdir/os2.vim
Vim Script
gpl2
166
Tests for completefunc/omnifunc. vim: set ft=vim : STARTTEST :"Test that nothing happens if the 'completefunc' opens :"a new window (no completion, no crash) :so small.vim :function! DummyCompleteOne(findstart, base) : if a:findstart : return 0 : else : wincmd n : return ['onedef', 'oneDEF'] : endif :endfunction :setlocal completefunc=DummyCompleteOne /^one A:q! :function! DummyCompleteTwo(findstart, base) : if a:findstart : wincmd n : return 0 : else : return ['twodef', 'twoDEF'] : endif :endfunction :setlocal completefunc=DummyCompleteTwo /^two A:q! :"Test that 'completefunc' works when it's OK. :function! DummyCompleteThree(findstart, base) : if a:findstart : return 0 : else : return ['threedef', 'threeDEF'] : endif :endfunction :setlocal completefunc=DummyCompleteThree /^three A:/^+++/,/^three/w! test.out :qa! ENDTEST +++ one two three
zyz2011-vim
src/testdir/test76.in
Vim Script
gpl2
899
# # Makefile to run all tests for Vim on VMS # # Authors: Zoltan Arpadffy, <arpadffy@polarhome.com> # Sandor Kopanyi, <sandor.kopanyi@mailbox.hu> # # Last change: 2012 Apr 05 # # This has been tested on VMS 6.2 to 8.3 on DEC Alpha, VAX and IA64. # Edit the lines in the Configuration section below to select. # # Execute with: # mms/descrip=Make_vms.mms # Cleanup with: # mms/descrip=Make_vms.mms clean # # Make files are MMK compatible. # # NOTE: You can run this script just in X/Window environment. It will # create a new terminals, therefore you have to set up your DISPLAY # logical. More info in VMS documentation or with: help set disp. # ####################################################################### # Configuration section. ####################################################################### # Uncomment if you want tests in GUI mode. Terminal mode is default. # WANT_GUI = YES # Comment out if you want to run Unix specific tests as well, but please # be aware, that on OpenVMS will fail, because of cat, rm, etc commands # and directory handling. # WANT_UNIX = YES # Comment out if you want to run Win32 specific tests as well, but please # be aware, that on OpenVMS will fail, because of cat, rm, etc commands # and directory handling. # WANT_WIN = YES # Comment out if you want to run spell checker tests. # They fail because VMS does not support file names. # WANT_SPELL = YES # Comment out if you want to run mzschema tests. # It fails because VMS does not support this feature yet. # WANT_MZSCH = YES # Comment out if you have gzip on your system # HAVE_GZIP = YES # Comment out if you have GNU compatible diff on your system # HAVE_GDIFF = YES ####################################################################### # End of configuration section. # # Please, do not change anything below without programming experience. ####################################################################### VIMPROG = <->vim.exe .SUFFIXES : .out .in SCRIPT = test1.out test2.out test3.out test4.out test5.out \ test6.out test7.out test8.out test9.out test10a.out\ test13.out test14.out test15.out test17.out \ test18.out test19.out test20.out test21.out test22.out \ test23.out test24.out test26.out \ test28.out test29.out test30.out test31.out test32.out \ test33.out test34.out test35.out test36.out test37.out \ test38.out test39.out test40.out test41.out test42.out \ test43.out test44.out test45.out test46.out \ test48.out test51.out test53.out test54.out test55.out \ test56.out test57.out test60.out \ test61.out test62.out test63.out test64.out test65.out \ test66.out test67.out test68.out test69.out \ test71.out test72.out test74.out test75.out test76.out \ test77.out test78.out test79.out test80.out test81.out \ test82.out test83.out test84.out # Known problems: # Test 30: a problem around mac format - unknown reason # # Test 32: VMS is not case sensitive and all filenames are lowercase within Vim # (this should be changed in order to preserve the original filename) - should # be fixed. VMS allows just one dot in the filename # # Test 58 and 59: Failed/Hangs - VMS does not support spell files (file names # with too many dots). # # Test 72: unknown reason # Test 85: no Lua interface .IFDEF WANT_GUI SCRIPT_GUI = test16.out GUI_OPTION = -g .ENDIF .IFDEF WANT_UNIX SCRIPT_UNIX = test10.out test12.out test25.out test27.out test49.out test73.out .ENDIF .IFDEF WANT_WIN SCRIPT_WIN = test50.out test52.out .ENDIF .IFDEF WANT_SPELL SCRIPT_SPELL = test58.out test59.out .ENDIF .IFDEF WANT_MZSCH SCRIPT_MZSCH = test70.out .ENDIF .IFDEF HAVE_GZIP SCRIPT_GZIP = test11.out .ENDIF .IFDEF HAVE_GDIFF SCRIPT_GDIFF = test47.out .ENDIF .in.out : -@ !clean up before doing the test -@ if "''F$SEARCH("test.out.*")'" .NES. "" then delete/noconfirm/nolog test.out.* -@ if "''F$SEARCH("$*.out.*")'" .NES. "" then delete/noconfirm/nolog $*.out.* -@ write sys$output " " -@ write sys$output "-----------------------------------------------" -@ write sys$output " "$*" " -@ write sys$output "-----------------------------------------------" -@ !run the test -@ create/term/wait/nodetach mcr $(VIMPROG) $(GUI_OPTION) -u vms.vim --noplugin -s dotest.in $*.in -@ !analyse the result -@ directory /size/date test.out -@ if "''F$SEARCH("test.out.*")'" .NES. "" then rename/nolog test.out $*.out -@ if "''F$SEARCH("$*.out.*")'" .NES. "" then differences /par $*.out $*.ok; -@ !clean up after the test -@ if "''F$SEARCH("Xdotest.*")'" .NES. "" then delete/noconfirm/nolog Xdotest.*.* all : clean nolog $(START_WITH) $(SCRIPT) $(SCRIPT_GUI) $(SCRIPT_UNIX) $(SCRIPT_WIN) $(SCRIPT_SPELL) $(SCRIPT_GZIP) \ $(SCRIPT_GDIFF) $(SCRIPT_MZSCH) nolog -@ write sys$output " " -@ write sys$output "-----------------------------------------------" -@ write sys$output " All done" -@ write sys$output "-----------------------------------------------" -@ deassign sys$output -@ delete/noconfirm/nolog x*.*.* -@ type test.log nolog : -@ define sys$output test.log -@ write sys$output "-----------------------------------------------" -@ write sys$output " Standard VIM test cases" -@ write sys$output "-----------------------------------------------" -@ write sys$output " OpenVMS version: ''F$GETSYI("VERSION")'" -@ write sys$output " Vim version:" -@ mcr $(VIMPROG) --version -@ write sys$output " Test date:" -@ show time -@ write sys$output "-----------------------------------------------" -@ write sys$output " Test results:" -@ write sys$output "-----------------------------------------------" -@ write sys$output "MAKE_VMS.MMS options:" -@ write sys$output " WANT_GUI = ""$(WANT_GUI)"" " -@ write sys$output " WANT_UNIX = ""$(WANT_UNIX)"" " -@ write sys$output " WANT_WIN = ""$(WANT_WIN)"" " -@ write sys$output " WANT_SPELL= ""$(WANT_SPELL)"" " -@ write sys$output " WANT_MZSCH= ""$(WANT_MZSCH)"" " -@ write sys$output " HAVE_GZIP = ""$(HAVE_GZIP)"" " -@ write sys$output " HAVE_GDIFF= ""$(HAVE_GDIFF)"" " -@ write sys$output "Default vimrc file is VMS.VIM:" -@ write sys$output "-----------------------------------------------" -@ type VMS.VIM clean : -@ if "''F$SEARCH("*.out")'" .NES. "" then delete/noconfirm/nolog *.out.* -@ if "''F$SEARCH("test.log")'" .NES. "" then delete/noconfirm/nolog test.log.* -@ if "''F$SEARCH("test.ok")'" .NES. "" then delete/noconfirm/nolog test.ok.* -@ if "''F$SEARCH("Xdotest.*")'" .NES. "" then delete/noconfirm/nolog Xdotest.*.* -@ if "''F$SEARCH("*.*_sw*")'" .NES. "" then delete/noconfirm/nolog *.*_sw*.* -@ if "''F$SEARCH("*.failed")'" .NES. "" then delete/noconfirm/nolog *.failed.* -@ if "''F$SEARCH("*.rej")'" .NES. "" then delete/noconfirm/nolog *.rej.* -@ if "''F$SEARCH("tiny.vim")'" .NES. "" then delete/noconfirm/nolog tiny.vim.* -@ if "''F$SEARCH("small.vim")'" .NES. "" then delete/noconfirm/nolog small.vim.* -@ if "''F$SEARCH("mbyte.vim")'" .NES. "" then delete/noconfirm/nolog mbyte.vim.* -@ if "''F$SEARCH("mzscheme.vim")'" .NES. "" then delete/noconfirm/nolog mzscheme.vim.* -@ if "''F$SEARCH("viminfo.*")'" .NES. "" then delete/noconfirm/nolog viminfo.*.*
zyz2011-vim
src/testdir/Make_vms.mms
Module Management System
gpl2
7,278
# # Makefile to run all tests for Vim, on Amiga # # Requires "rm", "csh" and "diff"! VIMPROG = /vim # These tests don't work (yet): # test2 "\\tmp" doesn't work # test10 'errorformat' is different # test11 "cat" doesn't work properly # test12 can't unlink a swap file # test25 uses symbolic link # test27 can't edit file with "*" # test52 only for Win32 # test85 no Lua interface SCRIPTS = test1.out test3.out test4.out test5.out test6.out \ test7.out test8.out test9.out \ test13.out test14.out test15.out test17.out \ test18.out test19.out test20.out test21.out test22.out \ test23.out test24.out test26.out \ test28.out test29.out test30.out test31.out test32.out \ test33.out test34.out test35.out test36.out test37.out \ test38.out test39.out test40.out test41.out test42.out \ test43.out test44.out test45.out test46.out test47.out \ test48.out test51.out test53.out test54.out test55.out \ test56.out test57.out test58.out test59.out test60.out \ test61.out test62.out test63.out test64.out test65.out \ test66.out test67.out test68.out test69.out test70.out \ test71.out test72.out test73.out test74.out test75.out \ test76.out test77.out test78.out test79.out test80.out \ test81.out test82.out test83.out test84.out .SUFFIXES: .in .out nongui: /tmp $(SCRIPTS) csh -c echo ALL DONE clean: csh -c \rm -rf *.out /tmp/* Xdotest small.vim tiny.vim mbyte.vim test.ok viminfo .in.out: copy $*.ok test.ok $(VIMPROG) -u amiga.vim -U NONE --noplugin -s dotest.in $*.in diff test.out $*.ok rename test.out $*.out -delete X#? ALL QUIET -delete test.ok # Create a directory for temp files /tmp: makedir /tmp # Manx requires all dependencies... test1.out: test1.in test2.out: test2.in test3.out: test3.in test4.out: test4.in test5.out: test5.in test6.out: test6.in test7.out: test7.in test8.out: test8.in test9.out: test9.in test10.out: test10.in test11.out: test11.in test12.out: test12.in test13.out: test13.in test14.out: test14.in test15.out: test15.in test16.out: test16.in test17.out: test17.in test18.out: test18.in test19.out: test19.in test20.out: test20.in test21.out: test21.in test22.out: test22.in test23.out: test23.in test24.out: test24.in test25.out: test25.in test26.out: test26.in test27.out: test27.in test28.out: test28.in test29.out: test29.in test30.out: test30.in test31.out: test31.in test32.out: test32.in test33.out: test33.in test34.out: test34.in test35.out: test35.in test36.out: test36.in test37.out: test37.in test38.out: test38.in test39.out: test39.in test40.out: test40.in test41.out: test41.in test42.out: test42.in test43.out: test43.in test44.out: test44.in test45.out: test45.in test46.out: test46.in test47.out: test47.in test48.out: test48.in test51.out: test51.in test53.out: test53.in test54.out: test54.in test55.out: test55.in test56.out: test56.in test57.out: test57.in test58.out: test58.in test59.out: test59.in test60.out: test60.in test61.out: test61.in test62.out: test62.in test63.out: test63.in test64.out: test64.in test65.out: test65.in test66.out: test66.in test67.out: test67.in test68.out: test68.in test69.out: test69.in test70.out: test70.in test71.out: test71.in test72.out: test72.in test73.out: test73.in test74.out: test74.in test75.out: test75.in test76.out: test76.in test77.out: test77.in test78.out: test78.in test79.out: test79.in test80.out: test80.in test81.out: test81.in test82.out: test82.in test83.out: test83.in test84.out: test84.in
zyz2011-vim
src/testdir/Make_amiga.mak
Makefile
gpl2
3,454
" Settings for test script execution set shell=csh map! /tmp t: cmap !rm !Delete all
zyz2011-vim
src/testdir/amiga.vim
Vim Script
gpl2
85
# # Makefile to run all tests for Vim # VIMPROG = ../vim # Uncomment this line to use valgrind for memory leaks and extra warnings. # The output goes into a file "valgrind.testN" # Vim should be compiled with EXITFREE to avoid false warnings. # This will make testing about 10 times as slow. # VALGRIND = valgrind --tool=memcheck --leak-check=yes --num-callers=15 --log-file=valgrind.$* SCRIPTS = test1.out test2.out test3.out test4.out test5.out test6.out \ test7.out test8.out test9.out test10.out test11.out \ test12.out test13.out test14.out test15.out test17.out \ test18.out test19.out test20.out test21.out test22.out \ test23.out test24.out test25.out test26.out test27.out \ test28.out test29.out test30.out test31.out test32.out \ test33.out test34.out test35.out test36.out test37.out \ test38.out test39.out test40.out test41.out test42.out \ test43.out test44.out test45.out test46.out test47.out \ test48.out test49.out test51.out test52.out test53.out \ test54.out test55.out test56.out test57.out test58.out \ test59.out test60.out test61.out test62.out test63.out \ test64.out test65.out test66.out test67.out test68.out \ test69.out test70.out test71.out test72.out test73.out \ test74.out test75.out test76.out test77.out test78.out \ test79.out test80.out test81.out test82.out test83.out \ test84.out test85.out SCRIPTS_GUI = test16.out .SUFFIXES: .in .out nongui: nolog $(SCRIPTS) report gui: nolog $(SCRIPTS) $(SCRIPTS_GUI) report report: @echo @echo 'Test results:' @/bin/sh -c "if test -f test.log; \ then cat test.log; echo TEST FAILURE; exit 1; \ else echo ALL DONE; \ fi" $(SCRIPTS) $(SCRIPTS_GUI): $(VIMPROG) clean: -rm -rf *.out *.failed *.rej *.orig test.log tiny.vim small.vim mbyte.vim mzscheme.vim test.ok X* valgrind.* viminfo test1.out: test1.in -rm -f $*.failed tiny.vim small.vim mbyte.vim mzscheme.vim test.ok X* viminfo $(VALGRIND) $(VIMPROG) -u unix.vim -U NONE --noplugin -s dotest.in $*.in @/bin/sh -c "if diff test.out $*.ok; \ then mv -f test.out $*.out; \ else echo; \ echo test1 FAILED - Something basic is wrong; \ echo; exit 1; fi" -rm -rf X* viminfo .in.out: -rm -rf $*.failed test.ok test.out X* viminfo cp $*.ok test.ok # Sleep a moment to avoid that the xterm title is messed up @-sleep .2 -$(VALGRIND) $(VIMPROG) -u unix.vim -U NONE --noplugin -s dotest.in $*.in @/bin/sh -c "if test -f test.out; then\ if diff test.out $*.ok; \ then mv -f test.out $*.out; \ else echo $* FAILED >>test.log; mv -f test.out $*.failed; \ fi \ else echo $* NO OUTPUT >>test.log; \ fi" # -rm -rf X* test.ok viminfo test49.out: test49.vim test60.out: test60.vim nolog: -rm -f test.log
zyz2011-vim
src/testdir/Makefile
Makefile
gpl2
2,721
Tests for List and Dictionary types. vim: set ft=vim : STARTTEST :so small.vim :fun Test(...) :" Creating List directly with different types :let l = [1, 'as''d', [1, 2, function("strlen")], {'a': 1},] :$put =string(l) :$put =string(l[-1]) :$put =string(l[-4]) :try : $put =string(l[-5]) :catch : $put =v:exception[:14] :endtry :" List slices :$put =string(l[:]) :$put =string(l[1:]) :$put =string(l[:-2]) :$put =string(l[0:8]) :$put =string(l[8:-1]) :" :" List identity :let ll = l :let lx = copy(l) :try : $put =(l == ll) . (l isnot ll) . (l is ll) . (l == lx) . (l is lx) . (l isnot lx) :catch : $put =v:exception :endtry :" :" Creating Dictionary directly with different types :let d = {001: 'asd', 'b': [1, 2, function('strlen')], -1: {'a': 1},} :$put =string(d) . d.1 :$put =string(sort(keys(d))) :$put =string (values(d)) :for [key, val] in items(d) : $put =key . ':' . string(val) : unlet key val :endfor :call extend (d, {3:33, 1:99}) :call extend(d, {'b':'bbb', 'c':'ccc'}, "keep") :try : call extend(d, {3:333,4:444}, "error") :catch : $put =v:exception[:15] . v:exception[-1:-1] :endtry :$put =string(d) :call filter(d, 'v:key =~ ''[ac391]''') :$put =string(d) :" :" Dictionary identity :let dd = d :let dx = copy(d) :try : $put =(d == dd) . (d isnot dd) . (d is dd) . (d == dx) . (d is dx) . (d isnot dx) :catch : $put =v:exception :endtry :" :" Changing var type should fail :try : let d = [] :catch : $put =v:exception[:14] . v:exception[-1:-1] :endtry :try : let l = {} :catch : $put =v:exception[:14] . v:exception[-1:-1] :endtry :" :" removing items with :unlet :unlet l[2] :$put =string(l) :let l = range(8) :try :unlet l[:3] :unlet l[1:] :catch :$put =v:exception :endtry :$put =string(l) :" :unlet d.c :unlet d[-1] :$put =string(d) :" :" removing items out of range: silently skip items that don't exist let l = [0, 1, 2, 3] :unlet l[2:1] :$put =string(l) let l = [0, 1, 2, 3] :unlet l[2:2] :$put =string(l) let l = [0, 1, 2, 3] :unlet l[2:3] :$put =string(l) let l = [0, 1, 2, 3] :unlet l[2:4] :$put =string(l) let l = [0, 1, 2, 3] :unlet l[2:5] :$put =string(l) let l = [0, 1, 2, 3] :unlet l[-1:2] :$put =string(l) let l = [0, 1, 2, 3] :unlet l[-2:2] :$put =string(l) let l = [0, 1, 2, 3] :unlet l[-3:2] :$put =string(l) let l = [0, 1, 2, 3] :unlet l[-4:2] :$put =string(l) let l = [0, 1, 2, 3] :unlet l[-5:2] :$put =string(l) let l = [0, 1, 2, 3] :unlet l[-6:2] :$put =string(l) :" :" assignment to a list :let l = [0, 1, 2, 3] :let [va, vb] = l[2:3] :$put =va :$put =vb :try : let [va, vb] = l :catch : $put =v:exception[:14] :endtry :try : let [va, vb] = l[1:1] :catch : $put =v:exception[:14] :endtry :" :" manipulating a big Dictionary (hashtable.c has a border of 1000 entries) :let d = {} :for i in range(1500) : let d[i] = 3000 - i :endfor :$put =d[0] . ' ' . d[100] . ' ' . d[999] . ' ' . d[1400] . ' ' . d[1499] :try : let n = d[1500] :catch : $put =substitute(v:exception, '\v(.{14}).*( \d{4}).*', '\1\2', '') :endtry :" lookup each items :for i in range(1500) : if d[i] != 3000 - i : $put =d[i] : endif :endfor : let i += 1 :" delete even items :while i >= 2 : let i -= 2 : unlet d[i] :endwhile :$put =get(d, 1500 - 100, 'NONE') . ' ' . d[1] :" delete odd items, checking value, one intentionally wrong :let d[33] = 999 :let i = 1 :while i < 1500 : if d[i] != 3000 - i : $put =i . '=' . d[i] : else : unlet d[i] : endif : let i += 2 :endwhile :$put =string(d) " must be almost empty now :unlet d :" :" Dictionary function :let dict = {} :func dict.func(a) dict : $put =a:a . len(self.data) :endfunc :let dict.data = [1,2,3] :call dict.func("len: ") :let x = dict.func("again: ") :try : let Fn = dict.func : call Fn('xxx') :catch : $put =v:exception[:15] :endtry :" :" Function in script-local List or Dict :let g:dict = {} :function g:dict.func() dict : $put ='g:dict.func'.self.foo[1].self.foo[0]('asdf') :endfunc :let g:dict.foo = ['-', 2, 3] :call insert(g:dict.foo, function('strlen')) :call g:dict.func() :" :" Nasty: remove func from Dict that's being called (works) :let d = {1:1} :func d.func(a) : return "a:". a:a :endfunc :$put =d.func(string(remove(d, 'func'))) :" :" Nasty: deepcopy() dict that refers to itself (fails when noref used) :let d = {1:1, 2:2} :let l = [4, d, 6] :let d[3] = l :let dc = deepcopy(d) :try : let dc = deepcopy(d, 1) :catch : $put =v:exception[:14] :endtry :let l2 = [0, l, l, 3] :let l[1] = l2 :let l3 = deepcopy(l2) :$put ='same list: ' . (l3[1] is l3[2]) :" :" Locked variables :for depth in range(5) : $put ='depth is ' . depth : for u in range(3) : unlet l : let l = [0, [1, [2, 3]], {4: 5, 6: {7: 8}}] : exe "lockvar " . depth . " l" : if u == 1 : exe "unlockvar l" : elseif u == 2 : exe "unlockvar " . depth . " l" : endif : let ps = islocked("l").islocked("l[1]").islocked("l[1][1]").islocked("l[1][1][0]").'-'.islocked("l[2]").islocked("l[2]['6']").islocked("l[2]['6'][7]") : $put =ps : let ps = '' : try : let l[1][1][0] = 99 : let ps .= 'p' : catch : let ps .= 'F' : endtry : try : let l[1][1] = [99] : let ps .= 'p' : catch : let ps .= 'F' : endtry : try : let l[1] = [99] : let ps .= 'p' : catch : let ps .= 'F' : endtry : try : let l[2]['6'][7] = 99 : let ps .= 'p' : catch : let ps .= 'F' : endtry : try : let l[2][6] = {99: 99} : let ps .= 'p' : catch : let ps .= 'F' : endtry : try : let l[2] = {99: 99} : let ps .= 'p' : catch : let ps .= 'F' : endtry : try : let l = [99] : let ps .= 'p' : catch : let ps .= 'F' : endtry : $put =ps : endfor :endfor :" :" a:000 function argument :" first the tests that should fail :try : let a:000 = [1, 2] :catch : $put ='caught a:000' :endtry :try : let a:000[0] = 9 :catch : $put ='caught a:000[0]' :endtry :try : let a:000[2] = [9, 10] :catch : $put ='caught a:000[2]' :endtry :try : let a:000[3] = {9: 10} :catch : $put ='caught a:000[3]' :endtry :" now the tests that should pass :try : let a:000[2][1] = 9 : call extend(a:000[2], [5, 6]) : let a:000[3][5] = 8 : let a:000[3]['a'] = 12 : $put =string(a:000) :catch : $put ='caught ' . v:exception :endtry :" :" reverse() and sort() :let l = ['-0', 'A11', 2, 'xaaa', 4, 'foo', 'foo6', [0, 1, 2], 'x8'] :$put =string(reverse(l)) :$put =string(reverse(reverse(l))) :$put =string(sort(l)) :$put =string(reverse(sort(l))) :$put =string(sort(reverse(sort(l)))) :" :" splitting a string to a List :$put =string(split(' aa bb ')) :$put =string(split(' aa bb ', '\W\+', 0)) :$put =string(split(' aa bb ', '\W\+', 1)) :$put =string(split(' aa bb ', '\W', 1)) :$put =string(split(':aa::bb:', ':', 0)) :$put =string(split(':aa::bb:', ':', 1)) :$put =string(split('aa,,bb, cc,', ',\s*', 1)) :$put =string(split('abc', '\zs')) :$put =string(split('abc', '\zs', 1)) :" :" compare recursively linked list and dict :let l = [1, 2, 3, 4] :let d = {'1': 1, '2': l, '3': 3} :let l[1] = d :$put =(l == l) :$put =(d == d) :$put =(l != deepcopy(l)) :$put =(d != deepcopy(d)) :" :" compare complex recursively linked list and dict :let l = [] :call add(l, l) :let dict4 = {"l": l} :call add(dict4.l, dict4) :let lcopy = deepcopy(l) :let dict4copy = deepcopy(dict4) :$put =(l == lcopy) :$put =(dict4 == dict4copy) :" :" Pass the same List to extend() :let l = [1, 2, 3, 4, 5] :call extend(l, l) :$put =string(l) :" :" Pass the same Dict to extend() :let d = { 'a': {'b': 'B'}} :call extend(d, d) :$put =string(d) :" :" Pass the same Dict to extend() with "error" :try : call extend(d, d, "error") :catch : $put =v:exception[:15] . v:exception[-1:-1] :endtry :$put =string(d) :endfun :" :call Test(1, 2, [3, 4], {5: 6}) " This may take a while :" :delfunc Test :unlet dict :call garbagecollect(1) :" :/^start:/,$wq! test.out ENDTEST start:
zyz2011-vim
src/testdir/test55.in
Vim Script
gpl2
7,875
Test for script-local function. vim: set ft=vim : STARTTEST :so small.vim :" :set nocp viminfo+=nviminfo :/^start:/+1,/^end:/-1w! Xtest.vim :source Xtest.vim _x :$-1,$wq! test.out ENDTEST start: fun <SID>DoLast() call append(line('$'), "last line") endfun fun s:DoNothing() call append(line('$'), "nothing line") endfun nnoremap <buffer> _x :call <SID>DoNothing()<bar>call <SID>DoLast()<bar>delfunc <SID>DoNothing<bar>delfunc <SID>DoLast<cr> end:
zyz2011-vim
src/testdir/test56.in
Vim Script
gpl2
457
" Vim script language tests " Author: Servatius Brandt <Servatius.Brandt@fujitsu-siemens.com> " Last Change: 2010 Sep 29 "------------------------------------------------------------------------------- " Test environment {{{1 "------------------------------------------------------------------------------- " Adding new tests easily. {{{2 " " Writing new tests is eased considerably with the following functions and " abbreviations (see "Commands for recording the execution path", "Automatic " argument generation"). " " To get the abbreviations, execute the command " " :let test49_set_env = 1 | source test49.vim " " To get them always (from src/testdir), put a line " " au! BufRead test49.vim let test49_set_env = 1 | source test49.vim " " into the local .vimrc file in the src/testdir directory. " if exists("test49_set_env") && test49_set_env " Automatic argument generation for the test environment commands. function! Xsum() let addend = substitute(getline("."), '^.*"\s*X:\s*\|^.*', '', "") " Evaluate arithmetic expression. if addend != "" exec "let g:Xsum = g:Xsum + " . addend endif endfunction function! Xcheck() let g:Xsum=0 ?XpathINIT?,.call Xsum() exec "norm A " return g:Xsum endfunction iab Xcheck Xcheck<Space><C-R>=Xcheck()<CR><C-O>x function! Xcomment(num) let str = "" let tabwidth = &sts ? &sts : &ts let tabs = (48+tabwidth - a:num - virtcol(".")) / tabwidth while tabs > 0 let str = str . "\t" let tabs = tabs - 1 endwhile let str = str . '" X:' return str endfunction function! Xloop() let back = line(".") . "|norm" . virtcol(".") . "|" norm 0 let last = search('X\(loop\|path\)INIT\|Xloop\>', "bW") exec back let theline = getline(last) if theline =~ 'X\(loop\|path\)INIT' let num = 1 else let num = 2 * substitute(theline, '.*Xloop\s*\(\d\+\).*', '\1', "") endif ?X\(loop\|path\)INIT? \s/\(XloopINIT!\=\s*\d\+\s\+\)\@<=\(\d\+\)/\=2*submatch(2)/ exec back exec "norm a " return num . Xcomment(strlen(num)) endfunction iab Xloop Xloop<Space><C-R>=Xloop()<CR><C-O>x function! Xpath(loopinit) let back = line(".") . "|norm" . virtcol(".") . "|" norm 0 let last = search('XpathINIT\|Xpath\>\|XloopINIT', "bW") exec back let theline = getline(last) if theline =~ 'XpathINIT' let num = 1 elseif theline =~ 'Xpath\>' let num = 2 * substitute(theline, '.*Xpath\s*\(\d\+\).*', '\1', "") else let pattern = '.*XloopINIT!\=\s*\(\d\+\)\s*\(\d\+\).*' let num = substitute(theline, pattern, '\1', "") let factor = substitute(theline, pattern, '\2', "") " The "<C-O>x" from the "Xpath" iab and the character triggering its " expansion are in the input buffer. Save and clear typeahead so " that it is not read away by the call to "input()" below. Restore " afterwards. call inputsave() let loops = input("Number of iterations in previous loop? ") call inputrestore() while (loops > 0) let num = num * factor let loops = loops - 1 endwhile endif exec "norm a " if a:loopinit return num . " 1" endif return num . Xcomment(strlen(num)) endfunction iab Xpath Xpath<Space><C-R>=Xpath(0)<CR><C-O>x iab XloopINIT XloopINIT<Space><C-R>=Xpath(1)<CR><C-O>x " Also useful (see ExtraVim below): aug ExtraVim au! au BufEnter <sfile> syn region ExtraVim \ start=+^if\s\+ExtraVim(.*)+ end=+^endif+ \ transparent keepend au BufEnter <sfile> syn match ExtraComment /^"/ \ contained containedin=ExtraVim au BufEnter <sfile> hi link ExtraComment vimComment aug END aug Xpath au BufEnter <sfile> syn keyword Xpath \ XpathINIT Xpath XloopINIT Xloop XloopNEXT Xcheck Xout au BufEnter <sfile> hi link Xpath Special aug END do BufEnter <sfile> " Do not execute the tests when sourcing this file for getting the functions " and abbreviations above, which are intended for easily adding new test " cases; they are not needed for test execution. Unlet the variable " controlling this so that an explicit ":source" command for this file will " execute the tests. unlet test49_set_env finish endif " Commands for recording the execution path. {{{2 " " The Xpath/Xloop commands can be used for computing the eXecution path by " adding (different) powers of 2 from those script lines, for which the " execution should be checked. Xloop provides different addends for each " execution of a loop. Permitted values are 2^0 to 2^30, so that 31 execution " points (multiply counted inside loops) can be tested. " " Note that the arguments of the following commands can be generated " automatically, see below. " " Usage: {{{3 " " - Use XpathINIT at the beginning of the test. " " - Use Xpath to check if a line is executed. " Argument: power of 2 (decimal). " " - To check multiple execution of loops use Xloop for automatically " computing Xpath values: " " - Use XloopINIT before the loop. " Two arguments: " - the first Xpath value (power of 2) to be used (Xnext), " - factor for computing a new Xnext value when reexecuting a loop " (by a ":continue" or ":endwhile"); this should be 2^n where " n is the number of Xloop commands inside the loop. " If XloopINIT! is used, the first execution of XloopNEXT is " a no-operation. " " - Use Xloop inside the loop: " One argument: " The argument and the Xnext value are multiplied to build the " next Xpath value. No new Xnext value is prepared. The argument " should be 2^(n-1) for the nth Xloop command inside the loop. " If the loop has only one Xloop command, the argument can be " ommitted (default: 1). " " - Use XloopNEXT before ":continue" and ":endwhile". This computes a new " Xnext value for the next execution of the loop by multiplying the old " one with the factor specified in the XloopINIT command. No Argument. " Alternatively, when XloopINIT! is used, a single XloopNEXT at the " beginning of the loop can be used. " " Nested loops are not supported. " " - Use Xcheck at end of each test. It prints the test number, the expected " execution path value, the test result ("OK" or "FAIL"), and, if the tests " fails, the actual execution path. " One argument: " Expected Xpath/Xloop sum for the correct execution path. " In order that this value can be computed automatically, do the " following: For each line in the test with an Xpath and Xloop " command, add a comment starting with "X:" and specifying an " expression that evaluates to the value contributed by this line to " the correct execution path. (For copying an Xpath argument of at " least two digits into the comment, press <C-P>.) At the end of the " test, just type "Xcheck" and press <Esc>. " " - In order to add additional information to the test output file, use the " Xout command. Argument(s) like ":echo". " " Automatic argument generation: {{{3 " " The arguments of the Xpath, XloopINIT, Xloop, and Xcheck commands can be " generated automatically, so that new tests can easily be written without " mental arithmetic. The Xcheck argument is computed from the "X:" comments " of the preceding Xpath and Xloop commands. See the commands and " abbreviations at the beginning of this file. " " Implementation: {{{3 " XpathINIT, Xpath, XloopINIT, Xloop, XloopNEXT, Xcheck, Xout. " " The variants for existing g:ExtraVimResult are needed when executing a script " in an extra Vim process, see ExtraVim below. " EXTRA_VIM_START - do not change or remove this line. com! XpathINIT let g:Xpath = 0 if exists("g:ExtraVimResult") com! -count -bar Xpath exec "!echo <count> >>" . g:ExtraVimResult else com! -count -bar Xpath let g:Xpath = g:Xpath + <count> endif com! -count -nargs=1 -bang \ XloopINIT let g:Xnext = <count> | \ let g:Xfactor = <args> | \ let g:Xskip = strlen("<bang>") if exists("g:ExtraVimResult") com! -count=1 -bar Xloop exec "!echo " . (g:Xnext * <count>) . " >>" . \ g:ExtraVimResult else com! -count=1 -bar Xloop let g:Xpath = g:Xpath + g:Xnext * <count> endif com! XloopNEXT let g:Xnext = g:Xnext * \ (g:Xskip ? 1 : g:Xfactor) | \ let g:Xskip = 0 let @r = "" let Xtest = 1 com! -count Xcheck let Xresult = "*** Test " . \ (Xtest<10?" ":Xtest<100?" ":"") . \ Xtest . ": " . ( \ (Xpath==<count>) ? "OK (".Xpath.")" : \ "FAIL (".Xpath." instead of <count>)" \ ) | \ let @R = Xresult . "\n" | \ echo Xresult | \ let Xtest = Xtest + 1 if exists("g:ExtraVimResult") com! -nargs=+ Xoutq exec "!echo @R:'" . \ substitute(substitute(<q-args>, \ "'", '&\\&&', "g"), "\n", "@NL@", "g") \ . "' >>" . g:ExtraVimResult else com! -nargs=+ Xoutq let @R = "--- Test " . \ (g:Xtest<10?" ":g:Xtest<100?" ":"") . \ g:Xtest . ": " . substitute(<q-args>, \ "\n", "&\t ", "g") . "\n" endif com! -nargs=+ Xout exec 'Xoutq' <args> " Switch off storing of lines for undoing changes. Speeds things up a little. set undolevels=-1 " EXTRA_VIM_STOP - do not change or remove this line. " ExtraVim() - Run a script file in an extra Vim process. {{{2 " " This is useful for testing immediate abortion of the script processing due to " an error in a command dynamically enclosed by a :try/:tryend region or when an " exception is thrown but not caught or when an interrupt occurs. It can also " be used for testing :finish. " " An interrupt location can be specified by an "INTERRUPT" comment. A number " telling how often this location is reached (in a loop or in several function " calls) should be specified as argument. When missing, once per script " invocation or function call is assumed. INTERRUPT locations are tested by " setting a breakpoint in that line and using the ">quit" debug command when " the breakpoint is reached. A function for which an INTERRUPT location is " specified must be defined before calling it (or executing it as a script by " using ExecAsScript below). " " This function is only called in normal modus ("g:ExtraVimResult" undefined). " " Tests to be executed as an extra script should be written as follows: " " column 1 column 1 " | | " v v " " XpathINIT XpathINIT " if ExtraVim() if ExtraVim() " ... " ... " ... " ... " endif endif " Xcheck <number> Xcheck <number> " " Double quotes in column 1 are removed before the script is executed. " They should be used if the test has unbalanced conditionals (:if/:endif, " :while:/endwhile, :try/:endtry) or for a line with a syntax error. The " extra script may use Xpath, XloopINIT, Xloop, XloopNEXT, and Xout as usual. " " A file name may be specified as argument. All messages of the extra Vim " process are then redirected to the file. An existing file is overwritten. " let ExtraVimCount = 0 let ExtraVimBase = expand("<sfile>") let ExtraVimTestEnv = "" " function! ExtraVim(...) " Count how often this function is called. let g:ExtraVimCount = g:ExtraVimCount + 1 " Disable folds to prevent that the ranges in the ":write" commands below " are extended up to the end of a closed fold. This also speeds things up " considerably. set nofoldenable " Open a buffer for this test script and copy the test environment to " a temporary file. Take account of parts relevant for the extra script " execution only. let current_buffnr = bufnr("%") execute "view +1" g:ExtraVimBase if g:ExtraVimCount == 1 let g:ExtraVimTestEnv = tempname() execute "/E" . "XTRA_VIM_START/+,/E" . "XTRA_VIM_STOP/-w" \ g:ExtraVimTestEnv "|']+" execute "/E" . "XTRA_VIM_START/+,/E" . "XTRA_VIM_STOP/-w >>" \ g:ExtraVimTestEnv "|']+" execute "/E" . "XTRA_VIM_START/+,/E" . "XTRA_VIM_STOP/-w >>" \ g:ExtraVimTestEnv "|']+" execute "/E" . "XTRA_VIM_START/+,/E" . "XTRA_VIM_STOP/-w >>" \ g:ExtraVimTestEnv "|']+" endif " Start the extra Vim script with a ":source" command for the test " environment. The source line number where the extra script will be " appended, needs to be passed as variable "ExtraVimBegin" to the script. let extra_script = tempname() exec "!echo 'source " . g:ExtraVimTestEnv . "' >" . extra_script let extra_begin = 1 " Starting behind the test environment, skip over the first g:ExtraVimCount " occurrences of "if ExtraVim()" and copy the following lines up to the " matching "endif" to the extra Vim script. execute "/E" . "ND_OF_TEST_ENVIRONMENT/" exec 'norm ' . g:ExtraVimCount . '/^\s*if\s\+ExtraVim(.*)/+' . "\n" execute ".,/^endif/-write >>" . extra_script " Open a buffer for the extra Vim script, delete all ^", and write the " script if was actually modified. execute "edit +" . (extra_begin + 1) extra_script ,$s/^"//e update " Count the INTERRUPTs and build the breakpoint and quit commands. let breakpoints = "" let debug_quits = "" let in_func = 0 exec extra_begin while search( \ '"\s*INTERRUPT\h\@!\|^\s*fu\%[nction]\>!\=\s*\%(\u\|s:\)\w*\s*(\|' \ . '^\s*\\\|^\s*endf\%[unction]\>\|' \ . '\%(^\s*fu\%[nction]!\=\s*\)\@<!\%(\u\|s:\)\w*\s*(\|' \ . 'ExecAsScript\s\+\%(\u\|s:\)\w*', \ "W") > 0 let theline = getline(".") if theline =~ '^\s*fu' " Function definition. let in_func = 1 let func_start = line(".") let func_name = substitute(theline, \ '^\s*fu\%[nction]!\=\s*\(\%(\u\|s:\)\w*\).*', '\1', "") elseif theline =~ '^\s*endf' " End of function definition. let in_func = 0 else let finding = substitute(theline, '.*\(\%' . col(".") . 'c.*\)', \ '\1', "") if finding =~ '^"\s*INTERRUPT\h\@!' " Interrupt comment. Compose as many quit commands as " specified. let cnt = substitute(finding, \ '^"\s*INTERRUPT\s*\(\d*\).*$', '\1', "") let quits = "" while cnt > 0 " Use "\r" rather than "\n" to separate the quit commands. " "\r" is not interpreted as command separator by the ":!" " command below but works to separate commands in the " external vim. let quits = quits . "q\r" let cnt = cnt - 1 endwhile if in_func " Add the function breakpoint and note the number of quits " to be used, if specified, or one for every call else. let breakpoints = breakpoints . " -c 'breakadd func " . \ (line(".") - func_start) . " " . \ func_name . "'" if quits != "" let debug_quits = debug_quits . quits elseif !exists("quits{func_name}") let quits{func_name} = "q\r" else let quits{func_name} = quits{func_name} . "q\r" endif else " Add the file breakpoint and the quits to be used for it. let breakpoints = breakpoints . " -c 'breakadd file " . \ line(".") . " " . extra_script . "'" if quits == "" let quits = "q\r" endif let debug_quits = debug_quits . quits endif else " Add the quits to be used for calling the function or executing " it as script file. if finding =~ '^ExecAsScript' " Sourcing function as script. let finding = substitute(finding, \ '^ExecAsScript\s\+\(\%(\u\|s:\)\w*\).*', '\1', "") else " Function call. let finding = substitute(finding, \ '^\(\%(\u\|s:\)\w*\).*', '\1', "") endif if exists("quits{finding}") let debug_quits = debug_quits . quits{finding} endif endif endif endwhile " Close the buffer for the script and create an (empty) resultfile. bwipeout let resultfile = tempname() exec "!>" . resultfile " Run the script in an extra vim. Switch to extra modus by passing the " resultfile in ExtraVimResult. Redirect messages to the file specified as " argument if any. Use ":debuggreedy" so that the commands provided on the " pipe are consumed at the debug prompt. Use "-N" to enable command-line " continuation ("C" in 'cpo'). Add "nviminfo" to 'viminfo' to avoid " messing up the user's viminfo file. let redirect = a:0 ? \ " -c 'au VimLeave * redir END' -c 'redir\\! >" . a:1 . "'" : "" exec "!echo '" . debug_quits . "q' | ../vim -u NONE -N -Xes" . redirect . \ " -c 'debuggreedy|set viminfo+=nviminfo'" . \ " -c 'let ExtraVimBegin = " . extra_begin . "'" . \ " -c 'let ExtraVimResult = \"" . resultfile . "\"'" . breakpoints . \ " -S " . extra_script " Build the resulting sum for resultfile and add it to g:Xpath. Add Xout " information provided by the extra Vim process to the test output. let sum = 0 exec "edit" resultfile let line = 1 while line <= line("$") let theline = getline(line) if theline =~ '^@R:' exec 'Xout "' . substitute(substitute( \ escape(escape(theline, '"'), '\"'), \ '^@R:', '', ""), '@NL@', "\n", "g") . '"' else let sum = sum + getline(line) endif let line = line + 1 endwhile bwipeout let g:Xpath = g:Xpath + sum " Delete the extra script and the resultfile. call delete(extra_script) call delete(resultfile) " Switch back to the buffer that was active when this function was entered. exec "buffer" current_buffnr " Return 0. This protects extra scripts from being run in the main Vim " process. return 0 endfunction " ExtraVimThrowpoint() - Relative throwpoint in ExtraVim script {{{2 " " Evaluates v:throwpoint and returns the throwpoint relative to the beginning of " an ExtraVim script as passed by ExtraVim() in ExtraVimBegin. " " EXTRA_VIM_START - do not change or remove this line. function! ExtraVimThrowpoint() if !exists("g:ExtraVimBegin") Xout "ExtraVimThrowpoint() used outside ExtraVim() script." return v:throwpoint endif if v:throwpoint =~ '^function\>' return v:throwpoint endif return "line " . \ (substitute(v:throwpoint, '.*, line ', '', "") - g:ExtraVimBegin) . \ " of ExtraVim() script" endfunction " EXTRA_VIM_STOP - do not change or remove this line. " MakeScript() - Make a script file from a function. {{{2 " " Create a script that consists of the body of the function a:funcname. " Replace any ":return" by a ":finish", any argument variable by a global " variable, and and every ":call" by a ":source" for the next following argument " in the variable argument list. This function is useful if similar tests are " to be made for a ":return" from a function call or a ":finish" in a script " file. " " In order to execute a function specifying an INTERRUPT location (see ExtraVim) " as a script file, use ExecAsScript below. " " EXTRA_VIM_START - do not change or remove this line. function! MakeScript(funcname, ...) let script = tempname() execute "redir! >" . script execute "function" a:funcname redir END execute "edit" script " Delete the "function" and the "endfunction" lines. Do not include the " word "function" in the pattern since it might be translated if LANG is " set. When MakeScript() is being debugged, this deletes also the debugging " output of its line 3 and 4. exec '1,/.*' . a:funcname . '(.*)/d' /^\d*\s*endfunction\>/,$d %s/^\d*//e %s/return/finish/e %s/\<a:\(\h\w*\)/g:\1/ge normal gg0 let cnt = 0 while search('\<call\s*\%(\u\|s:\)\w*\s*(.*)', 'W') > 0 let cnt = cnt + 1 s/\<call\s*\%(\u\|s:\)\w*\s*(.*)/\='source ' . a:{cnt}/ endwhile g/^\s*$/d write bwipeout return script endfunction " EXTRA_VIM_STOP - do not change or remove this line. " ExecAsScript - Source a temporary script made from a function. {{{2 " " Make a temporary script file from the function a:funcname, ":source" it, and " delete it afterwards. " " When inside ":if ExtraVim()", add a file breakpoint for each INTERRUPT " location specified in the function. " " EXTRA_VIM_START - do not change or remove this line. function! ExecAsScript(funcname) " Make a script from the function passed as argument. let script = MakeScript(a:funcname) " When running in an extra Vim process, add a file breakpoint for each " function breakpoint set when the extra Vim process was invoked by " ExtraVim(). if exists("g:ExtraVimResult") let bplist = tempname() execute "redir! >" . bplist breaklist redir END execute "edit" bplist " Get the line number from the function breakpoint. Works also when " LANG is set. execute 'v/^\s*\d\+\s\+func\s\+' . a:funcname . '\s.*/d' %s/^\s*\d\+\s\+func\s\+\%(\u\|s:\)\w*\s\D*\(\d*\).*/\1/e let cnt = 0 while cnt < line("$") let cnt = cnt + 1 if getline(cnt) != "" execute "breakadd file" getline(cnt) script endif endwhile bwipeout! call delete(bplist) endif " Source and delete the script. exec "source" script call delete(script) endfunction com! -nargs=1 -bar ExecAsScript call ExecAsScript(<f-args>) " EXTRA_VIM_STOP - do not change or remove this line. " END_OF_TEST_ENVIRONMENT - do not change or remove this line. "------------------------------------------------------------------------------- " Test 1: :endwhile in function {{{1 " " Detect if a broken loop is (incorrectly) reactivated by the " :endwhile. Use a :return to prevent an endless loop, and make " this test first to get a meaningful result on an error before other " tests will hang. "------------------------------------------------------------------------------- XpathINIT function! F() Xpath 1 " X: 1 let first = 1 XloopINIT 2 8 while 1 Xloop 1 " X: 2 + 0 * 16 if first Xloop 2 " X: 4 + 0 * 32 let first = 0 XloopNEXT break else Xloop 4 " X: 0 + 0 * 64 return endif endwhile endfunction call F() Xpath 128 " X: 128 function! G() Xpath 256 " X: 256 + 0 * 2048 let first = 1 XloopINIT 512 8 while 1 Xloop 1 " X: 512 + 0 * 4096 if first Xloop 2 " X: 1024 + 0 * 8192 let first = 0 XloopNEXT break else Xloop 4 " X: 0 + 0 * 16384 return endif if 1 " unmatched :if endwhile endfunction call G() Xpath 32768 " X: 32768 Xcheck 34695 " Leave F and G for execution as scripts in the next test. "------------------------------------------------------------------------------- " Test 2: :endwhile in script {{{1 " " Detect if a broken loop is (incorrectly) reactivated by the " :endwhile. Use a :finish to prevent an endless loop, and place " this test before others that might hang to get a meaningful result " on an error. " " This test executes the bodies of the functions F and G from the " previous test as script files (:return replaced by :finish). "------------------------------------------------------------------------------- XpathINIT ExecAsScript F " X: 1 + 2 + 4 Xpath 128 " X: 128 ExecAsScript G " X: 256 + 512 + 1024 Xpath 32768 " X: 32768 unlet first delfunction F delfunction G Xcheck 34695 "------------------------------------------------------------------------------- " Test 3: :if, :elseif, :while, :continue, :break {{{1 "------------------------------------------------------------------------------- XpathINIT if 1 Xpath 1 " X: 1 let loops = 3 XloopINIT 2 512 while loops > -1 " main loop: loops == 3, 2, 1 (which breaks) if loops <= 0 let break_err = 1 let loops = -1 else " 3: 2: 1: Xloop 1 " X: 2 + 2*512 + 2*512*512 endif if (loops == 2) while loops == 2 " dummy loop Xloop 2 " X: 4*512 let loops = loops - 1 continue " stop dummy loop Xloop 4 " X: 0 endwhile XloopNEXT continue " continue main loop Xloop 8 " X: 0 elseif (loops == 1) let p = 1 while p " dummy loop Xloop 16 " X: 32*512*512 let p = 0 break " break dummy loop Xloop 32 " X: 0 endwhile Xloop 64 " X: 128*512*512 unlet p break " break main loop Xloop 128 " X: 0 endif if (loops > 0) Xloop 256 " X: 512 endif while loops == 3 " dummy loop let loops = loops - 1 endwhile " end dummy loop XloopNEXT endwhile " end main loop Xpath 268435456 " X: 1024*512*512 else Xpath 536870912 " X: 0 endif Xpath 1073741824 " X: 4096*512*512 if exists("break_err") " The Xpath command does not accept 2^31 (negative); add explicitly: let Xpath = Xpath + 2147483648 " X: 0 unlet break_err endif unlet loops Xcheck 1384648195 "------------------------------------------------------------------------------- " Test 4: :return {{{1 "------------------------------------------------------------------------------- XpathINIT function! F() if 1 Xpath 1 " X: 1 let loops = 3 XloopINIT 2 16 while loops > 0 " 3: 2: 1: Xloop 1 " X: 2 + 2*16 + 0*16*16 if (loops == 2) Xloop 2 " X: 4*16 return Xloop 4 " X: 0 endif Xloop 8 " X: 16 let loops = loops - 1 XloopNEXT endwhile Xpath 8192 " X: 0 else Xpath 16384 " X: 0 endif endfunction call F() Xpath 32768 " X: 8*16*16*16 Xcheck 32883 " Leave F for execution as a script in the next test. "------------------------------------------------------------------------------- " Test 5: :finish {{{1 " " This test executes the body of the function F from the previous test " as a script file (:return replaced by :finish). "------------------------------------------------------------------------------- XpathINIT ExecAsScript F " X: 1 + 2 + 2*16 + 4*16 + 16 Xpath 32768 " X: 32768 unlet loops delfunction F Xcheck 32883 "------------------------------------------------------------------------------- " Test 6: Defining functions in :while loops {{{1 " " Functions can be defined inside other functions. An inner function " gets defined when the outer function is executed. Functions may " also be defined inside while loops. Expressions in braces for " defining the function name are allowed. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() " The command CALL collects the argument of all its invocations in "calls" " when used from a function (that is, when the global variable "calls" needs " the "g:" prefix). This is to check that the function code is skipped when " the function is defined. For inner functions, do so only if the outer " function is not being executed. " let calls = "" com! -nargs=1 CALL \ if !exists("calls") && !exists("outer") | \ let g:calls = g:calls . <args> | \ endif XloopINIT! 1 16 let i = 0 while i < 3 XloopNEXT let i = i + 1 if i == 1 Xloop 1 " X: 1 function! F1(arg) CALL a:arg let outer = 1 XloopINIT! 4096 4 let j = 0 while j < 1 XloopNEXT Xloop 1 " X: 4096 let j = j + 1 function! G1(arg) CALL a:arg endfunction Xloop 2 " X: 8192 endwhile endfunction Xloop 2 " X: 2 continue endif Xloop 4 " X: 4 * (16 + 256) function! F{i}(i, arg) CALL a:arg let outer = 1 XloopINIT! 16384 4 if a:i == 3 XloopNEXT XloopNEXT XloopNEXT endif let k = 0 while k < 3 XloopNEXT Xloop 1 " X: 16384*(1+4+16+64+256+1024) let k = k + 1 function! G{a:i}{k}(arg) CALL a:arg endfunction Xloop 2 " X: 32768*(1+4+16+64+256+1024) endwhile endfunction Xloop 8 " X: 8 * (16 + 256) endwhile if exists("*G1") Xpath 67108864 " X: 0 endif if exists("*F1") call F1("F1") if exists("*G1") call G1("G1") endif endif if exists("G21") || exists("G21") || exists("G21") Xpath 134217728 " X: 0 endif if exists("*F2") call F2(2, "F2") if exists("*G21") call G21("G21") endif if exists("*G22") call G22("G22") endif if exists("*G23") call G23("G23") endif endif if exists("G31") || exists("G31") || exists("G31") Xpath 268435456 " X: 0 endif if exists("*F3") call F3(3, "F3") if exists("*G31") call G31("G31") endif if exists("*G32") call G32("G32") endif if exists("*G33") call G33("G33") endif endif Xpath 536870912 " X: 536870912 if calls != "F1G1F2G21G22G23F3G31G32G33" Xpath 1073741824 " X: 0 Xout "calls is" calls endif delfunction F1 delfunction G1 delfunction F2 delfunction G21 delfunction G22 delfunction G23 delfunction G31 delfunction G32 delfunction G33 endif Xcheck 603978947 "------------------------------------------------------------------------------- " Test 7: Continuing on errors outside functions {{{1 " " On an error outside a function, the script processing continues " at the line following the outermost :endif or :endwhile. When not " inside an :if or :while, the script processing continues at the next " line. "------------------------------------------------------------------------------- XpathINIT if 1 Xpath 1 " X: 1 while 1 Xpath 2 " X: 2 asdf Xpath 4 " X: 0 break endwhile | Xpath 8 " X: 0 Xpath 16 " X: 0 endif | Xpath 32 " X: 0 Xpath 64 " X: 64 while 1 Xpath 128 " X: 128 if 1 Xpath 256 " X: 256 asdf Xpath 512 " X: 0 endif | Xpath 1024 " X: 0 Xpath 2048 " X: 0 break endwhile | Xpath 4096 " X: 0 Xpath 8192 " X: 8192 asdf Xpath 16384 " X: 16384 asdf | Xpath 32768 " X: 0 Xpath 65536 " X: 65536 Xcheck 90563 "------------------------------------------------------------------------------- " Test 8: Aborting and continuing on errors inside functions {{{1 " " On an error inside a function without the "abort" attribute, the " script processing continues at the next line (unless the error was " in a :return command). On an error inside a function with the " "abort" attribute, the function is aborted and the script processing " continues after the function call; the value -1 is returned then. "------------------------------------------------------------------------------- XpathINIT function! F() if 1 Xpath 1 " X: 1 while 1 Xpath 2 " X: 2 asdf Xpath 4 " X: 4 asdf | Xpath 8 " X: 0 Xpath 16 " X: 16 break endwhile Xpath 32 " X: 32 endif | Xpath 64 " X: 64 Xpath 128 " X: 128 while 1 Xpath 256 " X: 256 if 1 Xpath 512 " X: 512 asdf Xpath 1024 " X: 1024 asdf | Xpath 2048 " X: 0 Xpath 4096 " X: 4096 endif Xpath 8192 " X: 8192 break endwhile | Xpath 16384 " X: 16384 Xpath 32768 " X: 32768 return novar " returns (default return value 0) Xpath 65536 " X: 0 return 1 " not reached endfunction function! G() abort if 1 Xpath 131072 " X: 131072 while 1 Xpath 262144 " X: 262144 asdf " returns -1 Xpath 524288 " X: 0 break endwhile Xpath 1048576 " X: 0 endif | Xpath 2097152 " X: 0 Xpath Xpath 4194304 " X: 0 return -4 " not reached endfunction function! H() abort while 1 Xpath 8388608 " X: 8388608 if 1 Xpath 16777216 " X: 16777216 asdf " returns -1 Xpath 33554432 " X: 0 endif Xpath 67108864 " X: 0 break endwhile | Xpath 134217728 " X: 0 Xpath 268435456 " X: 0 return -4 " not reached endfunction " Aborted functions (G and H) return -1. let sum = (F() + 1) - 4*G() - 8*H() Xpath 536870912 " X: 536870912 if sum != 13 Xpath 1073741824 " X: 0 Xout "sum is" sum endif unlet sum delfunction F delfunction G delfunction H Xcheck 562493431 "------------------------------------------------------------------------------- " Test 9: Continuing after aborted functions {{{1 " " When a function with the "abort" attribute is aborted due to an " error, the next function back in the call hierarchy without an " "abort" attribute continues; the value -1 is returned then. "------------------------------------------------------------------------------- XpathINIT function! F() abort Xpath 1 " X: 1 let result = G() " not aborted Xpath 2 " X: 2 if result != 2 Xpath 4 " X: 0 endif return 1 endfunction function! G() " no abort attribute Xpath 8 " X: 8 if H() != -1 " aborted Xpath 16 " X: 0 endif Xpath 32 " X: 32 return 2 endfunction function! H() abort Xpath 64 " X: 64 call I() " aborted Xpath 128 " X: 0 return 4 endfunction function! I() abort Xpath 256 " X: 256 asdf " error Xpath 512 " X: 0 return 8 endfunction if F() != 1 Xpath 1024 " X: 0 endif delfunction F delfunction G delfunction H delfunction I Xcheck 363 "------------------------------------------------------------------------------- " Test 10: :if, :elseif, :while argument parsing {{{1 " " A '"' or '|' in an argument expression must not be mixed up with " a comment or a next command after a bar. Parsing errors should " be recognized. "------------------------------------------------------------------------------- XpathINIT function! MSG(enr, emsg) let english = v:lang == "C" || v:lang =~ '^[Ee]n' if a:enr == "" Xout "TODO: Add message number for:" a:emsg let v:errmsg = ":" . v:errmsg endif let match = 1 if v:errmsg !~ '^'.a:enr.':' || (english && v:errmsg !~ a:emsg) let match = 0 if v:errmsg == "" Xout "Message missing." else let v:errmsg = escape(v:errmsg, '"') Xout "Unexpected message:" v:errmsg endif endif return match endfunction if 1 || strlen("\"") | Xpath 1 " X: 1 Xpath 2 " X: 2 endif Xpath 4 " X: 4 if 0 elseif 1 || strlen("\"") | Xpath 8 " X: 8 Xpath 16 " X: 16 endif Xpath 32 " X: 32 while 1 || strlen("\"") | Xpath 64 " X: 64 Xpath 128 " X: 128 break endwhile Xpath 256 " X: 256 let v:errmsg = "" if 1 ||| strlen("\"") | Xpath 512 " X: 0 Xpath 1024 " X: 0 endif Xpath 2048 " X: 2048 if !MSG('E15', "Invalid expression") Xpath 4096 " X: 0 endif let v:errmsg = "" if 0 elseif 1 ||| strlen("\"") | Xpath 8192 " X: 0 Xpath 16384 " X: 0 endif Xpath 32768 " X: 32768 if !MSG('E15', "Invalid expression") Xpath 65536 " X: 0 endif let v:errmsg = "" while 1 ||| strlen("\"") | Xpath 131072 " X: 0 Xpath 262144 " X: 0 break endwhile Xpath 524288 " X: 524288 if !MSG('E15', "Invalid expression") Xpath 1048576 " X: 0 endif delfunction MSG Xcheck 559615 "------------------------------------------------------------------------------- " Test 11: :if, :elseif, :while argument evaluation after abort {{{1 " " When code is skipped over due to an error, the boolean argument to " an :if, :elseif, or :while must not be evaluated. "------------------------------------------------------------------------------- XpathINIT let calls = 0 function! P(num) let g:calls = g:calls + a:num " side effect on call return 0 endfunction if 1 Xpath 1 " X: 1 asdf " error Xpath 2 " X: 0 if P(1) " should not be called Xpath 4 " X: 0 elseif !P(2) " should not be called Xpath 8 " X: 0 else Xpath 16 " X: 0 endif Xpath 32 " X: 0 while P(4) " should not be called Xpath 64 " X: 0 endwhile Xpath 128 " X: 0 endif if calls % 2 Xpath 256 " X: 0 endif if (calls/2) % 2 Xpath 512 " X: 0 endif if (calls/4) % 2 Xpath 1024 " X: 0 endif Xpath 2048 " X: 2048 unlet calls delfunction P Xcheck 2049 "------------------------------------------------------------------------------- " Test 12: Expressions in braces in skipped code {{{1 " " In code skipped over due to an error or inactive conditional, " an expression in braces as part of a variable or function name " should not be evaluated. "------------------------------------------------------------------------------- XpathINIT XloopINIT 1 8 function! NULL() Xloop 1 " X: 0 return 0 endfunction function! ZERO() Xloop 2 " X: 0 return 0 endfunction function! F0() Xloop 4 " X: 0 endfunction function! F1(arg) Xpath 4096 " X: 0 endfunction let V0 = 1 Xpath 8192 " X: 8192 echo 0 ? F{NULL() + V{ZERO()}}() : 1 XloopNEXT Xpath 16384 " X: 16384 if 0 Xpath 32768 " X: 0 call F{NULL() + V{ZERO()}}() endif XloopNEXT Xpath 65536 " X: 65536 if 1 asdf " error Xpath 131072 " X: 0 call F1(F{NULL() + V{ZERO()}}()) endif XloopNEXT Xpath 262144 " X: 262144 if 1 asdf " error Xpath 524288 " X: 0 call F{NULL() + V{ZERO()}}() endif Xcheck 352256 "------------------------------------------------------------------------------- " Test 13: Failure in argument evaluation for :while {{{1 " " A failure in the expression evaluation for the condition of a :while " causes the whole :while loop until the matching :endwhile being " ignored. Continuation is at the next following line. "------------------------------------------------------------------------------- XpathINIT Xpath 1 " X: 1 while asdf Xpath 2 " X: 0 while 1 Xpath 4 " X: 0 break endwhile Xpath 8 " X: 0 break endwhile Xpath 16 " X: 16 while asdf | Xpath 32 | endwhile | Xpath 64 " X: 0 Xpath 128 " X: 128 Xcheck 145 "------------------------------------------------------------------------------- " Test 14: Failure in argument evaluation for :if {{{1 " " A failure in the expression evaluation for the condition of an :if " does not cause the corresponding :else or :endif being matched to " a previous :if/:elseif. Neither of both branches of the failed :if " are executed. "------------------------------------------------------------------------------- XpathINIT XloopINIT 1 256 function! F() Xloop 1 " X: 1 + 256 * 1 let x = 0 if x " false Xloop 2 " X: 0 + 256 * 0 elseif !x " always true Xloop 4 " X: 4 + 256 * 4 let x = 1 if g:boolvar " possibly undefined Xloop 8 " X: 8 + 256 * 0 else Xloop 16 " X: 0 + 256 * 0 endif Xloop 32 " X: 32 + 256 * 32 elseif x " never executed Xloop 64 " X: 0 + 256 * 0 endif Xloop 128 " X: 128 + 256 * 128 endfunction let boolvar = 1 call F() XloopNEXT unlet boolvar call F() delfunction F Xcheck 42413 "------------------------------------------------------------------------------- " Test 15: Failure in argument evaluation for :if (bar) {{{1 " " Like previous test, except that the failing :if ... | ... | :endif " is in a single line. "------------------------------------------------------------------------------- XpathINIT XloopINIT 1 256 function! F() Xloop 1 " X: 1 + 256 * 1 let x = 0 if x " false Xloop 2 " X: 0 + 256 * 0 elseif !x " always true Xloop 4 " X: 4 + 256 * 4 let x = 1 if g:boolvar | Xloop 8 | else | Xloop 16 | endif " X: 8 Xloop 32 " X: 32 + 256 * 32 elseif x " never executed Xloop 64 " X: 0 + 256 * 0 endif Xloop 128 " X: 128 + 256 * 128 endfunction let boolvar = 1 call F() XloopNEXT unlet boolvar call F() delfunction F Xcheck 42413 "------------------------------------------------------------------------------- " Test 16: Double :else or :elseif after :else {{{1 " " Multiple :elses or an :elseif after an :else are forbidden. "------------------------------------------------------------------------------- XpathINIT function! F() abort if 0 Xpath 1 " X: 0 else Xpath 2 " X: 2 else " aborts function Xpath 4 " X: 0 endif endfunction function! G() abort if 0 Xpath 8 " X: 0 else Xpath 16 " X: 16 elseif 1 " aborts function Xpath 32 " X: 0 else Xpath 64 " X: 0 endif endfunction function! H() abort if 0 Xpath 128 " X: 0 elseif 0 Xpath 256 " X: 0 else Xpath 512 " X: 512 else " aborts function Xpath 1024 " X: 0 endif endfunction function! I() abort if 0 Xpath 2048 " X: 0 elseif 0 Xpath 4096 " X: 0 else Xpath 8192 " X: 8192 elseif 1 " aborts function Xpath 16384 " X: 0 else Xpath 32768 " X: 0 endif endfunction call F() call G() call H() call I() delfunction F delfunction G delfunction H delfunction I Xcheck 8722 "------------------------------------------------------------------------------- " Test 17: Nesting of unmatched :if or :endif inside a :while {{{1 " " The :while/:endwhile takes precedence in nesting over an unclosed " :if or an unopened :endif. "------------------------------------------------------------------------------- XpathINIT function! MSG(enr, emsg) let english = v:lang == "C" || v:lang =~ '^[Ee]n' if a:enr == "" Xout "TODO: Add message number for:" a:emsg let v:errmsg = ":" . v:errmsg endif let match = 1 if v:errmsg !~ '^'.a:enr.':' || (english && v:errmsg !~ a:emsg) let match = 0 if v:errmsg == "" Xout "Message missing." else let v:errmsg = escape(v:errmsg, '"') Xout "Unexpected message:" v:errmsg endif endif return match endfunction let messages = "" " While loops inside a function are continued on error. function! F() let v:errmsg = "" XloopINIT 1 16 let loops = 3 while loops > 0 let loops = loops - 1 " 2: 1: 0: Xloop 1 " X: 1 + 1*16 + 1*16*16 if (loops == 1) Xloop 2 " X: 2*16 XloopNEXT continue elseif (loops == 0) Xloop 4 " X: 4*16*16 break elseif 1 Xloop 8 " X: 8 XloopNEXT " endif missing! endwhile " :endwhile after :if 1 Xpath 4096 " X: 16*16*16 if MSG('E171', "Missing :endif") let g:messages = g:messages . "A" endif let v:errmsg = "" XloopINIT! 8192 4 let loops = 2 while loops > 0 " 2: 1: XloopNEXT let loops = loops - 1 Xloop 1 " X: 8192 + 8192*4 if 0 Xloop 2 " X: 0 " endif missing endwhile " :endwhile after :if 0 Xpath 131072 " X: 8192*4*4 if MSG('E171', "Missing :endif") let g:messages = g:messages . "B" endif let v:errmsg = "" XloopINIT 262144 4 let loops = 2 while loops > 0 " 2: 1: let loops = loops - 1 Xloop 1 " X: 262144 + 262144 * 4 " if missing! endif " :endif without :if in while Xloop 2 " X: 524288 + 524288 * 4 XloopNEXT endwhile Xpath 4194304 " X: 262144*4*4 if MSG('E580', ":endif without :if") let g:messages = g:messages . "C" endif endfunction call F() " Error continuation outside a function is at the outermost :endwhile or :endif. let v:errmsg = "" XloopINIT! 8388608 4 let loops = 2 while loops > 0 " 2: 1: XloopNEXT let loops = loops - 1 Xloop 1 " X: 8388608 + 0 * 4 if 0 Xloop 2 " X: 0 " endif missing! Following :endwhile fails. endwhile | Xpath 134217728 " X: 0 Xpath 268435456 " X: 2*8388608*4*4 if MSG('E171', "Missing :endif") let messages = g:messages . "D" endif if messages != "ABCD" Xpath 536870912 " X: 0 Xout "messages is" messages "instead of ABCD" endif unlet loops messages delfunction F delfunction MSG Xcheck 285127993 "------------------------------------------------------------------------------- " Test 18: Interrupt (Ctrl-C pressed) {{{1 " " On an interrupt, the script processing is terminated immediately. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() if 1 Xpath 1 " X: 1 while 1 Xpath 2 " X: 2 if 1 Xpath 4 " X: 4 "INTERRUPT Xpath 8 " X: 0 break finish endif | Xpath 16 " X: 0 Xpath 32 " X: 0 endwhile | Xpath 64 " X: 0 Xpath 128 " X: 0 endif | Xpath 256 " X: 0 Xpath 512 " X: 0 endif if ExtraVim() try Xpath 1024 " X: 1024 "INTERRUPT Xpath 2048 " X: 0 endtry | Xpath 4096 " X: 0 Xpath 8192 " X: 0 endif if ExtraVim() function! F() if 1 Xpath 16384 " X: 16384 while 1 Xpath 32768 " X: 32768 if 1 Xpath 65536 " X: 65536 "INTERRUPT Xpath 131072 " X: 0 break return endif | Xpath 262144 " X: 0 Xpath Xpath 524288 " X: 0 endwhile | Xpath 1048576 " X: 0 Xpath Xpath 2097152 " X: 0 endif | Xpath Xpath 4194304 " X: 0 Xpath Xpath 8388608 " X: 0 endfunction call F() | Xpath 16777216 " X: 0 Xpath 33554432 " X: 0 endif if ExtraVim() function! G() try Xpath 67108864 " X: 67108864 "INTERRUPT Xpath 134217728 " X: 0 endtry | Xpath 268435456 " X: 0 Xpath 536870912 " X: 0 endfunction call G() | Xpath 1073741824 " X: 0 " The Xpath command does not accept 2^31 (negative); display explicitly: exec "!echo 2147483648 >>" . g:ExtraVimResult " X: 0 endif Xcheck 67224583 "------------------------------------------------------------------------------- " Test 19: Aborting on errors inside :try/:endtry {{{1 " " An error in a command dynamically enclosed in a :try/:endtry region " aborts script processing immediately. It does not matter whether " the failing command is outside or inside a function and whether a " function has an "abort" attribute. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() function! F() abort Xpath 1 " X: 1 asdf Xpath 2 " X: 0 endfunction try Xpath 4 " X: 4 call F() Xpath 8 " X: 0 endtry | Xpath 16 " X: 0 Xpath 32 " X: 0 endif if ExtraVim() function! G() Xpath 64 " X: 64 asdf Xpath 128 " X: 0 endfunction try Xpath 256 " X: 256 call G() Xpath 512 " X: 0 endtry | Xpath 1024 " X: 0 Xpath 2048 " X: 0 endif if ExtraVim() try Xpath 4096 " X: 4096 asdf Xpath 8192 " X: 0 endtry | Xpath 16384 " X: 0 Xpath 32768 " X: 0 endif if ExtraVim() if 1 try Xpath 65536 " X: 65536 asdf Xpath 131072 " X: 0 endtry | Xpath 262144 " X: 0 endif | Xpath 524288 " X: 0 Xpath 1048576 " X: 0 endif if ExtraVim() let p = 1 while p let p = 0 try Xpath 2097152 " X: 2097152 asdf Xpath 4194304 " X: 0 endtry | Xpath 8388608 " X: 0 endwhile | Xpath 16777216 " X: 0 Xpath 33554432 " X: 0 endif if ExtraVim() let p = 1 while p let p = 0 " try Xpath 67108864 " X: 67108864 endwhile | Xpath 134217728 " X: 0 Xpath 268435456 " X: 0 endif Xcheck 69275973 "------------------------------------------------------------------------------- " Test 20: Aborting on errors after :try/:endtry {{{1 " " When an error occurs after the last active :try/:endtry region has " been left, termination behavior is as if no :try/:endtry has been " seen. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() let p = 1 while p let p = 0 try Xpath 1 " X: 1 endtry asdf endwhile | Xpath 2 " X: 0 Xpath 4 " X: 4 endif if ExtraVim() while 1 try Xpath 8 " X: 8 break Xpath 16 " X: 0 endtry endwhile Xpath 32 " X: 32 asdf Xpath 64 " X: 64 endif if ExtraVim() while 1 try Xpath 128 " X: 128 break Xpath 256 " X: 0 finally Xpath 512 " X: 512 endtry endwhile Xpath 1024 " X: 1024 asdf Xpath 2048 " X: 2048 endif if ExtraVim() while 1 try Xpath 4096 " X: 4096 finally Xpath 8192 " X: 8192 break Xpath 16384 " X: 0 endtry endwhile Xpath 32768 " X: 32768 asdf Xpath 65536 " X: 65536 endif if ExtraVim() let p = 1 while p let p = 0 try Xpath 131072 " X: 131072 continue Xpath 262144 " X: 0 endtry endwhile Xpath 524288 " X: 524288 asdf Xpath 1048576 " X: 1048576 endif if ExtraVim() let p = 1 while p let p = 0 try Xpath 2097152 " X: 2097152 continue Xpath 4194304 " X: 0 finally Xpath 8388608 " X: 8388608 endtry endwhile Xpath 16777216 " X: 16777216 asdf Xpath 33554432 " X: 33554432 endif if ExtraVim() let p = 1 while p let p = 0 try Xpath 67108864 " X: 67108864 finally Xpath 134217728 " X: 134217728 continue Xpath 268435456 " X: 0 endtry endwhile Xpath 536870912 " X: 536870912 asdf Xpath 1073741824 " X: 1073741824 endif Xcheck 1874575085 "------------------------------------------------------------------------------- " Test 21: :finally for :try after :continue/:break/:return/:finish {{{1 " " If a :try conditional stays inactive due to a preceding :continue, " :break, :return, or :finish, its :finally clause should not be " executed. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() function F() let loops = 2 XloopINIT! 1 256 while loops > 0 XloopNEXT let loops = loops - 1 try if loops == 1 Xloop 1 " X: 1 continue Xloop 2 " X: 0 elseif loops == 0 Xloop 4 " X: 4*256 break Xloop 8 " X: 0 endif try " inactive Xloop 16 " X: 0 finally Xloop 32 " X: 0 endtry finally Xloop 64 " X: 64 + 64*256 endtry Xloop 128 " X: 0 endwhile try Xpath 65536 " X: 65536 return Xpath 131072 " X: 0 try " inactive Xpath 262144 " X: 0 finally Xpath 524288 " X: 0 endtry finally Xpath 1048576 " X: 1048576 endtry Xpath 2097152 " X: 0 endfunction try Xpath 4194304 " X: 4194304 call F() Xpath 8388608 " X: 8388608 finish Xpath 16777216 " X: 0 try " inactive Xpath 33554432 " X: 0 finally Xpath 67108864 " X: 0 endtry finally Xpath 134217728 " X: 134217728 endtry Xpath 268435456 " X: 0 endif Xcheck 147932225 "------------------------------------------------------------------------------- " Test 22: :finally for a :try after an error/interrupt/:throw {{{1 " " If a :try conditional stays inactive due to a preceding error or " interrupt or :throw, its :finally clause should not be executed. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() function! Error() try asdf " aborting error, triggering error exception endtry endfunction Xpath 1 " X: 1 call Error() Xpath 2 " X: 0 if 1 " not active due to error try " not active since :if inactive Xpath 4 " X: 0 finally Xpath 8 " X: 0 endtry endif try " not active due to error Xpath 16 " X: 0 finally Xpath 32 " X: 0 endtry endif if ExtraVim() function! Interrupt() try "INTERRUPT " triggering interrupt exception endtry endfunction Xpath 64 " X: 64 call Interrupt() Xpath 128 " X: 0 if 1 " not active due to interrupt try " not active since :if inactive Xpath 256 " X: 0 finally Xpath 512 " X: 0 endtry endif try " not active due to interrupt Xpath 1024 " X: 0 finally Xpath 2048 " X: 0 endtry endif if ExtraVim() function! Throw() throw "xyz" endfunction Xpath 4096 " X: 4096 call Throw() Xpath 8192 " X: 0 if 1 " not active due to :throw try " not active since :if inactive Xpath 16384 " X: 0 finally Xpath 32768 " X: 0 endtry endif try " not active due to :throw Xpath 65536 " X: 0 finally Xpath 131072 " X: 0 endtry endif Xcheck 4161 "------------------------------------------------------------------------------- " Test 23: :catch clauses for a :try after a :throw {{{1 " " If a :try conditional stays inactive due to a preceding :throw, " none of its :catch clauses should be executed. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() try Xpath 1 " X: 1 throw "xyz" Xpath 2 " X: 0 if 1 " not active due to :throw try " not active since :if inactive Xpath 4 " X: 0 catch /xyz/ Xpath 8 " X: 0 endtry endif catch /xyz/ Xpath 16 " X: 16 endtry Xpath 32 " X: 32 throw "abc" Xpath 64 " X: 0 try " not active due to :throw Xpath 128 " X: 0 catch /abc/ Xpath 256 " X: 0 endtry endif Xcheck 49 "------------------------------------------------------------------------------- " Test 24: :endtry for a :try after a :throw {{{1 " " If a :try conditional stays inactive due to a preceding :throw, " its :endtry should not rethrow the exception to the next surrounding " active :try conditional. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() try " try 1 try " try 2 Xpath 1 " X: 1 throw "xyz" " makes try 2 inactive Xpath 2 " X: 0 try " try 3 Xpath 4 " X: 0 endtry " no rethrow to try 1 catch /xyz/ " should catch although try 2 inactive Xpath 8 " X: 8 endtry catch /xyz/ " try 1 active, but exception already caught Xpath 16 " X: 0 endtry Xpath 32 " X: 32 endif Xcheck 41 "------------------------------------------------------------------------------- " Test 25: Executing :finally clauses on normal control flow {{{1 " " Control flow in a :try conditional should always fall through to its " :finally clause. A :finally clause of a :try conditional inside an " inactive conditional should never be executed. "------------------------------------------------------------------------------- XpathINIT function! F() let loops = 3 XloopINIT 1 256 while loops > 0 " 3: 2: 1: Xloop 1 " X: 1 + 1*256 + 1*256*256 if loops >= 2 try Xloop 2 " X: 2 + 2*256 if loops == 2 try Xloop 4 " X: 4*256 finally Xloop 8 " X: 8*256 endtry endif finally Xloop 16 " X: 16 + 16*256 if loops == 2 try Xloop 32 " X: 32*256 finally Xloop 64 " X: 64*256 endtry endif endtry endif Xloop 128 " X: 128 + 128*256 + 128*256*256 let loops = loops - 1 XloopNEXT endwhile Xpath 16777216 " X: 16777216 endfunction if 1 try Xpath 33554432 " X: 33554432 call F() Xpath 67108864 " X: 67108864 finally Xpath 134217728 " X: 134217728 endtry else try Xpath 268435456 " X: 0 finally Xpath 536870912 " X: 0 endtry endif delfunction F Xcheck 260177811 "------------------------------------------------------------------------------- " Test 26: Executing :finally clauses after :continue or :break {{{1 " " For a :continue or :break dynamically enclosed in a :try/:endtry " region inside the next surrounding :while/:endwhile, if the " :continue/:break is before the :finally, the :finally clause is " executed first. If the :continue/:break is after the :finally, the " :finally clause is broken (like an :if/:endif region). "------------------------------------------------------------------------------- XpathINIT try let loops = 3 XloopINIT! 1 32 while loops > 0 XloopNEXT try try if loops == 2 " 3: 2: 1: Xloop 1 " X: 1*32 let loops = loops - 1 continue elseif loops == 1 Xloop 2 " X: 2*32*32 break finish endif Xloop 4 " X: 4 endtry finally Xloop 8 " X: 8 + 8*32 + 8*32*32 endtry Xloop 16 " X: 16 let loops = loops - 1 endwhile Xpath 32768 " X: 32768 finally Xpath 65536 " X: 65536 let loops = 3 XloopINIT 131072 16 while loops > 0 try finally try if loops == 2 Xloop 1 " X: 131072*16 let loops = loops - 1 XloopNEXT continue elseif loops == 1 Xloop 2 " X: 131072*2*16*16 break finish endif endtry Xloop 4 " X: 131072*4 endtry Xloop 8 " X: 131072*8 let loops = loops - 1 XloopNEXT endwhile Xpath 536870912 " X: 536870912 endtry Xpath 1073741824 " X: 1073741824 unlet loops Xcheck 1681500476 "------------------------------------------------------------------------------- " Test 27: Executing :finally clauses after :return {{{1 " " For a :return command dynamically enclosed in a :try/:endtry region, " :finally clauses are executed and the called function is ended. "------------------------------------------------------------------------------- XpathINIT function! F() try Xpath 1 " X: 1 try Xpath 2 " X: 2 return Xpath 4 " X: 0 finally Xpath 8 " X: 8 endtry Xpath 16 " X: 0 finally Xpath 32 " X: 32 endtry Xpath 64 " X: 0 endfunction function! G() try Xpath 128 " X: 128 return Xpath 256 " X: 0 finally Xpath 512 " X: 512 call F() Xpath 1024 " X: 1024 endtry Xpath 2048 " X: 0 endfunction function! H() try Xpath 4096 " X: 4096 call G() Xpath 8192 " X: 8192 finally Xpath 16384 " X: 16384 return Xpath 32768 " X: 0 endtry Xpath 65536 " X: 0 endfunction try Xpath 131072 " X: 131072 call H() Xpath 262144 " X: 262144 finally Xpath 524288 " X: 524288 endtry Xpath 1048576 " X: 1048576 Xcheck 1996459 " Leave F, G, and H for execution as scripts in the next test. "------------------------------------------------------------------------------- " Test 28: Executing :finally clauses after :finish {{{1 " " For a :finish command dynamically enclosed in a :try/:endtry region, " :finally clauses are executed and the sourced file is finished. " " This test executes the bodies of the functions F, G, and H from the " previous test as script files (:return replaced by :finish). "------------------------------------------------------------------------------- XpathINIT let scriptF = MakeScript("F") " X: 1 + 2 + 8 + 32 let scriptG = MakeScript("G", scriptF) " X: 128 + 512 + 1024 let scriptH = MakeScript("H", scriptG) " X: 4096 + 8192 + 16384 try Xpath 131072 " X: 131072 exec "source" scriptH Xpath 262144 " X: 262144 finally Xpath 524288 " X: 524288 endtry Xpath 1048576 " X: 1048576 call delete(scriptF) call delete(scriptG) call delete(scriptH) unlet scriptF scriptG scriptH delfunction F delfunction G delfunction H Xcheck 1996459 "------------------------------------------------------------------------------- " Test 29: Executing :finally clauses on errors {{{1 " " After an error in a command dynamically enclosed in a :try/:endtry " region, :finally clauses are executed and the script processing is " terminated. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() function! F() while 1 try Xpath 1 " X: 1 while 1 try Xpath 2 " X: 2 asdf " error Xpath 4 " X: 0 finally Xpath 8 " X: 8 endtry | Xpath 16 " X: 0 Xpath 32 " X: 0 break endwhile Xpath 64 " X: 0 finally Xpath 128 " X: 128 endtry | Xpath 256 " X: 0 Xpath 512 " X: 0 break endwhile Xpath 1024 " X: 0 endfunction while 1 try Xpath 2048 " X: 2048 while 1 call F() Xpath 4096 " X: 0 break endwhile | Xpath 8192 " X: 0 Xpath 16384 " X: 0 finally Xpath 32768 " X: 32768 endtry | Xpath 65536 " X: 0 endwhile | Xpath 131072 " X: 0 Xpath 262144 " X: 0 endif if ExtraVim() function! G() abort if 1 try Xpath 524288 " X: 524288 asdf " error Xpath 1048576 " X: 0 finally Xpath 2097152 " X: 2097152 endtry | Xpath 4194304 " X: 0 endif | Xpath 8388608 " X: 0 Xpath 16777216 " X: 0 endfunction if 1 try Xpath 33554432 " X: 33554432 call G() Xpath 67108864 " X: 0 finally Xpath 134217728 " X: 134217728 endtry | Xpath 268435456 " X: 0 endif | Xpath 536870912 " X: 0 Xpath 1073741824 " X: 0 endif Xcheck 170428555 "------------------------------------------------------------------------------- " Test 30: Executing :finally clauses on interrupt {{{1 " " After an interrupt in a command dynamically enclosed in " a :try/:endtry region, :finally clauses are executed and the " script processing is terminated. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() XloopINIT 1 16 function! F() try Xloop 1 " X: 1 + 1*16 "INTERRUPT Xloop 2 " X: 0 finally Xloop 4 " X: 4 + 4*16 endtry Xloop 8 " X: 0 endfunction try Xpath 256 " X: 256 try Xpath 512 " X: 512 "INTERRUPT Xpath 1024 " X: 0 finally Xpath 2048 " X: 2048 try Xpath 4096 " X: 4096 try Xpath 8192 " X: 8192 finally Xpath 16384 " X: 16384 try Xpath 32768 " X: 32768 "INTERRUPT Xpath 65536 " X: 0 endtry Xpath 131072 " X: 0 endtry Xpath 262144 " X: 0 endtry Xpath 524288 " X: 0 endtry Xpath 1048576 " X: 0 finally Xpath 2097152 " X: 2097152 try Xpath 4194304 " X: 4194304 call F() Xpath 8388608 " X: 0 finally Xpath 16777216 " X: 16777216 try Xpath 33554432 " X: 33554432 XloopNEXT ExecAsScript F Xpath 67108864 " X: 0 finally Xpath 134217728 " X: 134217728 endtry Xpath 268435456 " X: 0 endtry Xpath 536870912 " X: 0 endtry Xpath 1073741824 " X: 0 endif Xcheck 190905173 "------------------------------------------------------------------------------- " Test 31: Executing :finally clauses after :throw {{{1 " " After a :throw dynamically enclosed in a :try/:endtry region, " :finally clauses are executed and the script processing is " terminated. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() XloopINIT 1 16 function! F() try Xloop 1 " X: 1 + 1*16 throw "exception" Xloop 2 " X: 0 finally Xloop 4 " X: 4 + 4*16 endtry Xloop 8 " X: 0 endfunction try Xpath 256 " X: 256 try Xpath 512 " X: 512 throw "exception" Xpath 1024 " X: 0 finally Xpath 2048 " X: 2048 try Xpath 4096 " X: 4096 try Xpath 8192 " X: 8192 finally Xpath 16384 " X: 16384 try Xpath 32768 " X: 32768 throw "exception" Xpath 65536 " X: 0 endtry Xpath 131072 " X: 0 endtry Xpath 262144 " X: 0 endtry Xpath 524288 " X: 0 endtry Xpath 1048576 " X: 0 finally Xpath 2097152 " X: 2097152 try Xpath 4194304 " X: 4194304 call F() Xpath 8388608 " X: 0 finally Xpath 16777216 " X: 16777216 try Xpath 33554432 " X: 33554432 XloopNEXT ExecAsScript F Xpath 67108864 " X: 0 finally Xpath 134217728 " X: 134217728 endtry Xpath 268435456 " X: 0 endtry Xpath 536870912 " X: 0 endtry Xpath 1073741824 " X: 0 endif Xcheck 190905173 "------------------------------------------------------------------------------- " Test 32: Remembering the :return value on :finally {{{1 " " If a :finally clause is executed due to a :return specifying " a value, this is the value visible to the caller if not overwritten " by a new :return in the :finally clause. A :return without a value " in the :finally clause overwrites with value 0. "------------------------------------------------------------------------------- XpathINIT function! F() try Xpath 1 " X: 1 try Xpath 2 " X: 2 return "ABCD" Xpath 4 " X: 0 finally Xpath 8 " X: 8 endtry Xpath 16 " X: 0 finally Xpath 32 " X: 32 endtry Xpath 64 " X: 0 endfunction function! G() try Xpath 128 " X: 128 return 8 Xpath 256 " X: 0 finally Xpath 512 " X: 512 return 16 + strlen(F()) Xpath 1024 " X: 0 endtry Xpath 2048 " X: 0 endfunction function! H() try Xpath 4096 " X: 4096 return 32 Xpath 8192 " X: 0 finally Xpath 16384 " X: 16384 return Xpath 32768 " X: 0 endtry Xpath 65536 " X: 0 endfunction function! I() try Xpath 131072 " X: 131072 finally Xpath 262144 " X: 262144 return G() + H() + 64 Xpath 524288 " X: 0 endtry Xpath 1048576 " X: 0 endfunction let retcode = I() Xpath 2097152 " X: 2097152 if retcode < 0 Xpath 4194304 " X: 0 endif if retcode % 4 Xpath 8388608 " X: 0 endif if (retcode/4) % 2 Xpath 16777216 " X: 16777216 endif if (retcode/8) % 2 Xpath 33554432 " X: 0 endif if (retcode/16) % 2 Xpath 67108864 " X: 67108864 endif if (retcode/32) % 2 Xpath 134217728 " X: 0 endif if (retcode/64) % 2 Xpath 268435456 " X: 268435456 endif if retcode/128 Xpath 536870912 " X: 0 endif unlet retcode delfunction F delfunction G delfunction H delfunction I Xcheck 354833067 "------------------------------------------------------------------------------- " Test 33: :return under :execute or user command and :finally {{{1 " " A :return command may be executed under an ":execute" or from " a user command. Executing of :finally clauses and passing through " the return code works also then. "------------------------------------------------------------------------------- XpathINIT command! -nargs=? RETURN \ try | return <args> | finally | return <args> * 2 | endtry function! F() try RETURN 8 Xpath 1 " X: 0 finally Xpath 2 " X: 2 endtry Xpath 4 " X: 0 endfunction function! G() try RETURN 32 Xpath 8 " X: 0 finally Xpath 16 " X: 16 RETURN 128 Xpath 32 " X: 0 endtry Xpath 64 " X: 0 endfunction function! H() try execute "try | return 512 | finally | return 1024 | endtry" Xpath 128 " X: 0 finally Xpath 256 " X: 256 endtry Xpath 512 " X: 0 endfunction function! I() try execute "try | return 2048 | finally | return 4096 | endtry" Xpath 1024 " X: 0 finally Xpath 2048 " X: 2048 execute "try | return 8192 | finally | return 16384 | endtry" Xpath 4096 " X: 0 endtry Xpath 8192 " X: 0 endfunction function! J() try RETURN 32768 Xpath 16384 " X: 0 finally Xpath 32768 " X: 32768 return Xpath 65536 " X: 0 endtry Xpath 131072 " X: 0 endfunction function! K() try execute "try | return 131072 | finally | return 262144 | endtry" Xpath 262144 " X: 0 finally Xpath 524288 " X: 524288 execute "try | return 524288 | finally | return | endtry" Xpath 1048576 " X: 0 endtry Xpath 2097152 " X: 0 endfunction function! L() try return Xpath 4194304 " X: 0 finally Xpath 8388608 " X: 8388608 RETURN 1048576 Xpath 16777216 " X: 0 endtry Xpath 33554432 " X: 0 endfunction function! M() try return Xpath 67108864 " X: 0 finally Xpath 134217728 " X: 134217728 execute "try | return 4194304 | finally | return 8388608 | endtry" Xpath 268435456 " X: 0 endtry Xpath 536870912 " X: 0 endfunction function! N() RETURN 16777216 endfunction function! O() execute "try | return 67108864 | finally | return 134217728 | endtry" endfunction let sum = F() + G() + H() + I() + J() + K() + L() + M() let expected = 16 + 256 + 1024 + 16384 + 0 + 0 + 2097152 + 8388608 let sum = sum + N() + O() let expected = expected + 33554432 + 134217728 if sum == expected Xout "sum = " . sum . " (ok)" else Xout "sum = " . sum . ", expected: " . expected endif Xpath 1073741824 " X: 1073741824 if sum != expected " The Xpath command does not accept 2^31 (negative); add explicitly: let Xpath = Xpath + 2147483648 " X: 0 endif unlet sum expected delfunction F delfunction G delfunction H delfunction I delfunction J delfunction K delfunction L delfunction M delfunction N delfunction O Xcheck 1216907538 "------------------------------------------------------------------------------- " Test 34: :finally reason discarded by :continue {{{1 " " When a :finally clause is executed due to a :continue, :break, " :return, :finish, error, interrupt or :throw, the jump reason is " discarded by a :continue in the finally clause. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() XloopINIT! 1 8 function! C(jump) XloopNEXT let loop = 0 while loop < 2 let loop = loop + 1 if loop == 1 try if a:jump == "continue" continue elseif a:jump == "break" break elseif a:jump == "return" || a:jump == "finish" return elseif a:jump == "error" asdf elseif a:jump == "interrupt" "INTERRUPT let dummy = 0 elseif a:jump == "throw" throw "abc" endif finally continue " discards jump that caused the :finally Xloop 1 " X: 0 endtry Xloop 2 " X: 0 elseif loop == 2 Xloop 4 " X: 4*(1+8+64+512+4096+32768+262144) endif endwhile endfunction call C("continue") Xpath 2097152 " X: 2097152 call C("break") Xpath 4194304 " X: 4194304 call C("return") Xpath 8388608 " X: 8388608 let g:jump = "finish" ExecAsScript C unlet g:jump Xpath 16777216 " X: 16777216 try call C("error") Xpath 33554432 " X: 33554432 finally Xpath 67108864 " X: 67108864 try call C("interrupt") Xpath 134217728 " X: 134217728 finally Xpath 268435456 " X: 268435456 call C("throw") Xpath 536870912 " X: 536870912 endtry endtry Xpath 1073741824 " X: 1073741824 delfunction C endif Xcheck 2146584868 "------------------------------------------------------------------------------- " Test 35: :finally reason discarded by :break {{{1 " " When a :finally clause is executed due to a :continue, :break, " :return, :finish, error, interrupt or :throw, the jump reason is " discarded by a :break in the finally clause. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() XloopINIT! 1 8 function! B(jump) XloopNEXT let loop = 0 while loop < 2 let loop = loop + 1 if loop == 1 try if a:jump == "continue" continue elseif a:jump == "break" break elseif a:jump == "return" || a:jump == "finish" return elseif a:jump == "error" asdf elseif a:jump == "interrupt" "INTERRUPT let dummy = 0 elseif a:jump == "throw" throw "abc" endif finally break " discards jump that caused the :finally Xloop 1 " X: 0 endtry elseif loop == 2 Xloop 2 " X: 0 endif endwhile Xloop 4 " X: 4*(1+8+64+512+4096+32768+262144) endfunction call B("continue") Xpath 2097152 " X: 2097152 call B("break") Xpath 4194304 " X: 4194304 call B("return") Xpath 8388608 " X: 8388608 let g:jump = "finish" ExecAsScript B unlet g:jump Xpath 16777216 " X: 16777216 try call B("error") Xpath 33554432 " X: 33554432 finally Xpath 67108864 " X: 67108864 try call B("interrupt") Xpath 134217728 " X: 134217728 finally Xpath 268435456 " X: 268435456 call B("throw") Xpath 536870912 " X: 536870912 endtry endtry Xpath 1073741824 " X: 1073741824 delfunction B endif Xcheck 2146584868 "------------------------------------------------------------------------------- " Test 36: :finally reason discarded by :return {{{1 " " When a :finally clause is executed due to a :continue, :break, " :return, :finish, error, interrupt or :throw, the jump reason is " discarded by a :return in the finally clause. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() XloopINIT! 1 8 function! R(jump, retval) abort XloopNEXT let loop = 0 while loop < 2 let loop = loop + 1 if loop == 1 try if a:jump == "continue" continue elseif a:jump == "break" break elseif a:jump == "return" return elseif a:jump == "error" asdf elseif a:jump == "interrupt" "INTERRUPT let dummy = 0 elseif a:jump == "throw" throw "abc" endif finally return a:retval " discards jump that caused the :finally Xloop 1 " X: 0 endtry elseif loop == 2 Xloop 2 " X: 0 endif endwhile Xloop 4 " X: 0 endfunction let sum = -R("continue", -8) Xpath 2097152 " X: 2097152 let sum = sum - R("break", -16) Xpath 4194304 " X: 4194304 let sum = sum - R("return", -32) Xpath 8388608 " X: 8388608 try let sum = sum - R("error", -64) Xpath 16777216 " X: 16777216 finally Xpath 33554432 " X: 33554432 try let sum = sum - R("interrupt", -128) Xpath 67108864 " X: 67108864 finally Xpath 134217728 " X: 134217728 let sum = sum - R("throw", -256) Xpath 268435456 " X: 268435456 endtry endtry Xpath 536870912 " X: 536870912 let expected = 8 + 16 + 32 + 64 + 128 + 256 if sum != expected Xpath 1073741824 " X: 0 Xout "sum =" . sum . ", expected: " . expected endif unlet sum expected delfunction R endif Xcheck 1071644672 "------------------------------------------------------------------------------- " Test 37: :finally reason discarded by :finish {{{1 " " When a :finally clause is executed due to a :continue, :break, " :return, :finish, error, interrupt or :throw, the jump reason is " discarded by a :finish in the finally clause. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() XloopINIT! 1 8 function! F(jump) " not executed as function, transformed to a script XloopNEXT let loop = 0 while loop < 2 let loop = loop + 1 if loop == 1 try if a:jump == "continue" continue elseif a:jump == "break" break elseif a:jump == "finish" finish elseif a:jump == "error" asdf elseif a:jump == "interrupt" "INTERRUPT let dummy = 0 elseif a:jump == "throw" throw "abc" endif finally finish " discards jump that caused the :finally Xloop 1 " X: 0 endtry elseif loop == 2 Xloop 2 " X: 0 endif endwhile Xloop 4 " X: 0 endfunction let scriptF = MakeScript("F") delfunction F let g:jump = "continue" exec "source" scriptF Xpath 2097152 " X: 2097152 let g:jump = "break" exec "source" scriptF Xpath 4194304 " X: 4194304 let g:jump = "finish" exec "source" scriptF Xpath 8388608 " X: 8388608 try let g:jump = "error" exec "source" scriptF Xpath 16777216 " X: 16777216 finally Xpath 33554432 " X: 33554432 try let g:jump = "interrupt" exec "source" scriptF Xpath 67108864 " X: 67108864 finally Xpath 134217728 " X: 134217728 try let g:jump = "throw" exec "source" scriptF Xpath 268435456 " X: 268435456 finally Xpath 536870912 " X: 536870912 endtry endtry endtry unlet g:jump call delete(scriptF) unlet scriptF endif Xcheck 1071644672 "------------------------------------------------------------------------------- " Test 38: :finally reason discarded by an error {{{1 " " When a :finally clause is executed due to a :continue, :break, " :return, :finish, error, interrupt or :throw, the jump reason is " discarded by an error in the finally clause. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() XloopINIT! 1 4 function! E(jump) XloopNEXT let loop = 0 while loop < 2 let loop = loop + 1 if loop == 1 try if a:jump == "continue" continue elseif a:jump == "break" break elseif a:jump == "return" || a:jump == "finish" return elseif a:jump == "error" asdf elseif a:jump == "interrupt" "INTERRUPT let dummy = 0 elseif a:jump == "throw" throw "abc" endif finally asdf " error; discards jump that caused the :finally endtry elseif loop == 2 Xloop 1 " X: 0 endif endwhile Xloop 2 " X: 0 endfunction try Xpath 16384 " X: 16384 call E("continue") Xpath 32768 " X: 0 finally try Xpath 65536 " X: 65536 call E("break") Xpath 131072 " X: 0 finally try Xpath 262144 " X: 262144 call E("return") Xpath 524288 " X: 0 finally try Xpath 1048576 " X: 1048576 let g:jump = "finish" ExecAsScript E Xpath 2097152 " X: 0 finally unlet g:jump try Xpath 4194304 " X: 4194304 call E("error") Xpath 8388608 " X: 0 finally try Xpath 16777216 " X: 16777216 call E("interrupt") Xpath 33554432 " X: 0 finally try Xpath 67108864 " X: 67108864 call E("throw") Xpath 134217728 " X: 0 finally Xpath 268435456 " X: 268435456 delfunction E endtry endtry endtry endtry endtry endtry endtry Xpath 536870912 " X: 0 endif Xcheck 357908480 "------------------------------------------------------------------------------- " Test 39: :finally reason discarded by an interrupt {{{1 " " When a :finally clause is executed due to a :continue, :break, " :return, :finish, error, interrupt or :throw, the jump reason is " discarded by an interrupt in the finally clause. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() XloopINIT! 1 4 function! I(jump) XloopNEXT let loop = 0 while loop < 2 let loop = loop + 1 if loop == 1 try if a:jump == "continue" continue elseif a:jump == "break" break elseif a:jump == "return" || a:jump == "finish" return elseif a:jump == "error" asdf elseif a:jump == "interrupt" "INTERRUPT let dummy = 0 elseif a:jump == "throw" throw "abc" endif finally "INTERRUPT - discards jump that caused the :finally let dummy = 0 endtry elseif loop == 2 Xloop 1 " X: 0 endif endwhile Xloop 2 " X: 0 endfunction try Xpath 16384 " X: 16384 call I("continue") Xpath 32768 " X: 0 finally try Xpath 65536 " X: 65536 call I("break") Xpath 131072 " X: 0 finally try Xpath 262144 " X: 262144 call I("return") Xpath 524288 " X: 0 finally try Xpath 1048576 " X: 1048576 let g:jump = "finish" ExecAsScript I Xpath 2097152 " X: 0 finally unlet g:jump try Xpath 4194304 " X: 4194304 call I("error") Xpath 8388608 " X: 0 finally try Xpath 16777216 " X: 16777216 call I("interrupt") Xpath 33554432 " X: 0 finally try Xpath 67108864 " X: 67108864 call I("throw") Xpath 134217728 " X: 0 finally Xpath 268435456 " X: 268435456 delfunction I endtry endtry endtry endtry endtry endtry endtry Xpath 536870912 " X: 0 endif Xcheck 357908480 "------------------------------------------------------------------------------- " Test 40: :finally reason discarded by :throw {{{1 " " When a :finally clause is executed due to a :continue, :break, " :return, :finish, error, interrupt or :throw, the jump reason is " discarded by a :throw in the finally clause. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() XloopINIT! 1 4 function! T(jump) XloopNEXT let loop = 0 while loop < 2 let loop = loop + 1 if loop == 1 try if a:jump == "continue" continue elseif a:jump == "break" break elseif a:jump == "return" || a:jump == "finish" return elseif a:jump == "error" asdf elseif a:jump == "interrupt" "INTERRUPT let dummy = 0 elseif a:jump == "throw" throw "abc" endif finally throw "xyz" " discards jump that caused the :finally endtry elseif loop == 2 Xloop 1 " X: 0 endif endwhile Xloop 2 " X: 0 endfunction try Xpath 16384 " X: 16384 call T("continue") Xpath 32768 " X: 0 finally try Xpath 65536 " X: 65536 call T("break") Xpath 131072 " X: 0 finally try Xpath 262144 " X: 262144 call T("return") Xpath 524288 " X: 0 finally try Xpath 1048576 " X: 1048576 let g:jump = "finish" ExecAsScript T Xpath 2097152 " X: 0 finally unlet g:jump try Xpath 4194304 " X: 4194304 call T("error") Xpath 8388608 " X: 0 finally try Xpath 16777216 " X: 16777216 call T("interrupt") Xpath 33554432 " X: 0 finally try Xpath 67108864 " X: 67108864 call T("throw") Xpath 134217728 " X: 0 finally Xpath 268435456 " X: 268435456 delfunction T endtry endtry endtry endtry endtry endtry endtry Xpath 536870912 " X: 0 endif Xcheck 357908480 "------------------------------------------------------------------------------- " Test 41: Skipped :throw finding next command {{{1 " " A :throw in an inactive conditional must not hide a following " command. "------------------------------------------------------------------------------- XpathINIT function! F() Xpath 1 " X: 1 if 0 | throw "never" | endif | Xpath 2 " X: 2 Xpath 4 " X: 4 endfunction function! G() Xpath 8 " X: 8 while 0 | throw "never" | endwhile | Xpath 16 " X: 16 Xpath 32 " X: 32 endfunction function H() Xpath 64 " X: 64 if 0 | try | throw "never" | endtry | endif | Xpath 128 " X: 128 Xpath 256 " X: 256 endfunction Xpath 512 " X: 512 try Xpath 1024 " X: 1024 call F() Xpath 2048 " X: 2048 catch /.*/ Xpath 4096 " X: 0 Xout v:exception "in" v:throwpoint endtry Xpath 8192 " X: 8192 try Xpath 16384 " X: 16384 call G() Xpath 32768 " X: 32768 catch /.*/ Xpath 65536 " X: 0 Xout v:exception "in" v:throwpoint endtry Xpath 131072 " X: 131072 try Xpath 262144 " X: 262144 call H() Xpath 524288 " X: 524288 catch /.*/ Xpath 1048576 " X: 0 Xout v:exception "in" v:throwpoint endtry Xpath 2097152 " X: 2097152 delfunction F delfunction G delfunction H Xcheck 3076095 "------------------------------------------------------------------------------- " Test 42: Catching number and string exceptions {{{1 " " When a number is thrown, it is converted to a string exception. " Numbers and strings may be caught by specifying a regular exception " as argument to the :catch command. "------------------------------------------------------------------------------- XpathINIT try try Xpath 1 " X: 1 throw 4711 Xpath 2 " X: 0 catch /4711/ Xpath 4 " X: 4 endtry try Xpath 8 " X: 8 throw 4711 Xpath 16 " X: 0 catch /^4711$/ Xpath 32 " X: 32 endtry try Xpath 64 " X: 64 throw 4711 Xpath 128 " X: 0 catch /\d/ Xpath 256 " X: 256 endtry try Xpath 512 " X: 512 throw 4711 Xpath 1024 " X: 0 catch /^\d\+$/ Xpath 2048 " X: 2048 endtry try Xpath 4096 " X: 4096 throw "arrgh" Xpath 8192 " X: 0 catch /arrgh/ Xpath 16384 " X: 16384 endtry try Xpath 32768 " X: 32768 throw "arrgh" Xpath 65536 " X: 0 catch /^arrgh$/ Xpath 131072 " X: 131072 endtry try Xpath 262144 " X: 262144 throw "arrgh" Xpath 524288 " X: 0 catch /\l/ Xpath 1048576 " X: 1048576 endtry try Xpath 2097152 " X: 2097152 throw "arrgh" Xpath 4194304 " X: 0 catch /^\l\+$/ Xpath 8388608 " X: 8388608 endtry try try Xpath 16777216 " X: 16777216 throw "ARRGH" Xpath 33554432 " X: 0 catch /^arrgh$/ Xpath 67108864 " X: 0 endtry catch /^\carrgh$/ Xpath 134217728 " X: 134217728 endtry try Xpath 268435456 " X: 268435456 throw "" Xpath 536870912 " X: 0 catch /^$/ Xpath 1073741824 " X: 1073741824 endtry catch /.*/ " The Xpath command does not accept 2^31 (negative); add explicitly: let Xpath = Xpath + 2147483648 " X: 0 Xout v:exception "in" v:throwpoint endtry Xcheck 1505155949 "------------------------------------------------------------------------------- " Test 43: Selecting the correct :catch clause {{{1 " " When an exception is thrown and there are multiple :catch clauses, " the first matching one is taken. "------------------------------------------------------------------------------- XpathINIT XloopINIT 1 1024 let loops = 3 while loops > 0 try if loops == 3 Xloop 1 " X: 1 throw "a" Xloop 2 " X: 0 elseif loops == 2 Xloop 4 " X: 4*1024 throw "ab" Xloop 8 " X: 0 elseif loops == 1 Xloop 16 " X: 16*1024*1024 throw "abc" Xloop 32 " X: 0 endif catch /abc/ Xloop 64 " X: 64*1024*1024 catch /ab/ Xloop 128 " X: 128*1024 catch /.*/ Xloop 256 " X: 256 catch /a/ Xloop 512 " X: 0 endtry let loops = loops - 1 XloopNEXT endwhile Xpath 1073741824 " X: 1073741824 unlet loops Xcheck 1157763329 "------------------------------------------------------------------------------- " Test 44: Missing or empty :catch patterns {{{1 " " A missing or empty :catch pattern means the same as /.*/, that is, " catches everything. To catch only empty exceptions, /^$/ must be " used. A :catch with missing, empty, or /.*/ argument also works " when followed by another command separated by a bar on the same " line. :catch patterns cannot be specified between ||. But other " pattern separators can be used instead of //. "------------------------------------------------------------------------------- XpathINIT try try Xpath 1 " X: 1 throw "" catch /^$/ Xpath 2 " X: 2 endtry try Xpath 4 " X: 4 throw "" catch /.*/ Xpath 8 " X: 8 endtry try Xpath 16 " X: 16 throw "" catch // Xpath 32 " X: 32 endtry try Xpath 64 " X: 64 throw "" catch Xpath 128 " X: 128 endtry try Xpath 256 " X: 256 throw "oops" catch /^$/ Xpath 512 " X: 0 catch /.*/ Xpath 1024 " X: 1024 endtry try Xpath 2048 " X: 2048 throw "arrgh" catch /^$/ Xpath 4096 " X: 0 catch // Xpath 8192 " X: 8192 endtry try Xpath 16384 " X: 16384 throw "brrr" catch /^$/ Xpath 32768 " X: 0 catch Xpath 65536 " X: 65536 endtry try | Xpath 131072 | throw "x" | catch /.*/ | Xpath 262144 | endtry " X: 131072 + 262144 try | Xpath 524288 | throw "y" | catch // | Xpath 1048576 | endtry " X: 524288 + 1048576 while 1 try let caught = 0 let v:errmsg = "" " Extra try level: if ":catch" without arguments below raises " a syntax error because it misinterprets the "Xpath" as a pattern, " let it be caught by the ":catch /.*/" below. try try | Xpath 2097152 | throw "z" | catch | Xpath 4194304 | : endtry " X: 2097152 + 4194304 endtry catch /.*/ let caught = 1 Xout v:exception "in" v:throwpoint finally if $VIMNOERRTHROW && v:errmsg != "" Xout v:errmsg endif if caught || $VIMNOERRTHROW && v:errmsg != "" Xpath 8388608 " X: 0 endif break " discard error for $VIMNOERRTHROW endtry endwhile let cologne = 4711 try try Xpath 16777216 " X: 16777216 throw "throw cologne" " Next lines catches all and throws 4711: catch |throw cologne| Xpath 33554432 " X: 0 endtry catch /4711/ Xpath 67108864 " X: 67108864 endtry try Xpath 134217728 " X: 134217728 throw "plus" catch +plus+ Xpath 268435456 " X: 268435456 endtry Xpath 536870912 " X: 536870912 catch /.*/ Xpath 1073741824 " X: 0 Xout v:exception "in" v:throwpoint endtry unlet! caught cologne Xcheck 1031761407 "------------------------------------------------------------------------------- " Test 45: Catching exceptions from nested :try blocks {{{1 " " When :try blocks are nested, an exception is caught by the innermost " try conditional that has a matching :catch clause. "------------------------------------------------------------------------------- XpathINIT XloopINIT 1 1024 let loops = 3 while loops > 0 try try try try if loops == 3 Xloop 1 " X: 1 throw "a" Xloop 2 " X: 0 elseif loops == 2 Xloop 4 " X: 4*1024 throw "ab" Xloop 8 " X: 0 elseif loops == 1 Xloop 16 " X: 16*1024*1024 throw "abc" Xloop 32 " X: 0 endif catch /abc/ Xloop 64 " X: 64*1024*1024 endtry catch /ab/ Xloop 128 " X: 128*1024 endtry catch /.*/ Xloop 256 " X: 256 endtry catch /a/ Xloop 512 " X: 0 endtry let loops = loops - 1 XloopNEXT endwhile Xpath 1073741824 " X: 1073741824 unlet loops Xcheck 1157763329 "------------------------------------------------------------------------------- " Test 46: Executing :finally after a :throw in nested :try {{{1 " " When an exception is thrown from within nested :try blocks, the " :finally clauses of the non-catching try conditionals should be " executed before the matching :catch of the next surrounding :try " gets the control. If this also has a :finally clause, it is " executed afterwards. "------------------------------------------------------------------------------- XpathINIT let sum = 0 try Xpath 1 " X: 1 try Xpath 2 " X: 2 try Xpath 4 " X: 4 try Xpath 8 " X: 8 throw "ABC" Xpath 16 " X: 0 catch /xyz/ Xpath 32 " X: 0 finally Xpath 64 " X: 64 if sum != 0 Xpath 128 " X: 0 endif let sum = sum + 1 endtry Xpath 256 " X: 0 catch /123/ Xpath 512 " X: 0 catch /321/ Xpath 1024 " X: 0 finally Xpath 2048 " X: 2048 if sum != 1 Xpath 4096 " X: 0 endif let sum = sum + 2 endtry Xpath 8192 " X: 0 finally Xpath 16384 " X: 16384 if sum != 3 Xpath 32768 " X: 0 endif let sum = sum + 4 endtry Xpath 65536 " X: 0 catch /ABC/ Xpath 131072 " X: 131072 if sum != 7 Xpath 262144 " X: 0 endif let sum = sum + 8 finally Xpath 524288 " X: 524288 if sum != 15 Xpath 1048576 " X: 0 endif let sum = sum + 16 endtry Xpath 65536 " X: 65536 if sum != 31 Xpath 131072 " X: 0 endif unlet sum Xcheck 739407 "------------------------------------------------------------------------------- " Test 47: Throwing exceptions from a :catch clause {{{1 " " When an exception is thrown from a :catch clause, it should not be " caught by a :catch of the same :try conditional. After executing " the :finally clause (if present), surrounding try conditionals " should be checked for a matching :catch. "------------------------------------------------------------------------------- XpathINIT Xpath 1 " X: 1 try Xpath 2 " X: 2 try Xpath 4 " X: 4 try Xpath 8 " X: 8 throw "x1" Xpath 16 " X: 0 catch /x1/ Xpath 32 " X: 32 try Xpath 64 " X: 64 throw "x2" Xpath 128 " X: 0 catch /x1/ Xpath 256 " X: 0 catch /x2/ Xpath 512 " X: 512 try Xpath 1024 " X: 1024 throw "x3" Xpath 2048 " X: 0 catch /x1/ Xpath 4096 " X: 0 catch /x2/ Xpath 8192 " X: 0 finally Xpath 16384 " X: 16384 endtry Xpath 32768 " X: 0 catch /x3/ Xpath 65536 " X: 0 endtry Xpath 131072 " X: 0 catch /x1/ Xpath 262144 " X: 0 catch /x2/ Xpath 524288 " X: 0 catch /x3/ Xpath 1048576 " X: 0 finally Xpath 2097152 " X: 2097152 endtry Xpath 4194304 " X: 0 catch /x1/ Xpath 8388608 " X: 0 catch /x2/ Xpath 16777216 " X: 0 catch /x3/ Xpath 33554432 " X: 33554432 endtry Xpath 67108864 " X: 67108864 catch /.*/ Xpath 134217728 " X: 0 Xout v:exception "in" v:throwpoint endtry Xpath 268435456 " X: 268435456 Xcheck 371213935 "------------------------------------------------------------------------------- " Test 48: Throwing exceptions from a :finally clause {{{1 " " When an exception is thrown from a :finally clause, it should not be " caught by a :catch of the same :try conditional. Surrounding try " conditionals should be checked for a matching :catch. A previously " thrown exception is discarded. "------------------------------------------------------------------------------- XpathINIT try try try Xpath 1 " X: 1 catch /x1/ Xpath 2 " X: 0 finally Xpath 4 " X: 4 throw "x1" Xpath 8 " X: 0 endtry Xpath 16 " X: 0 catch /x1/ Xpath 32 " X: 32 endtry Xpath 64 " X: 64 try try Xpath 128 " X: 128 throw "x2" Xpath 256 " X: 0 catch /x2/ Xpath 512 " X: 512 catch /x3/ Xpath 1024 " X: 0 finally Xpath 2048 " X: 2048 throw "x3" Xpath 4096 " X: 0 endtry Xpath 8192 " X: 0 catch /x2/ Xpath 16384 " X: 0 catch /x3/ Xpath 32768 " X: 32768 endtry Xpath 65536 " X: 65536 try try try Xpath 131072 " X: 131072 throw "x4" Xpath 262144 " X: 0 catch /x5/ Xpath 524288 " X: 0 finally Xpath 1048576 " X: 1048576 throw "x5" " discards "x4" Xpath 2097152 " X: 0 endtry Xpath 4194304 " X: 0 catch /x4/ Xpath 8388608 " X: 0 finally Xpath 16777216 " X: 16777216 endtry Xpath 33554432 " X: 0 catch /x5/ Xpath 67108864 " X: 67108864 endtry Xpath 134217728 " X: 134217728 catch /.*/ Xpath 268435456 " X: 0 Xout v:exception "in" v:throwpoint endtry Xpath 536870912 " X: 536870912 Xcheck 756255461 "------------------------------------------------------------------------------- " Test 49: Throwing exceptions across functions {{{1 " " When an exception is thrown but not caught inside a function, the " caller is checked for a matching :catch clause. "------------------------------------------------------------------------------- XpathINIT function! C() try Xpath 1 " X: 1 throw "arrgh" Xpath 2 " X: 0 catch /arrgh/ Xpath 4 " X: 4 endtry Xpath 8 " X: 8 endfunction XloopINIT! 16 16 function! T1() XloopNEXT try Xloop 1 " X: 16 + 16*16 throw "arrgh" Xloop 2 " X: 0 finally Xloop 4 " X: 64 + 64*16 endtry Xloop 8 " X: 0 endfunction function! T2() try Xpath 4096 " X: 4096 call T1() Xpath 8192 " X: 0 finally Xpath 16384 " X: 16384 endtry Xpath 32768 " X: 0 endfunction try Xpath 65536 " X: 65536 call C() " throw and catch Xpath 131072 " X: 131072 catch /.*/ Xpath 262144 " X: 0 Xout v:exception "in" v:throwpoint endtry try Xpath 524288 " X: 524288 call T1() " throw, one level Xpath 1048576 " X: 0 catch /arrgh/ Xpath 2097152 " X: 2097152 catch /.*/ Xpath 4194304 " X: 0 Xout v:exception "in" v:throwpoint endtry try Xpath 8388608 " X: 8388608 call T2() " throw, two levels Xpath 16777216 " X: 0 catch /arrgh/ Xpath 33554432 " X: 33554432 catch /.*/ Xpath 67108864 " X: 0 Xout v:exception "in" v:throwpoint endtry Xpath 134217728 " X: 134217728 Xcheck 179000669 " Leave C, T1, and T2 for execution as scripts in the next test. "------------------------------------------------------------------------------- " Test 50: Throwing exceptions across script files {{{1 " " When an exception is thrown but not caught inside a script file, " the sourcing script or function is checked for a matching :catch " clause. " " This test executes the bodies of the functions C, T1, and T2 from " the previous test as script files (:return replaced by :finish). "------------------------------------------------------------------------------- XpathINIT let scriptC = MakeScript("C") " X: 1 + 4 + 8 delfunction C XloopINIT! 16 16 let scriptT1 = MakeScript("T1") " X: 16 + 64 + 16*16 + 64*16 delfunction T1 let scriptT2 = MakeScript("T2", scriptT1) " X: 4096 + 16384 delfunction T2 function! F() try Xpath 65536 " X: 65536 exec "source" g:scriptC Xpath 131072 " X: 131072 catch /.*/ Xpath 262144 " X: 0 Xout v:exception "in" v:throwpoint endtry try Xpath 524288 " X: 524288 exec "source" g:scriptT1 Xpath 1048576 " X: 0 catch /arrgh/ Xpath 2097152 " X: 2097152 catch /.*/ Xpath 4194304 " X: 0 Xout v:exception "in" v:throwpoint endtry endfunction try Xpath 8388608 " X: 8388608 call F() Xpath 16777216 " X: 16777216 exec "source" scriptT2 Xpath 33554432 " X: 0 catch /arrgh/ Xpath 67108864 " X: 67108864 catch /.*/ Xpath 134217728 " X: 0 Xout v:exception "in" v:throwpoint endtry Xpath 268435456 " X: 268435456 call delete(scriptC) call delete(scriptT1) call delete(scriptT2) unlet scriptC scriptT1 scriptT2 delfunction F Xcheck 363550045 "------------------------------------------------------------------------------- " Test 51: Throwing exceptions across :execute and user commands {{{1 " " A :throw command may be executed under an ":execute" or from " a user command. "------------------------------------------------------------------------------- XpathINIT command! -nargs=? THROW1 throw <args> | throw 1 command! -nargs=? THROW2 try | throw <args> | endtry | throw 2 command! -nargs=? THROW3 try | throw 3 | catch /3/ | throw <args> | endtry command! -nargs=? THROW4 try | throw 4 | finally | throw <args> | endtry try try try Xpath 1 " X: 1 THROW1 "A" catch /A/ Xpath 2 " X: 2 endtry catch /1/ Xpath 4 " X: 0 endtry try try Xpath 8 " X: 8 THROW2 "B" catch /B/ Xpath 16 " X: 16 endtry catch /2/ Xpath 32 " X: 0 endtry try try Xpath 64 " X: 64 THROW3 "C" catch /C/ Xpath 128 " X: 128 endtry catch /3/ Xpath 256 " X: 0 endtry try try Xpath 512 " X: 512 THROW4 "D" catch /D/ Xpath 1024 " X: 1024 endtry catch /4/ Xpath 2048 " X: 0 endtry try try Xpath 4096 " X: 4096 execute 'throw "E" | throw 5' catch /E/ Xpath 8192 " X: 8192 endtry catch /5/ Xpath 16384 " X: 0 endtry try try Xpath 32768 " X: 32768 execute 'try | throw "F" | endtry | throw 6' catch /F/ Xpath 65536 " X: 65536 endtry catch /6/ Xpath 131072 " X: 0 endtry try try Xpath 262144 " X: 262144 execute'try | throw 7 | catch /7/ | throw "G" | endtry' catch /G/ Xpath 524288 " X: 524288 endtry catch /7/ Xpath 1048576 " X: 0 endtry try try Xpath 2097152 " X: 2097152 execute 'try | throw 8 | finally | throw "H" | endtry' catch /H/ Xpath 4194304 " X: 4194304 endtry catch /8/ Xpath 8388608 " X: 0 endtry catch /.*/ Xpath 16777216 " X: 0 Xout v:exception "in" v:throwpoint endtry Xpath 33554432 " X: 33554432 delcommand THROW1 delcommand THROW2 delcommand THROW3 delcommand THROW4 Xcheck 40744667 "------------------------------------------------------------------------------- " Test 52: Uncaught exceptions {{{1 " " When an exception is thrown but not caught, an error message is " displayed when the script is terminated. In case of an interrupt " or error exception, the normal interrupt or error message(s) are " displayed. "------------------------------------------------------------------------------- XpathINIT let msgfile = tempname() function! MESSAGES(...) try exec "edit" g:msgfile catch /^Vim(edit):/ return 0 endtry let english = v:lang == "C" || v:lang =~ '^[Ee]n' let match = 1 norm gg let num = a:0 / 2 let cnt = 1 while cnt <= num let enr = a:{2*cnt - 1} let emsg= a:{2*cnt} let cnt = cnt + 1 if enr == "" Xout "TODO: Add message number for:" emsg elseif enr == "INT" let enr = "" endif if enr == "" && !english continue endif let pattern = (enr != "") ? enr . ':.*' : '' if english let pattern = pattern . emsg endif if !search(pattern, "W") let match = 0 Xout "No match for:" pattern endif norm $ endwhile bwipeout! return match endfunction if ExtraVim(msgfile) Xpath 1 " X: 1 throw "arrgh" endif Xpath 2 " X: 2 if !MESSAGES('E605', "Exception not caught") Xpath 4 " X: 0 endif if ExtraVim(msgfile) try Xpath 8 " X: 8 throw "oops" catch /arrgh/ Xpath 16 " X: 0 endtry Xpath 32 " X: 0 endif Xpath 64 " X: 64 if !MESSAGES('E605', "Exception not caught") Xpath 128 " X: 0 endif if ExtraVim(msgfile) function! T() throw "brrr" endfunction try Xpath 256 " X: 256 throw "arrgh" catch /.*/ Xpath 512 " X: 512 call T() endtry Xpath 1024 " X: 0 endif Xpath 2048 " X: 2048 if !MESSAGES('E605', "Exception not caught") Xpath 4096 " X: 0 endif if ExtraVim(msgfile) try Xpath 8192 " X: 8192 throw "arrgh" finally Xpath 16384 " X: 16384 throw "brrr" endtry Xpath 32768 " X: 0 endif Xpath 65536 " X: 65536 if !MESSAGES('E605', "Exception not caught") Xpath 131072 " X: 0 endif if ExtraVim(msgfile) try Xpath 262144 " X: 262144 "INTERRUPT endtry Xpath 524288 " X: 0 endif Xpath 1048576 " X: 1048576 if !MESSAGES('INT', "Interrupted") Xpath 2097152 " X: 0 endif if ExtraVim(msgfile) try Xpath 4194304 " X: 4194304 let x = novar " error E121/E15; exception: E121 catch /E15:/ " should not catch Xpath 8388608 " X: 0 endtry Xpath 16777216 " X: 0 endif Xpath 33554432 " X: 33554432 if !MESSAGES('E121', "Undefined variable", 'E15', "Invalid expression") Xpath 67108864 " X: 0 endif if ExtraVim(msgfile) try Xpath 134217728 " X: 134217728 " unlet novar # " error E108/E488; exception: E488 catch /E108:/ " should not catch Xpath 268435456 " X: 0 endtry Xpath 536870912 " X: 0 endif Xpath 1073741824 " X: 1073741824 if !MESSAGES('E108', "No such variable", 'E488', "Trailing characters") " The Xpath command does not accept 2^31 (negative); add explicitly: let Xpath = Xpath + 2147483648 " X: 0 endif call delete(msgfile) unlet msgfile Xcheck 1247112011 " Leave MESSAGES() for the next tests. "------------------------------------------------------------------------------- " Test 53: Nesting errors: :endif/:else/:elseif {{{1 " " For nesting errors of :if conditionals the correct error messages " should be given. " " This test reuses the function MESSAGES() from the previous test. " This functions checks the messages in g:msgfile. "------------------------------------------------------------------------------- XpathINIT let msgfile = tempname() if ExtraVim(msgfile) " endif endif if MESSAGES('E580', ":endif without :if") Xpath 1 " X: 1 endif if ExtraVim(msgfile) " while 1 " endif " endwhile endif if MESSAGES('E580', ":endif without :if") Xpath 2 " X: 2 endif if ExtraVim(msgfile) " try " finally " endif " endtry endif if MESSAGES('E580', ":endif without :if") Xpath 4 " X: 4 endif if ExtraVim(msgfile) " try " endif " endtry endif if MESSAGES('E580', ":endif without :if") Xpath 8 " X: 8 endif if ExtraVim(msgfile) " try " throw "a" " catch /a/ " endif " endtry endif if MESSAGES('E580', ":endif without :if") Xpath 16 " X: 16 endif if ExtraVim(msgfile) " else endif if MESSAGES('E581', ":else without :if") Xpath 32 " X: 32 endif if ExtraVim(msgfile) " while 1 " else " endwhile endif if MESSAGES('E581', ":else without :if") Xpath 64 " X: 64 endif if ExtraVim(msgfile) " try " finally " else " endtry endif if MESSAGES('E581', ":else without :if") Xpath 128 " X: 128 endif if ExtraVim(msgfile) " try " else " endtry endif if MESSAGES('E581', ":else without :if") Xpath 256 " X: 256 endif if ExtraVim(msgfile) " try " throw "a" " catch /a/ " else " endtry endif if MESSAGES('E581', ":else without :if") Xpath 512 " X: 512 endif if ExtraVim(msgfile) " elseif endif if MESSAGES('E582', ":elseif without :if") Xpath 1024 " X: 1024 endif if ExtraVim(msgfile) " while 1 " elseif " endwhile endif if MESSAGES('E582', ":elseif without :if") Xpath 2048 " X: 2048 endif if ExtraVim(msgfile) " try " finally " elseif " endtry endif if MESSAGES('E582', ":elseif without :if") Xpath 4096 " X: 4096 endif if ExtraVim(msgfile) " try " elseif " endtry endif if MESSAGES('E582', ":elseif without :if") Xpath 8192 " X: 8192 endif if ExtraVim(msgfile) " try " throw "a" " catch /a/ " elseif " endtry endif if MESSAGES('E582', ":elseif without :if") Xpath 16384 " X: 16384 endif if ExtraVim(msgfile) " if 1 " else " else " endif endif if MESSAGES('E583', "multiple :else") Xpath 32768 " X: 32768 endif if ExtraVim(msgfile) " if 1 " else " elseif 1 " endif endif if MESSAGES('E584', ":elseif after :else") Xpath 65536 " X: 65536 endif call delete(msgfile) unlet msgfile Xcheck 131071 " Leave MESSAGES() for the next test. "------------------------------------------------------------------------------- " Test 54: Nesting errors: :while/:endwhile {{{1 " " For nesting errors of :while conditionals the correct error messages " should be given. " " This test reuses the function MESSAGES() from the previous test. " This functions checks the messages in g:msgfile. "------------------------------------------------------------------------------- XpathINIT let msgfile = tempname() if ExtraVim(msgfile) " endwhile endif if MESSAGES('E588', ":endwhile without :while") Xpath 1 " X: 1 endif if ExtraVim(msgfile) " if 1 " endwhile " endif endif if MESSAGES('E588', ":endwhile without :while") Xpath 2 " X: 2 endif if ExtraVim(msgfile) " while 1 " if 1 " endwhile endif if MESSAGES('E171', "Missing :endif") Xpath 4 " X: 4 endif if ExtraVim(msgfile) " try " finally " endwhile " endtry endif if MESSAGES('E588', ":endwhile without :while") Xpath 8 " X: 8 endif if ExtraVim(msgfile) " while 1 " try " finally " endwhile endif if MESSAGES('E600', "Missing :endtry") Xpath 16 " X: 16 endif if ExtraVim(msgfile) " while 1 " if 1 " try " finally " endwhile endif if MESSAGES('E600', "Missing :endtry") Xpath 32 " X: 32 endif if ExtraVim(msgfile) " while 1 " try " finally " if 1 " endwhile endif if MESSAGES('E171', "Missing :endif") Xpath 64 " X: 64 endif if ExtraVim(msgfile) " try " endwhile " endtry endif if MESSAGES('E588', ":endwhile without :while") Xpath 128 " X: 128 endif if ExtraVim(msgfile) " while 1 " try " endwhile " endtry " endwhile endif if MESSAGES('E588', ":endwhile without :while") Xpath 256 " X: 256 endif if ExtraVim(msgfile) " try " throw "a" " catch /a/ " endwhile " endtry endif if MESSAGES('E588', ":endwhile without :while") Xpath 512 " X: 512 endif if ExtraVim(msgfile) " while 1 " try " throw "a" " catch /a/ " endwhile " endtry " endwhile endif if MESSAGES('E588', ":endwhile without :while") Xpath 1024 " X: 1024 endif call delete(msgfile) unlet msgfile Xcheck 2047 " Leave MESSAGES() for the next test. "------------------------------------------------------------------------------- " Test 55: Nesting errors: :continue/:break {{{1 " " For nesting errors of :continue and :break commands the correct " error messages should be given. " " This test reuses the function MESSAGES() from the previous test. " This functions checks the messages in g:msgfile. "------------------------------------------------------------------------------- XpathINIT let msgfile = tempname() if ExtraVim(msgfile) " continue endif if MESSAGES('E586', ":continue without :while") Xpath 1 " X: 1 endif if ExtraVim(msgfile) " if 1 " continue " endif endif if MESSAGES('E586', ":continue without :while") Xpath 2 " X: 2 endif if ExtraVim(msgfile) " try " finally " continue " endtry endif if MESSAGES('E586', ":continue without :while") Xpath 4 " X: 4 endif if ExtraVim(msgfile) " try " continue " endtry endif if MESSAGES('E586', ":continue without :while") Xpath 8 " X: 8 endif if ExtraVim(msgfile) " try " throw "a" " catch /a/ " continue " endtry endif if MESSAGES('E586', ":continue without :while") Xpath 16 " X: 16 endif if ExtraVim(msgfile) " break endif if MESSAGES('E587', ":break without :while") Xpath 32 " X: 32 endif if ExtraVim(msgfile) " if 1 " break " endif endif if MESSAGES('E587', ":break without :while") Xpath 64 " X: 64 endif if ExtraVim(msgfile) " try " finally " break " endtry endif if MESSAGES('E587', ":break without :while") Xpath 128 " X: 128 endif if ExtraVim(msgfile) " try " break " endtry endif if MESSAGES('E587', ":break without :while") Xpath 256 " X: 256 endif if ExtraVim(msgfile) " try " throw "a" " catch /a/ " break " endtry endif if MESSAGES('E587', ":break without :while") Xpath 512 " X: 512 endif call delete(msgfile) unlet msgfile Xcheck 1023 " Leave MESSAGES() for the next test. "------------------------------------------------------------------------------- " Test 56: Nesting errors: :endtry {{{1 " " For nesting errors of :try conditionals the correct error messages " should be given. " " This test reuses the function MESSAGES() from the previous test. " This functions checks the messages in g:msgfile. "------------------------------------------------------------------------------- XpathINIT let msgfile = tempname() if ExtraVim(msgfile) " endtry endif if MESSAGES('E602', ":endtry without :try") Xpath 1 " X: 1 endif if ExtraVim(msgfile) " if 1 " endtry " endif endif if MESSAGES('E602', ":endtry without :try") Xpath 2 " X: 2 endif if ExtraVim(msgfile) " while 1 " endtry " endwhile endif if MESSAGES('E602', ":endtry without :try") Xpath 4 " X: 4 endif if ExtraVim(msgfile) " try " if 1 " endtry endif if MESSAGES('E171', "Missing :endif") Xpath 8 " X: 8 endif if ExtraVim(msgfile) " try " while 1 " endtry endif if MESSAGES('E170', "Missing :endwhile") Xpath 16 " X: 16 endif if ExtraVim(msgfile) " try " finally " if 1 " endtry endif if MESSAGES('E171', "Missing :endif") Xpath 32 " X: 32 endif if ExtraVim(msgfile) " try " finally " while 1 " endtry endif if MESSAGES('E170', "Missing :endwhile") Xpath 64 " X: 64 endif if ExtraVim(msgfile) " try " throw "a" " catch /a/ " if 1 " endtry endif if MESSAGES('E171', "Missing :endif") Xpath 128 " X: 128 endif if ExtraVim(msgfile) " try " throw "a" " catch /a/ " while 1 " endtry endif if MESSAGES('E170', "Missing :endwhile") Xpath 256 " X: 256 endif call delete(msgfile) unlet msgfile delfunction MESSAGES Xcheck 511 "------------------------------------------------------------------------------- " Test 57: v:exception and v:throwpoint for user exceptions {{{1 " " v:exception evaluates to the value of the exception that was caught " most recently and is not finished. (A caught exception is finished " when the next ":catch", ":finally", or ":endtry" is reached.) " v:throwpoint evaluates to the script/function name and line number " where that exception has been thrown. "------------------------------------------------------------------------------- XpathINIT function! FuncException() let g:exception = v:exception endfunction function! FuncThrowpoint() let g:throwpoint = v:throwpoint endfunction let scriptException = MakeScript("FuncException") let scriptThrowPoint = MakeScript("FuncThrowpoint") command! CmdException let g:exception = v:exception command! CmdThrowpoint let g:throwpoint = v:throwpoint XloopINIT! 1 2 function! CHECK(n, exception, throwname, throwline) XloopNEXT let error = 0 if v:exception != a:exception Xout a:n.": v:exception is" v:exception "instead of" a:exception let error = 1 endif if v:throwpoint !~ a:throwname let name = escape(a:throwname, '\') Xout a:n.": v:throwpoint (".v:throwpoint.") does not match" name let error = 1 endif if v:throwpoint !~ a:throwline let line = escape(a:throwline, '\') Xout a:n.": v:throwpoint (".v:throwpoint.") does not match" line let error = 1 endif if error Xloop 1 " X: 0 endif endfunction function! T(arg, line) if a:line == 2 throw a:arg " in line 2 elseif a:line == 4 throw a:arg " in line 4 elseif a:line == 6 throw a:arg " in line 6 elseif a:line == 8 throw a:arg " in line 8 endif endfunction function! G(arg, line) call T(a:arg, a:line) endfunction function! F(arg, line) call G(a:arg, a:line) endfunction let scriptT = MakeScript("T") let scriptG = MakeScript("G", scriptT) let scriptF = MakeScript("F", scriptG) try Xpath 32768 " X: 32768 call F("oops", 2) catch /.*/ Xpath 65536 " X: 65536 let exception = v:exception let throwpoint = v:throwpoint call CHECK(1, "oops", '\<F\.\.G\.\.T\>', '\<2\>') exec "let exception = v:exception" exec "let throwpoint = v:throwpoint" call CHECK(2, "oops", '\<F\.\.G\.\.T\>', '\<2\>') CmdException CmdThrowpoint call CHECK(3, "oops", '\<F\.\.G\.\.T\>', '\<2\>') call FuncException() call FuncThrowpoint() call CHECK(4, "oops", '\<F\.\.G\.\.T\>', '\<2\>') exec "source" scriptException exec "source" scriptThrowPoint call CHECK(5, "oops", '\<F\.\.G\.\.T\>', '\<2\>') try Xpath 131072 " X: 131072 call G("arrgh", 4) catch /.*/ Xpath 262144 " X: 262144 let exception = v:exception let throwpoint = v:throwpoint call CHECK(6, "arrgh", '\<G\.\.T\>', '\<4\>') try Xpath 524288 " X: 524288 let g:arg = "autsch" let g:line = 6 exec "source" scriptF catch /.*/ Xpath 1048576 " X: 1048576 let exception = v:exception let throwpoint = v:throwpoint " Symbolic links in tempname()s are not resolved, whereas resolving " is done for v:throwpoint. Resolve the temporary file name for " scriptT, so that it can be matched against v:throwpoint. call CHECK(7, "autsch", resolve(scriptT), '\<6\>') finally Xpath 2097152 " X: 2097152 let exception = v:exception let throwpoint = v:throwpoint call CHECK(8, "arrgh", '\<G\.\.T\>', '\<4\>') try Xpath 4194304 " X: 4194304 let g:arg = "brrrr" let g:line = 8 exec "source" scriptG catch /.*/ Xpath 8388608 " X: 8388608 let exception = v:exception let throwpoint = v:throwpoint " Resolve scriptT for matching it against v:throwpoint. call CHECK(9, "brrrr", resolve(scriptT), '\<8\>') finally Xpath 16777216 " X: 16777216 let exception = v:exception let throwpoint = v:throwpoint call CHECK(10, "arrgh", '\<G\.\.T\>', '\<4\>') endtry Xpath 33554432 " X: 33554432 let exception = v:exception let throwpoint = v:throwpoint call CHECK(11, "arrgh", '\<G\.\.T\>', '\<4\>') endtry Xpath 67108864 " X: 67108864 let exception = v:exception let throwpoint = v:throwpoint call CHECK(12, "arrgh", '\<G\.\.T\>', '\<4\>') finally Xpath 134217728 " X: 134217728 let exception = v:exception let throwpoint = v:throwpoint call CHECK(13, "oops", '\<F\.\.G\.\.T\>', '\<2\>') endtry Xpath 268435456 " X: 268435456 let exception = v:exception let throwpoint = v:throwpoint call CHECK(14, "oops", '\<F\.\.G\.\.T\>', '\<2\>') finally Xpath 536870912 " X: 536870912 let exception = v:exception let throwpoint = v:throwpoint call CHECK(15, "", '^$', '^$') endtry Xpath 1073741824 " X: 1073741824 unlet exception throwpoint delfunction FuncException delfunction FuncThrowpoint call delete(scriptException) call delete(scriptThrowPoint) unlet scriptException scriptThrowPoint delcommand CmdException delcommand CmdThrowpoint delfunction T delfunction G delfunction F call delete(scriptT) call delete(scriptG) call delete(scriptF) unlet scriptT scriptG scriptF Xcheck 2147450880 "------------------------------------------------------------------------------- " " Test 58: v:exception and v:throwpoint for error/interrupt exceptions {{{1 " " v:exception and v:throwpoint work also for error and interrupt " exceptions. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() function! T(line) if a:line == 2 delfunction T " error (function in use) in line 2 elseif a:line == 4 let dummy = 0 " INTERRUPT1 - interrupt in line 4 endif endfunction while 1 try Xpath 1 " X: 1 let caught = 0 call T(2) catch /.*/ let caught = 1 if v:exception !~ 'Vim(delfunction):' Xpath 2 " X: 0 endif if v:throwpoint !~ '\<T\>' Xpath 4 " X: 0 endif if v:throwpoint !~ '\<2\>' Xpath 8 " X: 0 endif finally Xpath 16 " X: 16 if caught || $VIMNOERRTHROW Xpath 32 " X: 32 endif if v:exception != "" Xpath 64 " X: 0 endif if v:throwpoint != "" Xpath 128 " X: 0 endif break " discard error for $VIMNOERRTHROW endtry endwhile Xpath 256 " X: 256 if v:exception != "" Xpath 512 " X: 0 endif if v:throwpoint != "" Xpath 1024 " X: 0 endif while 1 try Xpath 2048 " X: 2048 let caught = 0 call T(4) catch /.*/ let caught = 1 if v:exception != 'Vim:Interrupt' Xpath 4096 " X: 0 endif if v:throwpoint !~ '\<T\>' Xpath 8192 " X: 0 endif if v:throwpoint !~ '\<4\>' Xpath 16384 " X: 0 endif finally Xpath 32768 " X: 32768 if caught || $VIMNOINTTHROW Xpath 65536 " X: 65536 endif if v:exception != "" Xpath 131072 " X: 0 endif if v:throwpoint != "" Xpath 262144 " X: 0 endif break " discard error for $VIMNOERRTHROW endtry endwhile Xpath 524288 " X: 524288 if v:exception != "" Xpath 1048576 " X: 0 endif if v:throwpoint != "" Xpath 2097152 " X: 0 endif endif Xcheck 624945 "------------------------------------------------------------------------------- " " Test 59: v:exception and v:throwpoint when discarding exceptions {{{1 " " When a :catch clause is left by a ":break" etc or an error or " interrupt exception, v:exception and v:throwpoint are reset. They " are not affected by an exception that is discarded before being " caught. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() XloopINIT! 1 2 let sfile = expand("<sfile>") function! LineNumber() return substitute(substitute(v:throwpoint, g:sfile, '', ""), \ '\D*\(\d*\).*', '\1', "") endfunction command! -nargs=1 SetLineNumber \ try | throw "line" | catch /.*/ | let <args> = LineNumber() | endtry " Check v:exception/v:throwpoint against second/fourth parameter if " specified, check for being empty else. function! CHECK(n, ...) XloopNEXT let exception = a:0 != 0 ? a:1 : "" " second parameter (optional) let emsg = a:0 != 0 ? a:2 : "" " third parameter (optional) let line = a:0 != 0 ? a:3 : 0 " fourth parameter (optional) let error = 0 if emsg != "" " exception is the error number, emsg the English error message text if exception !~ '^E\d\+$' Xout "TODO: Add message number for:" emsg elseif v:lang == "C" || v:lang =~ '^[Ee]n' if exception == "E492" && emsg == "Not an editor command" let exception = '^Vim:' . exception . ': ' . emsg else let exception = '^Vim(\a\+):' . exception . ': ' . emsg endif else if exception == "E492" let exception = '^Vim:' . exception else let exception = '^Vim(\a\+):' . exception endif endif endif if exception == "" && v:exception != "" Xout a:n.": v:exception is set:" v:exception let error = 1 elseif exception != "" && v:exception !~ exception Xout a:n.": v:exception (".v:exception.") does not match" exception let error = 1 endif if line == 0 && v:throwpoint != "" Xout a:n.": v:throwpoint is set:" v:throwpoint let error = 1 elseif line != 0 && v:throwpoint !~ '\<' . line . '\>' Xout a:n.": v:throwpoint (".v:throwpoint.") does not match" line let error = 1 endif if !error Xloop 1 " X: 2097151 endif endfunction while 1 try throw "x1" catch /.*/ break endtry endwhile call CHECK(1) while 1 try throw "x2" catch /.*/ break finally call CHECK(2) endtry break endwhile call CHECK(3) while 1 try let errcaught = 0 try try throw "x3" catch /.*/ SetLineNumber line_before_error asdf endtry catch /.*/ let errcaught = 1 call CHECK(4, 'E492', "Not an editor command", \ line_before_error + 1) endtry finally if !errcaught && $VIMNOERRTHROW call CHECK(4) endif break " discard error for $VIMNOERRTHROW endtry endwhile call CHECK(5) Xpath 2097152 " X: 2097152 while 1 try let intcaught = 0 try try throw "x4" catch /.*/ SetLineNumber two_lines_before_interrupt "INTERRUPT let dummy = 0 endtry catch /.*/ let intcaught = 1 call CHECK(6, "Vim:Interrupt", '', \ two_lines_before_interrupt + 2) endtry finally if !intcaught && $VIMNOINTTHROW call CHECK(6) endif break " discard interrupt for $VIMNOINTTHROW endtry endwhile call CHECK(7) Xpath 4194304 " X: 4194304 while 1 try let errcaught = 0 try try " if 1 SetLineNumber line_before_throw throw "x5" " missing endif catch /.*/ Xpath 8388608 " X: 0 endtry catch /.*/ let errcaught = 1 call CHECK(8, 'E171', "Missing :endif", line_before_throw + 3) endtry finally if !errcaught && $VIMNOERRTHROW call CHECK(8) endif break " discard error for $VIMNOERRTHROW endtry endwhile call CHECK(9) Xpath 16777216 " X: 16777216 try while 1 try throw "x6" finally break endtry break endwhile catch /.*/ Xpath 33554432 " X: 0 endtry call CHECK(10) try while 1 try throw "x7" finally break endtry break endwhile catch /.*/ Xpath 67108864 " X: 0 finally call CHECK(11) endtry call CHECK(12) while 1 try let errcaught = 0 try try throw "x8" finally SetLineNumber line_before_error asdf endtry catch /.*/ let errcaught = 1 call CHECK(13, 'E492', "Not an editor command", \ line_before_error + 1) endtry finally if !errcaught && $VIMNOERRTHROW call CHECK(13) endif break " discard error for $VIMNOERRTHROW endtry endwhile call CHECK(14) Xpath 134217728 " X: 134217728 while 1 try let intcaught = 0 try try throw "x9" finally SetLineNumber two_lines_before_interrupt "INTERRUPT endtry catch /.*/ let intcaught = 1 call CHECK(15, "Vim:Interrupt", '', \ two_lines_before_interrupt + 2) endtry finally if !intcaught && $VIMNOINTTHROW call CHECK(15) endif break " discard interrupt for $VIMNOINTTHROW endtry endwhile call CHECK(16) Xpath 268435456 " X: 268435456 while 1 try let errcaught = 0 try try " if 1 SetLineNumber line_before_throw throw "x10" " missing endif finally call CHECK(17) endtry catch /.*/ let errcaught = 1 call CHECK(18, 'E171', "Missing :endif", line_before_throw + 3) endtry finally if !errcaught && $VIMNOERRTHROW call CHECK(18) endif break " discard error for $VIMNOERRTHROW endtry endwhile call CHECK(19) Xpath 536870912 " X: 536870912 while 1 try let errcaught = 0 try try " if 1 SetLineNumber line_before_throw throw "x11" " missing endif endtry catch /.*/ let errcaught = 1 call CHECK(20, 'E171', "Missing :endif", line_before_throw + 3) endtry finally if !errcaught && $VIMNOERRTHROW call CHECK(20) endif break " discard error for $VIMNOERRTHROW endtry endwhile call CHECK(21) Xpath 1073741824 " X: 1073741824 endif Xcheck 2038431743 "------------------------------------------------------------------------------- " " Test 60: (Re)throwing v:exception; :echoerr. {{{1 " " A user exception can be rethrown after catching by throwing " v:exception. An error or interrupt exception cannot be rethrown " because Vim exceptions cannot be faked. A Vim exception using the " value of v:exception can, however, be triggered by the :echoerr " command. "------------------------------------------------------------------------------- XpathINIT try try Xpath 1 " X: 1 throw "oops" catch /oops/ Xpath 2 " X: 2 throw v:exception " rethrow user exception catch /.*/ Xpath 4 " X: 0 endtry catch /^oops$/ " catches rethrown user exception Xpath 8 " X: 8 catch /.*/ Xpath 16 " X: 0 endtry function! F() try let caught = 0 try Xpath 32 " X: 32 write /n/o/n/w/r/i/t/a/b/l/e/_/f/i/l/e Xpath 64 " X: 0 Xout "did_emsg was reset before executing " . \ "BufWritePost autocommands." catch /^Vim(write):/ let caught = 1 throw v:exception " throw error: cannot fake Vim exception catch /.*/ Xpath 128 " X: 0 finally Xpath 256 " X: 256 if !caught && !$VIMNOERRTHROW Xpath 512 " X: 0 endif endtry catch /^Vim(throw):/ " catches throw error let caught = caught + 1 catch /.*/ Xpath 1024 " X: 0 finally Xpath 2048 " X: 2048 if caught != 2 if !caught && !$VIMNOERRTHROW Xpath 4096 " X: 0 elseif caught Xpath 8192 " X: 0 endif return | " discard error for $VIMNOERRTHROW endif endtry endfunction call F() delfunction F function! G() try let caught = 0 try Xpath 16384 " X: 16384 asdf catch /^Vim/ " catch error exception let caught = 1 " Trigger Vim error exception with value specified after :echoerr let value = substitute(v:exception, '^Vim\((.*)\)\=:', '', "") echoerr value catch /.*/ Xpath 32768 " X: 0 finally Xpath 65536 " X: 65536 if !caught if !$VIMNOERRTHROW Xpath 131072 " X: 0 else let value = "Error" echoerr value endif endif endtry catch /^Vim(echoerr):/ let caught = caught + 1 if v:exception !~ value Xpath 262144 " X: 0 endif catch /.*/ Xpath 524288 " X: 0 finally Xpath 1048576 " X: 1048576 if caught != 2 if !caught && !$VIMNOERRTHROW Xpath 2097152 " X: 0 elseif caught Xpath 4194304 " X: 0 endif return | " discard error for $VIMNOERRTHROW endif endtry endfunction call G() delfunction G unlet! value caught if ExtraVim() try let errcaught = 0 try Xpath 8388608 " X: 8388608 let intcaught = 0 "INTERRUPT catch /^Vim:/ " catch interrupt exception let intcaught = 1 " Trigger Vim error exception with value specified after :echoerr echoerr substitute(v:exception, '^Vim\((.*)\)\=:', '', "") catch /.*/ Xpath 16777216 " X: 0 finally Xpath 33554432 " X: 33554432 if !intcaught if !$VIMNOINTTHROW Xpath 67108864 " X: 0 else echoerr "Interrupt" endif endif endtry catch /^Vim(echoerr):/ let errcaught = 1 if v:exception !~ "Interrupt" Xpath 134217728 " X: 0 endif finally Xpath 268435456 " X: 268435456 if !errcaught && !$VIMNOERRTHROW Xpath 536870912 " X: 0 endif endtry endif Xcheck 311511339 "------------------------------------------------------------------------------- " Test 61: Catching interrupt exceptions {{{1 " " When an interrupt occurs inside a :try/:endtry region, an " interrupt exception is thrown and can be caught. Its value is " "Vim:Interrupt". If the interrupt occurs after an error or a :throw " but before a matching :catch is reached, all following :catches of " that try block are ignored, but the interrupt exception can be " caught by the next surrounding try conditional. An interrupt is " ignored when there is a previous interrupt that has not been caught " or causes a :finally clause to be executed. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() while 1 try try Xpath 1 " X: 1 let caught = 0 "INTERRUPT Xpath 2 " X: 0 catch /^Vim:Interrupt$/ let caught = 1 finally Xpath 4 " X: 4 if caught || $VIMNOINTTHROW Xpath 8 " X: 8 endif endtry catch /.*/ Xpath 16 " X: 0 Xout v:exception "in" v:throwpoint finally break " discard interrupt for $VIMNOINTTHROW endtry endwhile while 1 try try let caught = 0 try Xpath 32 " X: 32 asdf Xpath 64 " X: 0 catch /do_not_catch/ Xpath 128 " X: 0 catch /.*/ "INTERRUPT - throw interrupt if !$VIMNOERRTHROW Xpath 256 " X: 0 catch /.*/ Xpath 512 " X: 0 finally "INTERRUPT - throw interrupt if $VIMNOERRTHROW Xpath 1024 " X: 1024 endtry catch /^Vim:Interrupt$/ let caught = 1 finally Xpath 2048 " X: 2048 if caught || $VIMNOINTTHROW Xpath 4096 " X: 4096 endif endtry catch /.*/ Xpath 8192 " X: 0 Xout v:exception "in" v:throwpoint finally break " discard interrupt for $VIMNOINTTHROW endtry endwhile while 1 try try let caught = 0 try Xpath 16384 " X: 16384 throw "x" Xpath 32768 " X: 0 catch /do_not_catch/ Xpath 65536 " X: 0 catch /x/ "INTERRUPT Xpath 131072 " X: 0 catch /.*/ Xpath 262144 " X: 0 endtry catch /^Vim:Interrupt$/ let caught = 1 finally Xpath 524288 " X: 524288 if caught || $VIMNOINTTHROW Xpath 1048576 " X: 1048576 endif endtry catch /.*/ Xpath 2097152 " X: 0 Xout v:exception "in" v:throwpoint finally break " discard interrupt for $VIMNOINTTHROW endtry endwhile while 1 try let caught = 0 try Xpath 4194304 " X: 4194304 "INTERRUPT Xpath 8388608 " X: 0 catch /do_not_catch/ "INTERRUPT Xpath 16777216 " X: 0 catch /^Vim:Interrupt$/ let caught = 1 finally Xpath 33554432 " X: 33554432 if caught || $VIMNOINTTHROW Xpath 67108864 " X: 67108864 endif endtry catch /.*/ Xpath 134217728 " X: 0 Xout v:exception "in" v:throwpoint finally break " discard interrupt for $VIMNOINTTHROW endtry endwhile Xpath 268435456 " X: 268435456 endif Xcheck 374889517 "------------------------------------------------------------------------------- " Test 62: Catching error exceptions {{{1 " " An error inside a :try/:endtry region is converted to an exception " and can be caught. The error exception has a "Vim(cmdname):" prefix " where cmdname is the name of the failing command, or a "Vim:" prefix " if no command name is known. The "Vim" prefixes cannot be faked. "------------------------------------------------------------------------------- XpathINIT function! MSG(enr, emsg) let english = v:lang == "C" || v:lang =~ '^[Ee]n' if a:enr == "" Xout "TODO: Add message number for:" a:emsg let v:errmsg = ":" . v:errmsg endif let match = 1 if v:errmsg !~ '^'.a:enr.':' || (english && v:errmsg !~ a:emsg) let match = 0 if v:errmsg == "" Xout "Message missing." else let v:errmsg = escape(v:errmsg, '"') Xout "Unexpected message:" v:errmsg endif endif return match endfunction while 1 try try let caught = 0 unlet novar catch /^Vim(unlet):/ let caught = 1 let v:errmsg = substitute(v:exception, '^Vim(unlet):', '', "") finally Xpath 1 " X: 1 if !caught && !$VIMNOERRTHROW Xpath 2 " X: 0 endif if !MSG('E108', "No such variable") Xpath 4 " X: 0 endif endtry catch /.*/ Xpath 8 " X: 0 Xout v:exception "in" v:throwpoint finally break " discard error for $VIMNOERRTHROW endtry endwhile while 1 try try let caught = 0 throw novar " error in :throw catch /^Vim(throw):/ let caught = 1 let v:errmsg = substitute(v:exception, '^Vim(throw):', '', "") finally Xpath 16 " X: 16 if !caught && !$VIMNOERRTHROW Xpath 32 " X: 0 endif if caught ? !MSG('E121', "Undefined variable") \ : !MSG('E15', "Invalid expression") Xpath 64 " X: 0 endif endtry catch /.*/ Xpath 128 " X: 0 Xout v:exception "in" v:throwpoint finally break " discard error for $VIMNOERRTHROW endtry endwhile while 1 try try let caught = 0 throw "Vim:faked" " error: cannot fake Vim exception catch /^Vim(throw):/ let caught = 1 let v:errmsg = substitute(v:exception, '^Vim(throw):', '', "") finally Xpath 256 " X: 256 if !caught && !$VIMNOERRTHROW Xpath 512 " X: 0 endif if !MSG('E608', "Cannot :throw exceptions with 'Vim' prefix") Xpath 1024 " X: 0 endif endtry catch /.*/ Xpath 2048 " X: 0 Xout v:exception "in" v:throwpoint finally break " discard error for $VIMNOERRTHROW endtry endwhile function! F() while 1 " Missing :endwhile endfunction while 1 try try let caught = 0 call F() catch /^Vim(endfunction):/ let caught = 1 let v:errmsg = substitute(v:exception, '^Vim(endfunction):', '', "") finally Xpath 4096 " X: 4096 if !caught && !$VIMNOERRTHROW Xpath 8192 " X: 0 endif if !MSG('E170', "Missing :endwhile") Xpath 16384 " X: 0 endif endtry catch /.*/ Xpath 32768 " X: 0 Xout v:exception "in" v:throwpoint finally break " discard error for $VIMNOERRTHROW endtry endwhile while 1 try try let caught = 0 ExecAsScript F catch /^Vim:/ let caught = 1 let v:errmsg = substitute(v:exception, '^Vim:', '', "") finally Xpath 65536 " X: 65536 if !caught && !$VIMNOERRTHROW Xpath 131072 " X: 0 endif if !MSG('E170', "Missing :endwhile") Xpath 262144 " X: 0 endif endtry catch /.*/ Xpath 524288 " X: 0 Xout v:exception "in" v:throwpoint finally break " discard error for $VIMNOERRTHROW endtry endwhile function! G() call G() endfunction while 1 try let mfd_save = &mfd set mfd=3 try let caught = 0 call G() catch /^Vim(call):/ let caught = 1 let v:errmsg = substitute(v:exception, '^Vim(call):', '', "") finally Xpath 1048576 " X: 1048576 if !caught && !$VIMNOERRTHROW Xpath 2097152 " X: 0 endif if !MSG('E132', "Function call depth is higher than 'maxfuncdepth'") Xpath 4194304 " X: 0 endif endtry catch /.*/ Xpath 8388608 " X: 0 Xout v:exception "in" v:throwpoint finally let &mfd = mfd_save break " discard error for $VIMNOERRTHROW endtry endwhile function! H() return H() endfunction while 1 try let mfd_save = &mfd set mfd=3 try let caught = 0 call H() catch /^Vim(return):/ let caught = 1 let v:errmsg = substitute(v:exception, '^Vim(return):', '', "") finally Xpath 16777216 " X: 16777216 if !caught && !$VIMNOERRTHROW Xpath 33554432 " X: 0 endif if !MSG('E132', "Function call depth is higher than 'maxfuncdepth'") Xpath 67108864 " X: 0 endif endtry catch /.*/ Xpath 134217728 " X: 0 Xout v:exception "in" v:throwpoint finally let &mfd = mfd_save break " discard error for $VIMNOERRTHROW endtry endwhile unlet! caught mfd_save delfunction F delfunction G delfunction H Xpath 268435456 " X: 268435456 Xcheck 286331153 " Leave MSG() for the next test. "------------------------------------------------------------------------------- " Test 63: Suppressing error exceptions by :silent!. {{{1 " " A :silent! command inside a :try/:endtry region suppresses the " conversion of errors to an exception and the immediate abortion on " error. When the commands executed by the :silent! themselves open " a new :try/:endtry region, conversion of errors to exception and " immediate abortion is switched on again - until the next :silent! " etc. The :silent! has the effect of setting v:errmsg to the error " message text (without displaying it) and continuing with the next " script line. " " When a command triggering autocommands is executed by :silent! " inside a :try/:endtry, the autocommand execution is not suppressed " on error. " " This test reuses the function MSG() from the previous test. "------------------------------------------------------------------------------- XpathINIT XloopINIT! 1 4 let taken = "" function! S(n) abort XloopNEXT let g:taken = g:taken . "E" . a:n let v:errmsg = "" exec "asdf" . a:n " Check that ":silent!" continues: Xloop 1 " Check that ":silent!" sets "v:errmsg": if MSG('E492', "Not an editor command") Xloop 2 endif endfunction function! Foo() while 1 try try let caught = 0 " This is not silent: call S(3) " X: 0 * 16 catch /^Vim:/ let caught = 1 let errmsg3 = substitute(v:exception, '^Vim:', '', "") silent! call S(4) " X: 3 * 64 finally if !caught let errmsg3 = v:errmsg " Do call S(4) here if not executed in :catch. silent! call S(4) endif Xpath 1048576 " X: 1048576 if !caught && !$VIMNOERRTHROW Xpath 2097152 " X: 0 endif let v:errmsg = errmsg3 if !MSG('E492', "Not an editor command") Xpath 4194304 " X: 0 endif silent! call S(5) " X: 3 * 256 " Break out of try conditionals that cover ":silent!". This also " discards the aborting error when $VIMNOERRTHROW is non-zero. break endtry catch /.*/ Xpath 8388608 " X: 0 Xout v:exception "in" v:throwpoint endtry endwhile " This is a double ":silent!" (see caller). silent! call S(6) " X: 3 * 1024 endfunction function! Bar() try silent! call S(2) " X: 3 * 4 " X: 3 * 4096 silent! execute "call Foo() | call S(7)" silent! call S(8) " X: 3 * 16384 endtry " normal end of try cond that covers ":silent!" " This has a ":silent!" from the caller: call S(9) " X: 3 * 65536 endfunction silent! call S(1) " X: 3 * 1 silent! call Bar() silent! call S(10) " X: 3 * 262144 let expected = "E1E2E3E4E5E6E7E8E9E10" if taken != expected Xpath 16777216 " X: 0 Xout "'taken' is" taken "instead of" expected endif augroup TMP autocmd BufWritePost * Xpath 33554432 " X: 33554432 augroup END Xpath 67108864 " X: 67108864 write /i/m/p/o/s/s/i/b/l/e Xpath 134217728 " X: 134217728 autocmd! TMP unlet! caught errmsg3 taken expected delfunction S delfunction Foo delfunction Bar delfunction MSG Xcheck 236978127 "------------------------------------------------------------------------------- " Test 64: Error exceptions after error, interrupt or :throw {{{1 " " When an error occurs after an interrupt or a :throw but before " a matching :catch is reached, all following :catches of that try " block are ignored, but the error exception can be caught by the next " surrounding try conditional. Any previous error exception is " discarded. An error is ignored when there is a previous error that " has not been caught. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() while 1 try try Xpath 1 " X: 1 let caught = 0 while 1 " if 1 " Missing :endif endwhile " throw error exception catch /^Vim(/ let caught = 1 finally Xpath 2 " X: 2 if caught || $VIMNOERRTHROW Xpath 4 " X: 4 endif endtry catch /.*/ Xpath 8 " X: 0 Xout v:exception "in" v:throwpoint finally break " discard error for $VIMNOERRTHROW endtry endwhile while 1 try try Xpath 16 " X: 16 let caught = 0 try " if 1 " Missing :endif catch /.*/ " throw error exception Xpath 32 " X: 0 catch /.*/ Xpath 64 " X: 0 endtry catch /^Vim(/ let caught = 1 finally Xpath 128 " X: 128 if caught || $VIMNOERRTHROW Xpath 256 " X: 256 endif endtry catch /.*/ Xpath 512 " X: 0 Xout v:exception "in" v:throwpoint finally break " discard error for $VIMNOERRTHROW endtry endwhile while 1 try try let caught = 0 try Xpath 1024 " X: 1024 "INTERRUPT catch /do_not_catch/ Xpath 2048 " X: 0 " if 1 " Missing :endif catch /.*/ " throw error exception Xpath 4096 " X: 0 catch /.*/ Xpath 8192 " X: 0 endtry catch /^Vim(/ let caught = 1 finally Xpath 16384 " X: 16384 if caught || $VIMNOERRTHROW Xpath 32768 " X: 32768 endif endtry catch /.*/ Xpath 65536 " X: 0 Xout v:exception "in" v:throwpoint finally break " discard error for $VIMNOERRTHROW endtry endwhile while 1 try try let caught = 0 try Xpath 131072 " X: 131072 throw "x" catch /do_not_catch/ Xpath 262144 " X: 0 " if 1 " Missing :endif catch /x/ " throw error exception Xpath 524288 " X: 0 catch /.*/ Xpath 1048576 " X: 0 endtry catch /^Vim(/ let caught = 1 finally Xpath 2097152 " X: 2097152 if caught || $VIMNOERRTHROW Xpath 4194304 " X: 4194304 endif endtry catch /.*/ Xpath 8388608 " X: 0 Xout v:exception "in" v:throwpoint finally break " discard error for $VIMNOERRTHROW endtry endwhile while 1 try try let caught = 0 Xpath 16777216 " X: 16777216 " endif " :endif without :if; throw error exception " if 1 " Missing :endif catch /do_not_catch/ " ignore new error Xpath 33554432 " X: 0 catch /^Vim(endif):/ let caught = 1 catch /^Vim(/ Xpath 67108864 " X: 0 finally Xpath 134217728 " X: 134217728 if caught || $VIMNOERRTHROW Xpath 268435456 " X: 268435456 endif endtry catch /.*/ Xpath 536870912 " X: 0 Xout v:exception "in" v:throwpoint finally break " discard error for $VIMNOERRTHROW endtry endwhile Xpath 1073741824 " X: 1073741824 endif Xcheck 1499645335 "------------------------------------------------------------------------------- " Test 65: Errors in the /pattern/ argument of a :catch {{{1 " " On an error in the /pattern/ argument of a :catch, the :catch does " not match. Any following :catches of the same :try/:endtry don't " match either. Finally clauses are executed. "------------------------------------------------------------------------------- XpathINIT function! MSG(enr, emsg) let english = v:lang == "C" || v:lang =~ '^[Ee]n' if a:enr == "" Xout "TODO: Add message number for:" a:emsg let v:errmsg = ":" . v:errmsg endif let match = 1 if v:errmsg !~ '^'.a:enr.':' || (english && v:errmsg !~ a:emsg) let match = 0 if v:errmsg == "" Xout "Message missing." else let v:errmsg = escape(v:errmsg, '"') Xout "Unexpected message:" v:errmsg endif endif return match endfunction try try Xpath 1 " X: 1 throw "oops" catch /^oops$/ Xpath 2 " X: 2 catch /\)/ " not checked; exception has already been caught Xpath 4 " X: 0 endtry Xpath 8 " X: 8 catch /.*/ Xpath 16 " X: 0 Xout v:exception "in" v:throwpoint endtry function! F() try let caught = 0 try try Xpath 32 " X: 32 throw "ab" catch /abc/ " does not catch Xpath 64 " X: 0 catch /\)/ " error; discards exception Xpath 128 " X: 0 catch /.*/ " not checked Xpath 256 " X: 0 finally Xpath 512 " X: 512 endtry Xpath 1024 " X: 0 catch /^ab$/ " checked, but original exception is discarded Xpath 2048 " X: 0 catch /^Vim(catch):/ let caught = 1 let v:errmsg = substitute(v:exception, '^Vim(catch):', '', "") finally Xpath 4096 " X: 4096 if !caught && !$VIMNOERRTHROW Xpath 8192 " X: 0 endif if caught ? !MSG('E55', 'Unmatched \\)') \ : !MSG('E475', "Invalid argument") Xpath 16384 " X: 0 endif if !caught return | " discard error endif endtry catch /.*/ Xpath 32768 " X: 0 Xout v:exception "in" v:throwpoint endtry endfunction call F() Xpath 65536 " X: 65536 delfunction MSG delfunction F unlet! caught Xcheck 70187 "------------------------------------------------------------------------------- " Test 66: Stop range :call on error, interrupt, or :throw {{{1 " " When a function which is multiply called for a range since it " doesn't handle the range itself has an error in a command " dynamically enclosed by :try/:endtry or gets an interrupt or " executes a :throw, no more calls for the remaining lines in the " range are made. On an error in a command not dynamically enclosed " by :try/:endtry, the function is executed again for the remaining " lines in the range. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() let file = tempname() exec "edit" file insert line 1 line 2 line 3 . XloopINIT! 1 2 let taken = "" let expected = "G1EF1E(1)F1E(2)F1E(3)G2EF2E(1)G3IF3I(1)G4TF4T(1)G5AF5A(1)" function! F(reason, n) abort let g:taken = g:taken . "F" . a:n . \ substitute(a:reason, '\(\l\).*', '\u\1', "") . \ "(" . line(".") . ")" if a:reason == "error" asdf elseif a:reason == "interrupt" "INTERRUPT let dummy = 0 elseif a:reason == "throw" throw "xyz" elseif a:reason == "aborting error" XloopNEXT if g:taken != g:expected Xloop 1 " X: 0 Xout "'taken' is" g:taken "instead of" g:expected endif try bwipeout! call delete(file) asdf endtry endif endfunction function! G(reason, n) let g:taken = g:taken . "G" . a:n . \ substitute(a:reason, '\(\l\).*', '\u\1', "") 1,3call F(a:reason, a:n) endfunction Xpath 8 " X: 8 call G("error", 1) try Xpath 16 " X: 16 try call G("error", 2) Xpath 32 " X: 0 finally Xpath 64 " X: 64 try call G("interrupt", 3) Xpath 128 " X: 0 finally Xpath 256 " X: 256 try call G("throw", 4) Xpath 512 " X: 0 endtry endtry endtry catch /xyz/ Xpath 1024 " X: 1024 catch /.*/ Xpath 2048 " X: 0 Xout v:exception "in" ExtraVimThrowpoint() endtry Xpath 4096 " X: 4096 call G("aborting error", 5) Xpath 8192 " X: 0 Xout "'taken' is" taken "instead of" expected endif Xcheck 5464 "------------------------------------------------------------------------------- " Test 67: :throw across :call command {{{1 " " On a call command, an exception might be thrown when evaluating the " function name, during evaluation of the arguments, or when the " function is being executed. The exception can be caught by the " caller. "------------------------------------------------------------------------------- XpathINIT function! THROW(x, n) if a:n == 1 Xpath 1 " X: 1 elseif a:n == 2 Xpath 2 " X: 2 elseif a:n == 3 Xpath 4 " X: 4 endif throw a:x endfunction function! NAME(x, n) if a:n == 1 Xpath 8 " X: 0 elseif a:n == 2 Xpath 16 " X: 16 elseif a:n == 3 Xpath 32 " X: 32 elseif a:n == 4 Xpath 64 " X: 64 endif return a:x endfunction function! ARG(x, n) if a:n == 1 Xpath 128 " X: 0 elseif a:n == 2 Xpath 256 " X: 0 elseif a:n == 3 Xpath 512 " X: 512 elseif a:n == 4 Xpath 1024 " X: 1024 endif return a:x endfunction function! F(x, n) if a:n == 2 Xpath 2048 " X: 0 elseif a:n == 4 Xpath 4096 " X: 4096 endif endfunction while 1 try let error = 0 let v:errmsg = "" while 1 try Xpath 8192 " X: 8192 call {NAME(THROW("name", 1), 1)}(ARG(4711, 1), 1) Xpath 16384 " X: 0 catch /^name$/ Xpath 32768 " X: 32768 catch /.*/ let error = 1 Xout "1:" v:exception "in" v:throwpoint finally if !error && $VIMNOERRTHROW && v:errmsg != "" let error = 1 Xout "1:" v:errmsg endif if error Xpath 65536 " X: 0 endif let error = 0 let v:errmsg = "" break " discard error for $VIMNOERRTHROW endtry endwhile while 1 try Xpath 131072 " X: 131072 call {NAME("F", 2)}(ARG(THROW("arg", 2), 2), 2) Xpath 262144 " X: 0 catch /^arg$/ Xpath 524288 " X: 524288 catch /.*/ let error = 1 Xout "2:" v:exception "in" v:throwpoint finally if !error && $VIMNOERRTHROW && v:errmsg != "" let error = 1 Xout "2:" v:errmsg endif if error Xpath 1048576 " X: 0 endif let error = 0 let v:errmsg = "" break " discard error for $VIMNOERRTHROW endtry endwhile while 1 try Xpath 2097152 " X: 2097152 call {NAME("THROW", 3)}(ARG("call", 3), 3) Xpath 4194304 " X: 0 catch /^call$/ Xpath 8388608 " X: 8388608 catch /^0$/ " default return value Xpath 16777216 " X: 0 Xout "3:" v:throwpoint catch /.*/ let error = 1 Xout "3:" v:exception "in" v:throwpoint finally if !error && $VIMNOERRTHROW && v:errmsg != "" let error = 1 Xout "3:" v:errmsg endif if error Xpath 33554432 " X: 0 endif let error = 0 let v:errmsg = "" break " discard error for $VIMNOERRTHROW endtry endwhile while 1 try Xpath 67108864 " X: 67108864 call {NAME("F", 4)}(ARG(4711, 4), 4) Xpath 134217728 " X: 134217728 catch /.*/ let error = 1 Xout "4:" v:exception "in" v:throwpoint finally if !error && $VIMNOERRTHROW && v:errmsg != "" let error = 1 Xout "4:" v:errmsg endif if error Xpath 268435456 " X: 0 endif let error = 0 let v:errmsg = "" break " discard error for $VIMNOERRTHROW endtry endwhile catch /^0$/ " default return value Xpath 536870912 " X: 0 Xout v:throwpoint catch /.*/ let error = 1 Xout v:exception "in" v:throwpoint finally if !error && $VIMNOERRTHROW && v:errmsg != "" let error = 1 Xout v:errmsg endif if error Xpath 1073741824 " X: 0 endif break " discard error for $VIMNOERRTHROW endtry endwhile unlet error delfunction F Xcheck 212514423 " Leave THROW(), NAME(), and ARG() for the next test. "------------------------------------------------------------------------------- " Test 68: :throw across function calls in expressions {{{1 " " On a function call within an expression, an exception might be " thrown when evaluating the function name, during evaluation of the " arguments, or when the function is being executed. The exception " can be caught by the caller. " " This test reuses the functions THROW(), NAME(), and ARG() from the " previous test. "------------------------------------------------------------------------------- XpathINIT function! F(x, n) if a:n == 2 Xpath 2048 " X: 0 elseif a:n == 4 Xpath 4096 " X: 4096 endif return a:x endfunction unlet! var1 var2 var3 var4 while 1 try let error = 0 let v:errmsg = "" while 1 try Xpath 8192 " X: 8192 let var1 = {NAME(THROW("name", 1), 1)}(ARG(4711, 1), 1) Xpath 16384 " X: 0 catch /^name$/ Xpath 32768 " X: 32768 catch /.*/ let error = 1 Xout "1:" v:exception "in" v:throwpoint finally if !error && $VIMNOERRTHROW && v:errmsg != "" let error = 1 Xout "1:" v:errmsg endif if error Xpath 65536 " X: 0 endif let error = 0 let v:errmsg = "" break " discard error for $VIMNOERRTHROW endtry endwhile while 1 try Xpath 131072 " X: 131072 let var2 = {NAME("F", 2)}(ARG(THROW("arg", 2), 2), 2) Xpath 262144 " X: 0 catch /^arg$/ Xpath 524288 " X: 524288 catch /.*/ let error = 1 Xout "2:" v:exception "in" v:throwpoint finally if !error && $VIMNOERRTHROW && v:errmsg != "" let error = 1 Xout "2:" v:errmsg endif if error Xpath 1048576 " X: 0 endif let error = 0 let v:errmsg = "" break " discard error for $VIMNOERRTHROW endtry endwhile while 1 try Xpath 2097152 " X: 2097152 let var3 = {NAME("THROW", 3)}(ARG("call", 3), 3) Xpath 4194304 " X: 0 catch /^call$/ Xpath 8388608 " X: 8388608 catch /^0$/ " default return value Xpath 16777216 " X: 0 Xout "3:" v:throwpoint catch /.*/ let error = 1 Xout "3:" v:exception "in" v:throwpoint finally if !error && $VIMNOERRTHROW && v:errmsg != "" let error = 1 Xout "3:" v:errmsg endif if error Xpath 33554432 " X: 0 endif let error = 0 let v:errmsg = "" break " discard error for $VIMNOERRTHROW endtry endwhile while 1 try Xpath 67108864 " X: 67108864 let var4 = {NAME("F", 4)}(ARG(4711, 4), 4) Xpath 134217728 " X: 134217728 catch /.*/ let error = 1 Xout "4:" v:exception "in" v:throwpoint finally if !error && $VIMNOERRTHROW && v:errmsg != "" let error = 1 Xout "4:" v:errmsg endif if error Xpath 268435456 " X: 0 endif let error = 0 let v:errmsg = "" break " discard error for $VIMNOERRTHROW endtry endwhile catch /^0$/ " default return value Xpath 536870912 " X: 0 Xout v:throwpoint catch /.*/ let error = 1 Xout v:exception "in" v:throwpoint finally if !error && $VIMNOERRTHROW && v:errmsg != "" let error = 1 Xout v:errmsg endif if error Xpath 1073741824 " X: 0 endif break " discard error for $VIMNOERRTHROW endtry endwhile if exists("var1") || exists("var2") || exists("var3") || \ !exists("var4") || var4 != 4711 " The Xpath command does not accept 2^31 (negative); add explicitly: let Xpath = Xpath + 2147483648 " X: 0 if exists("var1") Xout "var1 =" var1 endif if exists("var2") Xout "var2 =" var2 endif if exists("var3") Xout "var3 =" var3 endif if !exists("var4") Xout "var4 unset" elseif var4 != 4711 Xout "var4 =" var4 endif endif unlet! error var1 var2 var3 var4 delfunction THROW delfunction NAME delfunction ARG delfunction F Xcheck 212514423 "------------------------------------------------------------------------------- " Test 69: :throw across :if, :elseif, :while {{{1 " " On an :if, :elseif, or :while command, an exception might be thrown " during evaluation of the expression to test. The exception can be " caught by the script. "------------------------------------------------------------------------------- XpathINIT XloopINIT! 1 2 function! THROW(x) XloopNEXT Xloop 1 " X: 1 + 2 + 4 throw a:x endfunction try try Xpath 8 " X: 8 if 4711 == THROW("if") + 111 Xpath 16 " X: 0 else Xpath 32 " X: 0 endif Xpath 64 " X: 0 catch /^if$/ Xpath 128 " X: 128 catch /.*/ Xpath 256 " X: 0 Xout "if:" v:exception "in" v:throwpoint endtry try Xpath 512 " X: 512 if 4711 == 4 + 7 + 1 + 1 Xpath 1024 " X: 0 elseif 4711 == THROW("elseif") + 222 Xpath 2048 " X: 0 else Xpath 4096 " X: 0 endif Xpath 8192 " X: 0 catch /^elseif$/ Xpath 16384 " X: 16384 catch /.*/ Xpath 32768 " X: 0 Xout "elseif:" v:exception "in" v:throwpoint endtry try Xpath 65536 " X: 65536 while 4711 == THROW("while") + 4711 Xpath 131072 " X: 0 break endwhile Xpath 262144 " X: 0 catch /^while$/ Xpath 524288 " X: 524288 catch /.*/ Xpath 1048576 " X: 0 Xout "while:" v:exception "in" v:throwpoint endtry catch /^0$/ " default return value Xpath 2097152 " X: 0 Xout v:throwpoint catch /.*/ Xout v:exception "in" v:throwpoint Xpath 4194304 " X: 0 endtry Xpath 8388608 " X: 8388608 delfunction THROW Xcheck 8995471 "------------------------------------------------------------------------------- " Test 70: :throw across :return or :throw {{{1 " " On a :return or :throw command, an exception might be thrown during " evaluation of the expression to return or throw, respectively. The " exception can be caught by the script. "------------------------------------------------------------------------------- XpathINIT let taken = "" function! THROW(x, n) let g:taken = g:taken . "T" . a:n throw a:x endfunction function! F(x, y, n) let g:taken = g:taken . "F" . a:n return a:x + THROW(a:y, a:n) endfunction function! G(x, y, n) let g:taken = g:taken . "G" . a:n throw a:x . THROW(a:y, a:n) return a:x endfunction try try Xpath 1 " X: 1 call F(4711, "return", 1) Xpath 2 " X: 0 catch /^return$/ Xpath 4 " X: 4 catch /.*/ Xpath 8 " X: 0 Xout "return:" v:exception "in" v:throwpoint endtry try Xpath 16 " X: 16 let var = F(4712, "return-var", 2) Xpath 32 " X: 0 catch /^return-var$/ Xpath 64 " X: 64 catch /.*/ Xpath 128 " X: 0 Xout "return-var:" v:exception "in" v:throwpoint finally unlet! var endtry try Xpath 256 " X: 256 throw "except1" . THROW("throw1", 3) Xpath 512 " X: 0 catch /^except1/ Xpath 1024 " X: 0 catch /^throw1$/ Xpath 2048 " X: 2048 catch /.*/ Xpath 4096 " X: 0 Xout "throw1:" v:exception "in" v:throwpoint endtry try Xpath 8192 " X: 8192 call G("except2", "throw2", 4) Xpath 16384 " X: 0 catch /^except2/ Xpath 32768 " X: 0 catch /^throw2$/ Xpath 65536 " X: 65536 catch /.*/ Xpath 131072 " X: 0 Xout "throw2:" v:exception "in" v:throwpoint endtry try Xpath 262144 " X: 262144 let var = G("except3", "throw3", 5) Xpath 524288 " X: 0 catch /^except3/ Xpath 1048576 " X: 0 catch /^throw3$/ Xpath 2097152 " X: 2097152 catch /.*/ Xpath 4194304 " X: 0 Xout "throw3:" v:exception "in" v:throwpoint finally unlet! var endtry let expected = "F1T1F2T2T3G4T4G5T5" if taken != expected Xpath 8388608 " X: 0 Xout "'taken' is" taken "instead of" expected endif catch /^0$/ " default return value Xpath 16777216 " X: 0 Xout v:throwpoint catch /.*/ Xpath 33554432 " X: 0 Xout v:exception "in" v:throwpoint endtry Xpath 67108864 " X: 67108864 unlet taken expected delfunction THROW delfunction F delfunction G Xcheck 69544277 "------------------------------------------------------------------------------- " Test 71: :throw across :echo variants and :execute {{{1 " " On an :echo, :echon, :echomsg, :echoerr, or :execute command, an " exception might be thrown during evaluation of the arguments to " be displayed or executed as a command, respectively. Any following " arguments are not evaluated, then. The exception can be caught by " the script. "------------------------------------------------------------------------------- XpathINIT let taken = "" function! THROW(x, n) let g:taken = g:taken . "T" . a:n throw a:x endfunction function! F(n) let g:taken = g:taken . "F" . a:n return "F" . a:n endfunction try try Xpath 1 " X: 1 echo "echo" . THROW("echo-except", 1) F(1) Xpath 2 " X: 0 catch /^echo-except$/ Xpath 4 " X: 4 catch /.*/ Xpath 8 " X: 0 Xout "echo:" v:exception "in" v:throwpoint endtry try Xpath 16 " X: 16 echon "echon" . THROW("echon-except", 2) F(2) Xpath 32 " X: 0 catch /^echon-except$/ Xpath 64 " X: 64 catch /.*/ Xpath 128 " X: 0 Xout "echon:" v:exception "in" v:throwpoint endtry try Xpath 256 " X: 256 echomsg "echomsg" . THROW("echomsg-except", 3) F(3) Xpath 512 " X: 0 catch /^echomsg-except$/ Xpath 1024 " X: 1024 catch /.*/ Xpath 2048 " X: 0 Xout "echomsg:" v:exception "in" v:throwpoint endtry try Xpath 4096 " X: 4096 echoerr "echoerr" . THROW("echoerr-except", 4) F(4) Xpath 8192 " X: 0 catch /^echoerr-except$/ Xpath 16384 " X: 16384 catch /Vim/ Xpath 32768 " X: 0 catch /echoerr/ Xpath 65536 " X: 0 catch /.*/ Xpath 131072 " X: 0 Xout "echoerr:" v:exception "in" v:throwpoint endtry try Xpath 262144 " X: 262144 execute "echo 'execute" . THROW("execute-except", 5) F(5) "'" Xpath 524288 " X: 0 catch /^execute-except$/ Xpath 1048576 " X: 1048576 catch /.*/ Xpath 2097152 " X: 0 Xout "execute:" v:exception "in" v:throwpoint endtry let expected = "T1T2T3T4T5" if taken != expected Xpath 4194304 " X: 0 Xout "'taken' is" taken "instead of" expected endif catch /^0$/ " default return value Xpath 8388608 " X: 0 Xout v:throwpoint catch /.*/ Xpath 16777216 " X: 0 Xout v:exception "in" v:throwpoint endtry Xpath 33554432 " X: 33554432 unlet taken expected delfunction THROW delfunction F Xcheck 34886997 "------------------------------------------------------------------------------- " Test 72: :throw across :let or :unlet {{{1 " " On a :let command, an exception might be thrown during evaluation " of the expression to assign. On an :let or :unlet command, the " evaluation of the name of the variable to be assigned or list or " deleted, respectively, may throw an exception. Any following " arguments are not evaluated, then. The exception can be caught by " the script. "------------------------------------------------------------------------------- XpathINIT let throwcount = 0 function! THROW(x) let g:throwcount = g:throwcount + 1 throw a:x endfunction try try let $VAR = "old_value" Xpath 1 " X: 1 let $VAR = "let(" . THROW("var") . ")" Xpath 2 " X: 0 catch /^var$/ Xpath 4 " X: 4 finally if $VAR != "old_value" Xpath 8 " X: 0 endif endtry try let @a = "old_value" Xpath 16 " X: 16 let @a = "let(" . THROW("reg") . ")" Xpath 32 " X: 0 catch /^reg$/ try Xpath 64 " X: 64 let @A = "let(" . THROW("REG") . ")" Xpath 128 " X: 0 catch /^REG$/ Xpath 256 " X: 256 endtry finally if @a != "old_value" Xpath 512 " X: 0 endif if @A != "old_value" Xpath 1024 " X: 0 endif endtry try let saved_gpath = &g:path let saved_lpath = &l:path Xpath 2048 " X: 2048 let &path = "let(" . THROW("opt") . ")" Xpath 4096 " X: 0 catch /^opt$/ try Xpath 8192 " X: 8192 let &g:path = "let(" . THROW("gopt") . ")" Xpath 16384 " X: 0 catch /^gopt$/ try Xpath 32768 " X: 32768 let &l:path = "let(" . THROW("lopt") . ")" Xpath 65536 " X: 0 catch /^lopt$/ Xpath 131072 " X: 131072 endtry endtry finally if &g:path != saved_gpath || &l:path != saved_lpath Xpath 262144 " X: 0 endif let &g:path = saved_gpath let &l:path = saved_lpath endtry unlet! var1 var2 var3 try Xpath 524288 " X: 524288 let var1 = "let(" . THROW("var1") . ")" Xpath 1048576 " X: 0 catch /^var1$/ Xpath 2097152 " X: 2097152 finally if exists("var1") Xpath 4194304 " X: 0 endif endtry try let var2 = "old_value" Xpath 8388608 " X: 8388608 let var2 = "let(" . THROW("var2"). ")" Xpath 16777216 " X: 0 catch /^var2$/ Xpath 33554432 " X: 33554432 finally if var2 != "old_value" Xpath 67108864 " X: 0 endif endtry try Xpath 134217728 " X: 134217728 let var{THROW("var3")} = 4711 Xpath 268435456 " X: 0 catch /^var3$/ Xpath 536870912 " X: 536870912 endtry let addpath = "" function ADDPATH(p) let g:addpath = g:addpath . a:p endfunction try call ADDPATH("T1") let var{THROW("var4")} var{ADDPATH("T2")} | call ADDPATH("T3") call ADDPATH("T4") catch /^var4$/ call ADDPATH("T5") endtry try call ADDPATH("T6") unlet var{THROW("var5")} var{ADDPATH("T7")} | call ADDPATH("T8") call ADDPATH("T9") catch /^var5$/ call ADDPATH("T10") endtry if addpath != "T1T5T6T10" || throwcount != 11 throw "addpath: " . addpath . ", throwcount: " . throwcount endif Xpath 1073741824 " X: 1073741824 catch /.*/ " The Xpath command does not accept 2^31 (negative); add explicitly: let Xpath = Xpath + 2147483648 " X: 0 Xout v:exception "in" v:throwpoint endtry unlet! var1 var2 var3 addpath throwcount delfunction THROW Xcheck 1789569365 "------------------------------------------------------------------------------- " Test 73: :throw across :function, :delfunction {{{1 " " The :function and :delfunction commands may cause an expression " specified in braces to be evaluated. During evaluation, an " exception might be thrown. The exception can be caught by the " script. "------------------------------------------------------------------------------- XpathINIT let taken = "" function! THROW(x, n) let g:taken = g:taken . "T" . a:n throw a:x endfunction function! EXPR(x, n) let g:taken = g:taken . "E" . a:n if a:n % 2 == 0 call THROW(a:x, a:n) endif return 2 - a:n % 2 endfunction try try " Define function. Xpath 1 " X: 1 function! F0() endfunction Xpath 2 " X: 2 function! F{EXPR("function-def-ok", 1)}() endfunction Xpath 4 " X: 4 function! F{EXPR("function-def", 2)}() endfunction Xpath 8 " X: 0 catch /^function-def-ok$/ Xpath 16 " X: 0 catch /^function-def$/ Xpath 32 " X: 32 catch /.*/ Xpath 64 " X: 0 Xout "def:" v:exception "in" v:throwpoint endtry try " List function. Xpath 128 " X: 128 function F0 Xpath 256 " X: 256 function F{EXPR("function-lst-ok", 3)} Xpath 512 " X: 512 function F{EXPR("function-lst", 4)} Xpath 1024 " X: 0 catch /^function-lst-ok$/ Xpath 2048 " X: 0 catch /^function-lst$/ Xpath 4096 " X: 4096 catch /.*/ Xpath 8192 " X: 0 Xout "lst:" v:exception "in" v:throwpoint endtry try " Delete function Xpath 16384 " X: 16384 delfunction F0 Xpath 32768 " X: 32768 delfunction F{EXPR("function-del-ok", 5)} Xpath 65536 " X: 65536 delfunction F{EXPR("function-del", 6)} Xpath 131072 " X: 0 catch /^function-del-ok$/ Xpath 262144 " X: 0 catch /^function-del$/ Xpath 524288 " X: 524288 catch /.*/ Xpath 1048576 " X: 0 Xout "del:" v:exception "in" v:throwpoint endtry let expected = "E1E2T2E3E4T4E5E6T6" if taken != expected Xpath 2097152 " X: 0 Xout "'taken' is" taken "instead of" expected endif catch /.*/ Xpath 4194304 " X: 0 Xout v:exception "in" v:throwpoint endtry Xpath 8388608 " X: 8388608 unlet taken expected delfunction THROW delfunction EXPR Xcheck 9032615 "------------------------------------------------------------------------------- " Test 74: :throw across builtin functions and commands {{{1 " " Some functions like exists(), searchpair() take expression " arguments, other functions or commands like substitute() or " :substitute cause an expression (specified in the regular " expression) to be evaluated. During evaluation an exception " might be thrown. The exception can be caught by the script. "------------------------------------------------------------------------------- XpathINIT let taken = "" function! THROW(x, n) let g:taken = g:taken . "T" . a:n throw a:x endfunction function! EXPR(x, n) let g:taken = g:taken . "E" . a:n call THROW(a:x . a:n, a:n) return "EXPR" endfunction function! SKIP(x, n) let g:taken = g:taken . "S" . a:n . "(" . line(".") let theline = getline(".") if theline =~ "skip" let g:taken = g:taken . "s)" return 1 elseif theline =~ "throw" let g:taken = g:taken . "t)" call THROW(a:x . a:n, a:n) else let g:taken = g:taken . ")" return 0 endif endfunction function! SUBST(x, n) let g:taken = g:taken . "U" . a:n . "(" . line(".") let theline = getline(".") if theline =~ "not" " SUBST() should not be called for this line let g:taken = g:taken . "n)" call THROW(a:x . a:n, a:n) elseif theline =~ "throw" let g:taken = g:taken . "t)" call THROW(a:x . a:n, a:n) else let g:taken = g:taken . ")" return "replaced" endif endfunction try try Xpath 1 " X: 1 let result = exists('*{EXPR("exists", 1)}') Xpath 2 " X: 0 catch /^exists1$/ Xpath 4 " X: 4 try let result = exists('{EXPR("exists", 2)}') Xpath 8 " X: 0 catch /^exists2$/ Xpath 16 " X: 16 catch /.*/ Xpath 32 " X: 0 Xout "exists2:" v:exception "in" v:throwpoint endtry catch /.*/ Xpath 64 " X: 0 Xout "exists1:" v:exception "in" v:throwpoint endtry try let file = tempname() exec "edit" file insert begin xx middle 3 xx middle 5 skip xx middle 7 throw xx end . normal! gg Xpath 128 " X: 128 let result = \ searchpair("begin", "middle", "end", '', 'SKIP("searchpair", 3)') Xpath 256 " X: 256 let result = \ searchpair("begin", "middle", "end", '', 'SKIP("searchpair", 4)') Xpath 512 " X: 0 let result = \ searchpair("begin", "middle", "end", '', 'SKIP("searchpair", 5)') Xpath 1024 " X: 0 catch /^searchpair[35]$/ Xpath 2048 " X: 0 catch /^searchpair4$/ Xpath 4096 " X: 4096 catch /.*/ Xpath 8192 " X: 0 Xout "searchpair:" v:exception "in" v:throwpoint finally bwipeout! call delete(file) endtry try let file = tempname() exec "edit" file insert subst 1 subst 2 not subst 4 subst throw subst 6 . normal! gg Xpath 16384 " X: 16384 1,2substitute/subst/\=SUBST("substitute", 6)/ try Xpath 32768 " X: 32768 try let v:errmsg = "" 3substitute/subst/\=SUBST("substitute", 7)/ finally if v:errmsg != "" " If exceptions are not thrown on errors, fake the error " exception in order to get the same execution path. throw "faked Vim(substitute)" endif endtry catch /Vim(substitute)/ " Pattern not found ('e' flag missing) Xpath 65536 " X: 65536 3substitute/subst/\=SUBST("substitute", 8)/e Xpath 131072 " X: 131072 endtry Xpath 262144 " X: 262144 4,6substitute/subst/\=SUBST("substitute", 9)/ Xpath 524288 " X: 0 catch /^substitute[678]/ Xpath 1048576 " X: 0 catch /^substitute9/ Xpath 2097152 " X: 2097152 finally bwipeout! call delete(file) endtry try Xpath 4194304 " X: 4194304 let var = substitute("sub", "sub", '\=THROW("substitute()y", 10)', '') Xpath 8388608 " X: 0 catch /substitute()y/ Xpath 16777216 " X: 16777216 catch /.*/ Xpath 33554432 " X: 0 Xout "substitute()y:" v:exception "in" v:throwpoint endtry try Xpath 67108864 " X: 67108864 let var = substitute("not", "sub", '\=THROW("substitute()n", 11)', '') Xpath 134217728 " X: 134217728 catch /substitute()n/ Xpath 268435456 " X: 0 catch /.*/ Xpath 536870912 " X: 0 Xout "substitute()n:" v:exception "in" v:throwpoint endtry let expected = "E1T1E2T2S3(3)S4(5s)S4(7t)T4U6(1)U6(2)U9(4)U9(5t)T9T10" if taken != expected Xpath 1073741824 " X: 0 Xout "'taken' is" taken "instead of" expected endif catch /.*/ " The Xpath command does not accept 2^31 (negative); add explicitly: let Xpath = Xpath + 2147483648 " X: 0 Xout v:exception "in" v:throwpoint endtry unlet result var taken expected delfunction THROW delfunction EXPR delfunction SKIP delfunction SUBST Xcheck 224907669 "------------------------------------------------------------------------------- " Test 75: Errors in builtin functions. {{{1 " " On an error in a builtin function called inside a :try/:endtry " region, the evaluation of the expression calling that function and " the command containing that expression are abandoned. The error can " be caught as an exception. " " A simple :call of the builtin function is a trivial case. If the " builtin function is called in the argument list of another function, " no further arguments are evaluated, and the other function is not " executed. If the builtin function is called from the argument of " a :return command, the :return command is not executed. If the " builtin function is called from the argument of a :throw command, " the :throw command is not executed. The evaluation of the " expression calling the builtin function is abandoned. "------------------------------------------------------------------------------- XpathINIT function! F1(arg1) Xpath 1 " X: 0 endfunction function! F2(arg1, arg2) Xpath 2 " X: 0 endfunction function! G() Xpath 4 " X: 0 endfunction function! H() Xpath 8 " X: 0 endfunction function! R() while 1 try let caught = 0 let v:errmsg = "" Xpath 16 " X: 16 return append(1, "s") catch /E21/ let caught = 1 catch /.*/ Xpath 32 " X: 0 finally Xpath 64 " X: 64 if caught || $VIMNOERRTHROW && v:errmsg =~ 'E21' Xpath 128 " X: 128 endif break " discard error for $VIMNOERRTHROW endtry endwhile Xpath 256 " X: 256 endfunction try set noma " let append() fail with "E21" while 1 try let caught = 0 let v:errmsg = "" Xpath 512 " X: 512 call append(1, "s") catch /E21/ let caught = 1 catch /.*/ Xpath 1024 " X: 0 finally Xpath 2048 " X: 2048 if caught || $VIMNOERRTHROW && v:errmsg =~ 'E21' Xpath 4096 " X: 4096 endif break " discard error for $VIMNOERRTHROW endtry endwhile while 1 try let caught = 0 let v:errmsg = "" Xpath 8192 " X: 8192 call F1('x' . append(1, "s")) catch /E21/ let caught = 1 catch /.*/ Xpath 16384 " X: 0 finally Xpath 32768 " X: 32768 if caught || $VIMNOERRTHROW && v:errmsg =~ 'E21' Xpath 65536 " X: 65536 endif break " discard error for $VIMNOERRTHROW endtry endwhile while 1 try let caught = 0 let v:errmsg = "" Xpath 131072 " X: 131072 call F2('x' . append(1, "s"), G()) catch /E21/ let caught = 1 catch /.*/ Xpath 262144 " X: 0 finally Xpath 524288 " X: 524288 if caught || $VIMNOERRTHROW && v:errmsg =~ 'E21' Xpath 1048576 " X: 1048576 endif break " discard error for $VIMNOERRTHROW endtry endwhile call R() while 1 try let caught = 0 let v:errmsg = "" Xpath 2097152 " X: 2097152 throw "T" . append(1, "s") catch /E21/ let caught = 1 catch /^T.*/ Xpath 4194304 " X: 0 catch /.*/ Xpath 8388608 " X: 0 finally Xpath 16777216 " X: 16777216 if caught || $VIMNOERRTHROW && v:errmsg =~ 'E21' Xpath 33554432 " X: 33554432 endif break " discard error for $VIMNOERRTHROW endtry endwhile while 1 try let caught = 0 let v:errmsg = "" Xpath 67108864 " X: 67108864 let x = "a" let x = x . "b" . append(1, "s") . H() catch /E21/ let caught = 1 catch /.*/ Xpath 134217728 " X: 0 finally Xpath 268435456 " X: 268435456 if caught || $VIMNOERRTHROW && v:errmsg =~ 'E21' Xpath 536870912 " X: 536870912 endif if x == "a" Xpath 1073741824 " X: 1073741824 endif break " discard error for $VIMNOERRTHROW endtry endwhile catch /.*/ " The Xpath command does not accept 2^31 (negative); add explicitly: let Xpath = Xpath + 2147483648 " X: 0 Xout v:exception "in" v:throwpoint finally set ma& endtry unlet! caught x delfunction F1 delfunction F2 delfunction G delfunction H delfunction R Xcheck 2000403408 "------------------------------------------------------------------------------- " Test 76: Errors, interrupts, :throw during expression evaluation {{{1 " " When a function call made during expression evaluation is aborted " due to an error inside a :try/:endtry region or due to an interrupt " or a :throw, the expression evaluation is aborted as well. No " message is displayed for the cancelled expression evaluation. On an " error not inside :try/:endtry, the expression evaluation continues. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() let taken = "" function! ERR(n) let g:taken = g:taken . "E" . a:n asdf endfunction function! ERRabort(n) abort let g:taken = g:taken . "A" . a:n asdf endfunction " returns -1; may cause follow-up msg for illegal var/func name function! WRAP(n, arg) let g:taken = g:taken . "W" . a:n let g:saved_errmsg = v:errmsg return arg endfunction function! INT(n) let g:taken = g:taken . "I" . a:n "INTERRUPT9 let dummy = 0 endfunction function! THR(n) let g:taken = g:taken . "T" . a:n throw "should not be caught" endfunction function! CONT(n) let g:taken = g:taken . "C" . a:n endfunction function! MSG(n) let g:taken = g:taken . "M" . a:n let errmsg = (a:n >= 37 && a:n <= 44) ? g:saved_errmsg : v:errmsg let msgptn = (a:n >= 10 && a:n <= 27) ? "^$" : "asdf" if errmsg !~ msgptn let g:taken = g:taken . "x" Xout "Expr" a:n.": Unexpected message:" v:errmsg endif let v:errmsg = "" let g:saved_errmsg = "" endfunction let v:errmsg = "" try let t = 1 XloopINIT 1 2 while t <= 9 Xloop 1 " X: 511 try if t == 1 let v{ERR(t) + CONT(t)} = 0 elseif t == 2 let v{ERR(t) + CONT(t)} elseif t == 3 let var = exists('v{ERR(t) + CONT(t)}') elseif t == 4 unlet v{ERR(t) + CONT(t)} elseif t == 5 function F{ERR(t) + CONT(t)}() endfunction elseif t == 6 function F{ERR(t) + CONT(t)} elseif t == 7 let var = exists('*F{ERR(t) + CONT(t)}') elseif t == 8 delfunction F{ERR(t) + CONT(t)} elseif t == 9 let var = ERR(t) + CONT(t) endif catch /asdf/ " v:errmsg is not set when the error message is converted to an " exception. Set it to the original error message. let v:errmsg = substitute(v:exception, '^Vim:', '', "") catch /^Vim\((\a\+)\)\=:/ " An error exception has been thrown after the original error. let v:errmsg = "" finally call MSG(t) let t = t + 1 XloopNEXT continue " discard an aborting error endtry endwhile catch /.*/ Xpath 512 " X: 0 Xout v:exception "in" ExtraVimThrowpoint() endtry try let t = 10 XloopINIT 1024 2 while t <= 18 Xloop 1 " X: 1024 * 511 try if t == 10 let v{INT(t) + CONT(t)} = 0 elseif t == 11 let v{INT(t) + CONT(t)} elseif t == 12 let var = exists('v{INT(t) + CONT(t)}') elseif t == 13 unlet v{INT(t) + CONT(t)} elseif t == 14 function F{INT(t) + CONT(t)}() endfunction elseif t == 15 function F{INT(t) + CONT(t)} elseif t == 16 let var = exists('*F{INT(t) + CONT(t)}') elseif t == 17 delfunction F{INT(t) + CONT(t)} elseif t == 18 let var = INT(t) + CONT(t) endif catch /^Vim\((\a\+)\)\=:\(Interrupt\)\@!/ " An error exception has been triggered after the interrupt. let v:errmsg = substitute(v:exception, \ '^Vim\((\a\+)\)\=:', '', "") finally call MSG(t) let t = t + 1 XloopNEXT continue " discard interrupt endtry endwhile catch /.*/ Xpath 524288 " X: 0 Xout v:exception "in" ExtraVimThrowpoint() endtry try let t = 19 XloopINIT 1048576 2 while t <= 27 Xloop 1 " X: 1048576 * 511 try if t == 19 let v{THR(t) + CONT(t)} = 0 elseif t == 20 let v{THR(t) + CONT(t)} elseif t == 21 let var = exists('v{THR(t) + CONT(t)}') elseif t == 22 unlet v{THR(t) + CONT(t)} elseif t == 23 function F{THR(t) + CONT(t)}() endfunction elseif t == 24 function F{THR(t) + CONT(t)} elseif t == 25 let var = exists('*F{THR(t) + CONT(t)}') elseif t == 26 delfunction F{THR(t) + CONT(t)} elseif t == 27 let var = THR(t) + CONT(t) endif catch /^Vim\((\a\+)\)\=:/ " An error exception has been triggered after the :throw. let v:errmsg = substitute(v:exception, \ '^Vim\((\a\+)\)\=:', '', "") finally call MSG(t) let t = t + 1 XloopNEXT continue " discard exception endtry endwhile catch /.*/ Xpath 536870912 " X: 0 Xout v:exception "in" ExtraVimThrowpoint() endtry let v{ERR(28) + CONT(28)} = 0 call MSG(28) let v{ERR(29) + CONT(29)} call MSG(29) let var = exists('v{ERR(30) + CONT(30)}') call MSG(30) unlet v{ERR(31) + CONT(31)} call MSG(31) function F{ERR(32) + CONT(32)}() endfunction call MSG(32) function F{ERR(33) + CONT(33)} call MSG(33) let var = exists('*F{ERR(34) + CONT(34)}') call MSG(34) delfunction F{ERR(35) + CONT(35)} call MSG(35) let var = ERR(36) + CONT(36) call MSG(36) let saved_errmsg = "" let v{WRAP(37, ERRabort(37)) + CONT(37)} = 0 call MSG(37) let v{WRAP(38, ERRabort(38)) + CONT(38)} call MSG(38) let var = exists('v{WRAP(39, ERRabort(39)) + CONT(39)}') call MSG(39) unlet v{WRAP(40, ERRabort(40)) + CONT(40)} call MSG(40) function F{WRAP(41, ERRabort(41)) + CONT(41)}() endfunction call MSG(41) function F{WRAP(42, ERRabort(42)) + CONT(42)} call MSG(42) let var = exists('*F{WRAP(43, ERRabort(43)) + CONT(43)}') call MSG(43) delfunction F{WRAP(44, ERRabort(44)) + CONT(44)} call MSG(44) let var = ERRabort(45) + CONT(45) call MSG(45) Xpath 1073741824 " X: 1073741824 let expected = "" \ . "E1M1E2M2E3M3E4M4E5M5E6M6E7M7E8M8E9M9" \ . "I10M10I11M11I12M12I13M13I14M14I15M15I16M16I17M17I18M18" \ . "T19M19T20M20T21M21T22M22T23M23T24M24T25M25T26M26T27M27" \ . "E28C28M28E29C29M29E30C30M30E31C31M31E32C32M32E33C33M33" \ . "E34C34M34E35C35M35E36C36M36" \ . "A37W37C37M37A38W38C38M38A39W39C39M39A40W40C40M40A41W41C41M41" \ . "A42W42C42M42A43W43C43M43A44W44C44M44A45C45M45" if taken != expected " The Xpath command does not accept 2^31 (negative); display explicitly: exec "!echo 2147483648 >>" . g:ExtraVimResult " X: 0 Xout "'taken' is" taken "instead of" expected if substitute(taken, \ '\(.*\)E3C3M3x\(.*\)E30C30M30x\(.*\)A39C39M39x\(.*\)', \ '\1E3M3\2E30C30M30\3A39C39M39\4', \ "") == expected Xout "Is ++emsg_skip for var with expr_start non-NULL" \ "in f_exists ok?" endif endif unlet! v var saved_errmsg taken expected call delete(WA_t5) call delete(WA_t14) call delete(WA_t23) unlet! WA_t5 WA_t14 WA_t23 delfunction WA_t5 delfunction WA_t14 delfunction WA_t23 endif Xcheck 1610087935 "------------------------------------------------------------------------------- " Test 77: Errors, interrupts, :throw in name{brace-expression} {{{1 " " When a function call made during evaluation of an expression in " braces as part of a function name after ":function" is aborted due " to an error inside a :try/:endtry region or due to an interrupt or " a :throw, the expression evaluation is aborted as well, and the " function definition is ignored, skipping all commands to the " ":endfunction". On an error not inside :try/:endtry, the expression " evaluation continues and the function gets defined, and can be " called and deleted. "------------------------------------------------------------------------------- XpathINIT XloopINIT 1 4 function! ERR() abort Xloop 1 " X: 1 + 4 + 16 + 64 asdf endfunction " returns -1 function! OK() Xloop 2 " X: 2 * (1 + 4 + 16) let v:errmsg = "" return 0 endfunction let v:errmsg = "" Xpath 4096 " X: 4096 function! F{1 + ERR() + OK()}(arg) " F0 should be defined. if exists("a:arg") && a:arg == "calling" Xpath 8192 " X: 8192 else Xpath 16384 " X: 0 endif endfunction if v:errmsg != "" Xpath 32768 " X: 0 endif XloopNEXT Xpath 65536 " X: 65536 call F{1 + ERR() + OK()}("calling") if v:errmsg != "" Xpath 131072 " X: 0 endif XloopNEXT Xpath 262144 " X: 262144 delfunction F{1 + ERR() + OK()} if v:errmsg != "" Xpath 524288 " X: 0 endif XloopNEXT try while 1 let caught = 0 try Xpath 1048576 " X: 1048576 function! G{1 + ERR() + OK()}(arg) " G0 should not be defined, and the function body should be " skipped. if exists("a:arg") && a:arg == "calling" Xpath 2097152 " X: 0 else Xpath 4194304 " X: 0 endif " Use an unmatched ":finally" to check whether the body is " skipped when an error occurs in ERR(). This works whether or " not the exception is converted to an exception. finally Xpath 8388608 " X: 0 Xout "Body of G{1 + ERR() + OK()}() not skipped" " Discard the aborting error or exception, and break the " while loop. break " End the try conditional and start a new one to avoid " ":catch after :finally" errors. endtry try Xpath 16777216 " X: 0 endfunction " When the function was not defined, this won't be reached - whether " the body was skipped or not. When the function was defined, it " can be called and deleted here. Xpath 33554432 " X: 0 Xout "G0() has been defined" XloopNEXT try call G{1 + ERR() + OK()}("calling") catch /.*/ Xpath 67108864 " X: 0 endtry Xpath 134217728 " X: 0 XloopNEXT try delfunction G{1 + ERR() + OK()} catch /.*/ Xpath 268435456 " X: 0 endtry catch /asdf/ " Jumped to when the function is not defined and the body is " skipped. let caught = 1 catch /.*/ Xpath 536870912 " X: 0 finally if !caught && !$VIMNOERRTHROW Xpath 1073741824 " X: 0 endif break " discard error for $VIMNOERRTHROW endtry " jumped to when the body is not skipped endwhile catch /.*/ " The Xpath command does not accept 2^31 (negative); add explicitly: let Xpath = Xpath + 2147483648 " X: 0 Xout "Body of G{1 + ERR() + OK()}() not skipped, exception caught" Xout v:exception "in" v:throwpoint endtry Xcheck 1388671 "------------------------------------------------------------------------------- " Test 78: Messages on parsing errors in expression evaluation {{{1 " " When an expression evaluation detects a parsing error, an error " message is given and converted to an exception, and the expression " evaluation is aborted. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() let taken = "" function! F(n) let g:taken = g:taken . "F" . a:n endfunction function! MSG(n, enr, emsg) let g:taken = g:taken . "M" . a:n let english = v:lang == "C" || v:lang =~ '^[Ee]n' if a:enr == "" Xout "TODO: Add message number for:" a:emsg let v:errmsg = ":" . v:errmsg endif if v:errmsg !~ '^'.a:enr.':' || (english && v:errmsg !~ a:emsg) if v:errmsg == "" Xout "Expr" a:n.": Message missing." let g:taken = g:taken . "x" else let v:errmsg = escape(v:errmsg, '"') Xout "Expr" a:n.": Unexpected message:" v:errmsg Xout "Expected: " . a:enr . ': ' . a:emsg let g:taken = g:taken . "X" endif endif endfunction function! CONT(n) let g:taken = g:taken . "C" . a:n endfunction let v:errmsg = "" XloopINIT 1 2 try let t = 1 while t <= 14 let g:taken = g:taken . "T" . t let v:errmsg = "" try let caught = 0 if t == 1 let v{novar + CONT(t)} = 0 elseif t == 2 let v{novar + CONT(t)} elseif t == 3 let var = exists('v{novar + CONT(t)}') elseif t == 4 unlet v{novar + CONT(t)} elseif t == 5 function F{novar + CONT(t)}() endfunction elseif t == 6 function F{novar + CONT(t)} elseif t == 7 let var = exists('*F{novar + CONT(t)}') elseif t == 8 delfunction F{novar + CONT(t)} elseif t == 9 echo novar + CONT(t) elseif t == 10 echo v{novar + CONT(t)} elseif t == 11 echo F{novar + CONT(t)} elseif t == 12 let var = novar + CONT(t) elseif t == 13 let var = v{novar + CONT(t)} elseif t == 14 let var = F{novar + CONT(t)}() endif catch /^Vim\((\a\+)\)\=:/ " v:errmsg is not set when the error message is converted to an " exception. Set it to the original error message. let v:errmsg = substitute(v:exception, \ '^Vim\((\a\+)\)\=:', '', "") let caught = 1 finally if t <= 8 && t != 3 && t != 7 call MSG(t, 'E475', 'Invalid argument\>') else if !caught " no error exceptions ($VIMNOERRTHROW set) call MSG(t, 'E15', "Invalid expression") else call MSG(t, 'E121', "Undefined variable") endif endif let t = t + 1 XloopNEXT continue " discard an aborting error endtry endwhile catch /.*/ Xloop 1 " X: 0 Xout t.":" v:exception "in" ExtraVimThrowpoint() endtry function! T(n, expr, enr, emsg) try let g:taken = g:taken . "T" . a:n let v:errmsg = "" try let caught = 0 execute "let var = " . a:expr catch /^Vim\((\a\+)\)\=:/ " v:errmsg is not set when the error message is converted to an " exception. Set it to the original error message. let v:errmsg = substitute(v:exception, \ '^Vim\((\a\+)\)\=:', '', "") let caught = 1 finally if !caught " no error exceptions ($VIMNOERRTHROW set) call MSG(a:n, 'E15', "Invalid expression") else call MSG(a:n, a:enr, a:emsg) endif XloopNEXT " Discard an aborting error: return endtry catch /.*/ Xloop 1 " X: 0 Xout a:n.":" v:exception "in" ExtraVimThrowpoint() endtry endfunction call T(15, 'Nofunc() + CONT(15)', 'E117', "Unknown function") call T(16, 'F(1 2 + CONT(16))', 'E116', "Invalid arguments") call T(17, 'F(1, 2) + CONT(17)', 'E118', "Too many arguments") call T(18, 'F() + CONT(18)', 'E119', "Not enough arguments") call T(19, '{(1} + CONT(19)', 'E110', "Missing ')'") call T(20, '("abc"[1) + CONT(20)', 'E111', "Missing ']'") call T(21, '(1 +) + CONT(21)', 'E15', "Invalid expression") call T(22, '1 2 + CONT(22)', 'E15', "Invalid expression") call T(23, '(1 ? 2) + CONT(23)', 'E109', "Missing ':' after '?'") call T(24, '("abc) + CONT(24)', 'E114', "Missing quote") call T(25, "('abc) + CONT(25)", 'E115', "Missing quote") call T(26, '& + CONT(26)', 'E112', "Option name missing") call T(27, '&asdf + CONT(27)', 'E113', "Unknown option") Xpath 134217728 " X: 134217728 let expected = "" \ . "T1M1T2M2T3M3T4M4T5M5T6M6T7M7T8M8T9M9T10M10T11M11T12M12T13M13T14M14" \ . "T15M15T16M16T17M17T18M18T19M19T20M20T21M21T22M22T23M23T24M24T25M25" \ . "T26M26T27M27" if taken != expected Xpath 268435456 " X: 0 Xout "'taken' is" taken "instead of" expected if substitute(taken, '\(.*\)T3M3x\(.*\)', '\1T3M3\2', "") == expected Xout "Is ++emsg_skip for var with expr_start non-NULL" \ "in f_exists ok?" endif endif unlet! var caught taken expected call delete(WA_t5) unlet! WA_t5 delfunction WA_t5 endif Xcheck 134217728 "------------------------------------------------------------------------------- " Test 79: Throwing one of several errors for the same command {{{1 " " When several errors appear in a row (for instance during expression " evaluation), the first as the most specific one is used when " throwing an error exception. If, however, a syntax error is " detected afterwards, this one is used for the error exception. " On a syntax error, the next command is not executed, on a normal " error, however, it is (relevant only in a function without the " "abort" flag). v:errmsg is not set. " " If throwing error exceptions is configured off, v:errmsg is always " set to the latest error message, that is, to the more general " message or the syntax error, respectively. "------------------------------------------------------------------------------- XpathINIT XloopINIT 1 2 function! NEXT(cmd) exec a:cmd . " | Xloop 1" endfunction call NEXT('echo novar') " X: 1 * 1 (checks nextcmd) XloopNEXT call NEXT('let novar #') " X: 0 * 2 (skips nextcmd) XloopNEXT call NEXT('unlet novar #') " X: 0 * 4 (skips nextcmd) XloopNEXT call NEXT('let {novar}') " X: 0 * 8 (skips nextcmd) XloopNEXT call NEXT('unlet{ novar}') " X: 0 * 16 (skips nextcmd) function! EXEC(cmd) exec a:cmd endfunction function! MATCH(expected, msg, enr, emsg) let msg = a:msg if a:enr == "" Xout "TODO: Add message number for:" a:emsg let msg = ":" . msg endif let english = v:lang == "C" || v:lang =~ '^[Ee]n' if msg !~ '^'.a:enr.':' || (english && msg !~ a:emsg) let match = 0 if a:expected " no match although expected if a:msg == "" Xout "Message missing." else let msg = escape(msg, '"') Xout "Unexpected message:" msg Xout "Expected:" a:enr . ": " . a:emsg endif endif else let match = 1 if !a:expected " match although not expected let msg = escape(msg, '"') Xout "Unexpected message:" msg Xout "Expected none." endif endif return match endfunction try while 1 " dummy loop try let v:errmsg = "" let caught = 0 let thrmsg = "" call EXEC('echo novar') " normal error catch /^Vim\((\a\+)\)\=:/ let caught = 1 let thrmsg = substitute(v:exception, '^Vim\((\a\+)\)\=:', '', "") finally Xpath 32 " X: 32 if !caught if !$VIMNOERRTHROW Xpath 64 " X: 0 endif elseif !MATCH(1, thrmsg, 'E121', "Undefined variable") \ || v:errmsg != "" Xpath 128 " X: 0 endif if !caught && !MATCH(1, v:errmsg, 'E15', "Invalid expression") Xpath 256 " X: 0 endif break " discard error if $VIMNOERRTHROW == 1 endtry endwhile Xpath 512 " X: 512 let cmd = "let" XloopINIT 1024 32 while cmd != "" try let v:errmsg = "" let caught = 0 let thrmsg = "" call EXEC(cmd . ' novar #') " normal plus syntax error catch /^Vim\((\a\+)\)\=:/ let caught = 1 let thrmsg = substitute(v:exception, '^Vim\((\a\+)\)\=:', '', "") finally Xloop 1 " X: 1024 * (1 + 32) if !caught if !$VIMNOERRTHROW Xloop 2 " X: 0 endif else if cmd == "let" let match = MATCH(0, thrmsg, 'E121', "Undefined variable") elseif cmd == "unlet" let match = MATCH(0, thrmsg, 'E108', "No such variable") endif if match " normal error Xloop 4 " X: 0 endif if !MATCH(1, thrmsg, 'E488', "Trailing characters") \|| v:errmsg != "" " syntax error Xloop 8 " X: 0 endif endif if !caught && !MATCH(1, v:errmsg, 'E488', "Trailing characters") " last error Xloop 16 " X: 0 endif if cmd == "let" let cmd = "unlet" else let cmd = "" endif XloopNEXT continue " discard error if $VIMNOERRTHROW == 1 endtry endwhile Xpath 1048576 " X: 1048576 let cmd = "let" XloopINIT 2097152 32 while cmd != "" try let v:errmsg = "" let caught = 0 let thrmsg = "" call EXEC(cmd . ' {novar}') " normal plus syntax error catch /^Vim\((\a\+)\)\=:/ let caught = 1 let thrmsg = substitute(v:exception, '^Vim\((\a\+)\)\=:', '', "") finally Xloop 1 " X: 2097152 * (1 + 32) if !caught if !$VIMNOERRTHROW Xloop 2 " X: 0 endif else if MATCH(0, thrmsg, 'E121', "Undefined variable") " normal error Xloop 4 " X: 0 endif if !MATCH(1, thrmsg, 'E475', 'Invalid argument\>') \ || v:errmsg != "" " syntax error Xloop 8 " X: 0 endif endif if !caught && !MATCH(1, v:errmsg, 'E475', 'Invalid argument\>') " last error Xloop 16 " X: 0 endif if cmd == "let" let cmd = "unlet" else let cmd = "" endif XloopNEXT continue " discard error if $VIMNOERRTHROW == 1 endtry endwhile catch /.*/ " The Xpath command does not accept 2^31 (negative); add explicitly: let Xpath = Xpath + 2147483648 " X: 0 Xout v:exception "in" v:throwpoint endtry unlet! next_command thrmsg match delfunction NEXT delfunction EXEC delfunction MATCH Xcheck 70288929 "------------------------------------------------------------------------------- " Test 80: Syntax error in expression for illegal :elseif {{{1 " " If there is a syntax error in the expression after an illegal " :elseif, an error message is given (or an error exception thrown) " for the illegal :elseif rather than the expression error. "------------------------------------------------------------------------------- XpathINIT function! MSG(enr, emsg) let english = v:lang == "C" || v:lang =~ '^[Ee]n' if a:enr == "" Xout "TODO: Add message number for:" a:emsg let v:errmsg = ":" . v:errmsg endif let match = 1 if v:errmsg !~ '^'.a:enr.':' || (english && v:errmsg !~ a:emsg) let match = 0 if v:errmsg == "" Xout "Message missing." else let v:errmsg = escape(v:errmsg, '"') Xout "Unexpected message:" v:errmsg endif endif return match endfunction let v:errmsg = "" if 0 else elseif 1 ||| 2 endif Xpath 1 " X: 1 if !MSG('E584', ":elseif after :else") Xpath 2 " X: 0 endif let v:errmsg = "" if 1 else elseif 1 ||| 2 endif Xpath 4 " X: 4 if !MSG('E584', ":elseif after :else") Xpath 8 " X: 0 endif let v:errmsg = "" elseif 1 ||| 2 Xpath 16 " X: 16 if !MSG('E582', ":elseif without :if") Xpath 32 " X: 0 endif let v:errmsg = "" while 1 elseif 1 ||| 2 endwhile Xpath 64 " X: 64 if !MSG('E582', ":elseif without :if") Xpath 128 " X: 0 endif while 1 try try let v:errmsg = "" let caught = 0 if 0 else elseif 1 ||| 2 endif catch /^Vim\((\a\+)\)\=:/ let caught = 1 let v:errmsg = substitute(v:exception, '^Vim\((\a\+)\)\=:', '', "") finally Xpath 256 " X: 256 if !caught && !$VIMNOERRTHROW Xpath 512 " X: 0 endif if !MSG('E584', ":elseif after :else") Xpath 1024 " X: 0 endif endtry catch /.*/ Xpath 2048 " X: 0 Xout v:exception "in" v:throwpoint finally break " discard error for $VIMNOERRTHROW endtry endwhile while 1 try try let v:errmsg = "" let caught = 0 if 1 else elseif 1 ||| 2 endif catch /^Vim\((\a\+)\)\=:/ let caught = 1 let v:errmsg = substitute(v:exception, '^Vim\((\a\+)\)\=:', '', "") finally Xpath 4096 " X: 4096 if !caught && !$VIMNOERRTHROW Xpath 8192 " X: 0 endif if !MSG('E584', ":elseif after :else") Xpath 16384 " X: 0 endif endtry catch /.*/ Xpath 32768 " X: 0 Xout v:exception "in" v:throwpoint finally break " discard error for $VIMNOERRTHROW endtry endwhile while 1 try try let v:errmsg = "" let caught = 0 elseif 1 ||| 2 catch /^Vim\((\a\+)\)\=:/ let caught = 1 let v:errmsg = substitute(v:exception, '^Vim\((\a\+)\)\=:', '', "") finally Xpath 65536 " X: 65536 if !caught && !$VIMNOERRTHROW Xpath 131072 " X: 0 endif if !MSG('E582', ":elseif without :if") Xpath 262144 " X: 0 endif endtry catch /.*/ Xpath 524288 " X: 0 Xout v:exception "in" v:throwpoint finally break " discard error for $VIMNOERRTHROW endtry endwhile while 1 try try let v:errmsg = "" let caught = 0 while 1 elseif 1 ||| 2 endwhile catch /^Vim\((\a\+)\)\=:/ let caught = 1 let v:errmsg = substitute(v:exception, '^Vim\((\a\+)\)\=:', '', "") finally Xpath 1048576 " X: 1048576 if !caught && !$VIMNOERRTHROW Xpath 2097152 " X: 0 endif if !MSG('E582', ":elseif without :if") Xpath 4194304 " X: 0 endif endtry catch /.*/ Xpath 8388608 " X: 0 Xout v:exception "in" v:throwpoint finally break " discard error for $VIMNOERRTHROW endtry endwhile Xpath 16777216 " X: 16777216 unlet! caught delfunction MSG Xcheck 17895765 "------------------------------------------------------------------------------- " Test 81: Discarding exceptions after an error or interrupt {{{1 " " When an exception is thrown from inside a :try conditional without " :catch and :finally clauses and an error or interrupt occurs before " the :endtry is reached, the exception is discarded. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() try Xpath 1 " X: 1 try Xpath 2 " X: 2 throw "arrgh" Xpath 4 " X: 0 " if 1 Xpath 8 " X: 0 " error after :throw: missing :endif endtry Xpath 16 " X: 0 catch /arrgh/ Xpath 32 " X: 0 endtry Xpath 64 " X: 0 endif if ExtraVim() try Xpath 128 " X: 128 try Xpath 256 " X: 256 throw "arrgh" Xpath 512 " X: 0 endtry " INTERRUPT Xpath 1024 " X: 0 catch /arrgh/ Xpath 2048 " X: 0 endtry Xpath 4096 " X: 0 endif Xcheck 387 "------------------------------------------------------------------------------- " Test 82: Ignoring :catch clauses after an error or interrupt {{{1 " " When an exception is thrown and an error or interrupt occurs before " the matching :catch clause is reached, the exception is discarded " and the :catch clause is ignored (also for the error or interrupt " exception being thrown then). "------------------------------------------------------------------------------- XpathINIT if ExtraVim() try try Xpath 1 " X: 1 throw "arrgh" Xpath 2 " X: 0 " if 1 Xpath 4 " X: 0 " error after :throw: missing :endif catch /.*/ Xpath 8 " X: 0 Xout v:exception "in" ExtraVimThrowpoint() catch /.*/ Xpath 16 " X: 0 Xout v:exception "in" ExtraVimThrowpoint() endtry Xpath 32 " X: 0 catch /arrgh/ Xpath 64 " X: 0 endtry Xpath 128 " X: 0 endif if ExtraVim() function! E() try try Xpath 256 " X: 256 throw "arrgh" Xpath 512 " X: 0 " if 1 Xpath 1024 " X: 0 " error after :throw: missing :endif catch /.*/ Xpath 2048 " X: 0 Xout v:exception "in" ExtraVimThrowpoint() catch /.*/ Xpath 4096 " X: 0 Xout v:exception "in" ExtraVimThrowpoint() endtry Xpath 8192 " X: 0 catch /arrgh/ Xpath 16384 " X: 0 endtry endfunction call E() Xpath 32768 " X: 0 endif if ExtraVim() try try Xpath 65536 " X: 65536 throw "arrgh" Xpath 131072 " X: 0 catch /.*/ "INTERRUPT Xpath 262144 " X: 0 Xout v:exception "in" ExtraVimThrowpoint() catch /.*/ Xpath 524288 " X: 0 Xout v:exception "in" ExtraVimThrowpoint() endtry Xpath 1048576 " X: 0 catch /arrgh/ Xpath 2097152 " X: 0 endtry Xpath 4194304 " X: 0 endif if ExtraVim() function I() try try Xpath 8388608 " X: 8388608 throw "arrgh" Xpath 16777216 " X: 0 catch /.*/ "INTERRUPT Xpath 33554432 " X: 0 Xout v:exception "in" ExtraVimThrowpoint() catch /.*/ Xpath 67108864 " X: 0 Xout v:exception "in" ExtraVimThrowpoint() endtry Xpath 134217728 " X: 0 catch /arrgh/ Xpath 268435456 " X: 0 endtry endfunction call I() Xpath 536870912 " X: 0 endif Xcheck 8454401 "------------------------------------------------------------------------------- " Test 83: Executing :finally clauses after an error or interrupt {{{1 " " When an exception is thrown and an error or interrupt occurs before " the :finally of the innermost :try is reached, the exception is " discarded and the :finally clause is executed. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() try Xpath 1 " X: 1 try Xpath 2 " X: 2 throw "arrgh" Xpath 4 " X: 0 " if 1 Xpath 8 " X: 0 " error after :throw: missing :endif finally Xpath 16 " X: 16 endtry Xpath 32 " X: 0 catch /arrgh/ Xpath 64 " X: 0 endtry Xpath 128 " X: 0 endif if ExtraVim() try Xpath 256 " X: 256 try Xpath 512 " X: 512 throw "arrgh" Xpath 1024 " X: 0 finally "INTERRUPT Xpath 2048 " X: 2048 endtry Xpath 4096 " X: 0 catch /arrgh/ Xpath 8192 " X: 0 endtry Xpath 16384 " X: 0 endif Xcheck 2835 "------------------------------------------------------------------------------- " Test 84: Exceptions in autocommand sequences. {{{1 " " When an exception occurs in a sequence of autocommands for " a specific event, the rest of the sequence is not executed. The " command that triggered the autocommand execution aborts, and the " exception is propagated to the caller. " " For the FuncUndefined event under a function call expression or " :call command, the function is not executed, even when it has " been defined by the autocommands before the exception occurred. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() function! INT() "INTERRUPT let dummy = 0 endfunction aug TMP autocmd! autocmd User x1 Xpath 1 " X: 1 autocmd User x1 throw "x1" autocmd User x1 Xpath 2 " X: 0 autocmd User x2 Xpath 4 " X: 4 autocmd User x2 asdf autocmd User x2 Xpath 8 " X: 0 autocmd User x3 Xpath 16 " X: 16 autocmd User x3 call INT() autocmd User x3 Xpath 32 " X: 0 autocmd FuncUndefined U1 function! U1() autocmd FuncUndefined U1 Xpath 64 " X: 0 autocmd FuncUndefined U1 endfunction autocmd FuncUndefined U1 Xpath 128 " X: 128 autocmd FuncUndefined U1 throw "U1" autocmd FuncUndefined U1 Xpath 256 " X: 0 autocmd FuncUndefined U2 function! U2() autocmd FuncUndefined U2 Xpath 512 " X: 0 autocmd FuncUndefined U2 endfunction autocmd FuncUndefined U2 Xpath 1024 " X: 1024 autocmd FuncUndefined U2 ASDF autocmd FuncUndefined U2 Xpath 2048 " X: 0 autocmd FuncUndefined U3 function! U3() autocmd FuncUndefined U3 Xpath 4096 " X: 0 autocmd FuncUndefined U3 endfunction autocmd FuncUndefined U3 Xpath 8192 " X: 8192 autocmd FuncUndefined U3 call INT() autocmd FuncUndefined U3 Xpath 16384 " X: 0 aug END try try Xpath 32768 " X: 32768 doautocmd User x1 catch /x1/ Xpath 65536 " X: 65536 endtry while 1 try Xpath 131072 " X: 131072 let caught = 0 doautocmd User x2 catch /asdf/ let caught = 1 finally Xpath 262144 " X: 262144 if !caught && !$VIMNOERRTHROW Xpath 524288 " X: 0 " Propagate uncaught error exception, else " ... but break loop for caught error exception, " or discard error and break loop if $VIMNOERRTHROW break endif endtry endwhile while 1 try Xpath 1048576 " X: 1048576 let caught = 0 doautocmd User x3 catch /Vim:Interrupt/ let caught = 1 finally Xpath 2097152 " X: 2097152 if !caught && !$VIMNOINTTHROW Xpath 4194304 " X: 0 " Propagate uncaught interrupt exception, else " ... but break loop for caught interrupt exception, " or discard interrupt and break loop if $VIMNOINTTHROW break endif endtry endwhile if exists("*U1") | delfunction U1 | endif if exists("*U2") | delfunction U2 | endif if exists("*U3") | delfunction U3 | endif try Xpath 8388608 " X: 8388608 call U1() catch /U1/ Xpath 16777216 " X: 16777216 endtry while 1 try Xpath 33554432 " X: 33554432 let caught = 0 call U2() catch /ASDF/ let caught = 1 finally Xpath 67108864 " X: 67108864 if !caught && !$VIMNOERRTHROW Xpath 134217728 " X: 0 " Propagate uncaught error exception, else " ... but break loop for caught error exception, " or discard error and break loop if $VIMNOERRTHROW break endif endtry endwhile while 1 try Xpath 268435456 " X: 268435456 let caught = 0 call U3() catch /Vim:Interrupt/ let caught = 1 finally Xpath 536870912 " X: 536870912 if !caught && !$VIMNOINTTHROW Xpath 1073741824 " X: 0 " Propagate uncaught interrupt exception, else " ... but break loop for caught interrupt exception, " or discard interrupt and break loop if $VIMNOINTTHROW break endif endtry endwhile catch /.*/ " The Xpath command does not accept 2^31 (negative); display explicitly: exec "!echo 2147483648 >>" . g:ExtraVimResult Xout "Caught" v:exception "in" v:throwpoint endtry unlet caught delfunction INT delfunction U1 delfunction U2 delfunction U3 au! TMP aug! TMP endif Xcheck 934782101 "------------------------------------------------------------------------------- " Test 85: Error exceptions in autocommands for I/O command events {{{1 " " When an I/O command is inside :try/:endtry, autocommands to be " executed after it should be skipped on an error (exception) in the " command itself or in autocommands to be executed before the command. " In the latter case, the I/O command should not be executed either. " Example 1: BufWritePre, :write, BufWritePost " Example 2: FileReadPre, :read, FileReadPost. "------------------------------------------------------------------------------- XpathINIT function! MSG(enr, emsg) let english = v:lang == "C" || v:lang =~ '^[Ee]n' if a:enr == "" Xout "TODO: Add message number for:" a:emsg let v:errmsg = ":" . v:errmsg endif let match = 1 if v:errmsg !~ '^'.a:enr.':' || (english && v:errmsg !~ a:emsg) let match = 0 if v:errmsg == "" Xout "Message missing." else let v:errmsg = escape(v:errmsg, '"') Xout "Unexpected message:" v:errmsg endif endif return match endfunction " Remove the autocommands for the events specified as arguments in all used " autogroups. function! Delete_autocommands(...) let augfile = tempname() while 1 try exec "redir >" . augfile aug redir END exec "edit" augfile g/^$/d norm G$ let wrap = "w" while search('\%( \|^\)\@<=.\{-}\%( \)\@=', wrap) > 0 let wrap = "W" exec "norm y/ \n" let argno = 1 while argno <= a:0 exec "au!" escape(@", " ") a:{argno} let argno = argno + 1 endwhile endwhile catch /.*/ finally bwipeout! call delete(augfile) break " discard errors for $VIMNOERRTHROW endtry endwhile endfunction call Delete_autocommands("BufWritePre", "BufWritePost") while 1 try try let post = 0 aug TMP au! BufWritePost * let post = 1 aug END let caught = 0 write /n/o/n/e/x/i/s/t/e/n/t catch /^Vim(write):/ let caught = 1 let v:errmsg = substitute(v:exception, '^Vim(write):', '', "") finally Xpath 1 " X: 1 if !caught && !$VIMNOERRTHROW Xpath 2 " X: 0 endif let v:errmsg = substitute(v:errmsg, '^"/n/o/n/e/x/i/s/t/e/n/t" ', \ '', "") if !MSG('E212', "Can't open file for writing") Xpath 4 " X: 0 endif if post Xpath 8 " X: 0 Xout "BufWritePost commands executed after write error" endif au! TMP aug! TMP endtry catch /.*/ Xpath 16 " X: 0 Xout v:exception "in" v:throwpoint finally break " discard error for $VIMNOERRTHROW endtry endwhile while 1 try try let post = 0 aug TMP au! BufWritePre * asdf au! BufWritePost * let post = 1 aug END let tmpfile = tempname() let caught = 0 exec "write" tmpfile catch /^Vim\((write)\)\=:/ let caught = 1 let v:errmsg = substitute(v:exception, '^Vim\((write)\)\=:', '', "") finally Xpath 32 " X: 32 if !caught && !$VIMNOERRTHROW Xpath 64 " X: 0 endif let v:errmsg = substitute(v:errmsg, '^"'.tmpfile.'" ', '', "") if !MSG('E492', "Not an editor command") Xpath 128 " X: 0 endif if filereadable(tmpfile) Xpath 256 " X: 0 Xout ":write command not suppressed after BufWritePre error" endif if post Xpath 512 " X: 0 Xout "BufWritePost commands executed after BufWritePre error" endif au! TMP aug! TMP endtry catch /.*/ Xpath 1024 " X: 0 Xout v:exception "in" v:throwpoint finally break " discard error for $VIMNOERRTHROW endtry endwhile call delete(tmpfile) call Delete_autocommands("BufWritePre", "BufWritePost", \ "BufReadPre", "BufReadPost", "FileReadPre", "FileReadPost") while 1 try try let post = 0 aug TMP au! FileReadPost * let post = 1 aug END let caught = 0 read /n/o/n/e/x/i/s/t/e/n/t catch /^Vim(read):/ let caught = 1 let v:errmsg = substitute(v:exception, '^Vim(read):', '', "") finally Xpath 2048 " X: 2048 if !caught && !$VIMNOERRTHROW Xpath 4096 " X: 0 endif let v:errmsg = substitute(v:errmsg, ' /n/o/n/e/x/i/s/t/e/n/t$', \ '', "") if !MSG('E484', "Can't open file") Xpath 8192 " X: 0 endif if post Xpath 16384 " X: 0 Xout "FileReadPost commands executed after write error" endif au! TMP aug! TMP endtry catch /.*/ Xpath 32768 " X: 0 Xout v:exception "in" v:throwpoint finally break " discard error for $VIMNOERRTHROW endtry endwhile while 1 try let infile = tempname() let tmpfile = tempname() exec "!echo XYZ >" . infile exec "edit" tmpfile try Xpath 65536 " X: 65536 try let post = 0 aug TMP au! FileReadPre * asdf au! FileReadPost * let post = 1 aug END let caught = 0 exec "0read" infile catch /^Vim\((read)\)\=:/ let caught = 1 let v:errmsg = substitute(v:exception, '^Vim\((read)\)\=:', '', \ "") finally Xpath 131072 " X: 131072 if !caught && !$VIMNOERRTHROW Xpath 262144 " X: 0 endif let v:errmsg = substitute(v:errmsg, ' '.infile.'$', '', "") if !MSG('E492', "Not an editor command") Xpath 524288 " X: 0 endif if getline("1") == "XYZ" Xpath 1048576 " X: 0 Xout ":read command not suppressed after FileReadPre error" endif if post Xpath 2097152 " X: 0 Xout "FileReadPost commands executed after " . \ "FileReadPre error" endif au! TMP aug! TMP endtry finally bwipeout! endtry catch /.*/ Xpath 4194304 " X: 0 Xout v:exception "in" v:throwpoint finally break " discard error for $VIMNOERRTHROW endtry endwhile call delete(infile) call delete(tmpfile) unlet! caught post infile tmpfile delfunction MSG delfunction Delete_autocommands Xcheck 198689 "------------------------------------------------------------------------------- " Test 86: $VIMNOERRTHROW and $VIMNOINTTHROW support {{{1 " " It is possible to configure Vim for throwing exceptions on error " or interrupt, controlled by variables $VIMNOERRTHROW and " $VIMNOINTTHROW. This is just for increasing the number of tests. " All tests here should run for all four combinations of setting " these variables to 0 or 1. The variables are intended for the " development phase only. In the final release, Vim should be " configured to always use error and interrupt exceptions. " " The test result is "OK", " " - if the $VIMNOERRTHROW and the $VIMNOINTTHROW control are not " configured and exceptions are thrown on error and on " interrupt. " " - if the $VIMNOERRTHROW or the $VIMNOINTTHROW control is " configured and works as intended. " " What actually happens, is shown in the test output. " " Otherwise, the test result is "FAIL", and the test output describes " the problem. " " IMPORTANT: This must be the last test because it sets $VIMNOERRTHROW and " $VIMNOINTTHROW. "------------------------------------------------------------------------------- XpathINIT if ExtraVim() function! ThrowOnError() XloopNEXT let caught = 0 try Xloop 1 " X: 1 + 8 + 64 asdf catch /.*/ let caught = 1 " error exception caught finally Xloop 2 " X: 2 + 16 + 128 return caught " discard aborting error endtry Xloop 4 " X: 0 endfunction let quits_skipped = 0 function! ThrowOnInterrupt() XloopNEXT let caught = 0 try Xloop 1 " X: (1 + 8 + 64) * 512 "INTERRUPT3 let dummy = 0 let g:quits_skipped = g:quits_skipped + 1 catch /.*/ let caught = 1 " interrupt exception caught finally Xloop 2 " X: (2 + 16 + 128) * 512 return caught " discard interrupt endtry Xloop 4 " X: 0 endfunction function! CheckThrow(Type) execute 'return ThrowOn' . a:Type . '()' endfunction function! CheckConfiguration(type) " type is "error" or "interrupt" let type = a:type let Type = substitute(type, '.*', '\u&', "") let VAR = '$VIMNO' . substitute(type, '\(...\).*', '\U\1', "") . 'THROW' if type == "error" XloopINIT! 1 8 elseif type == "interrupt" XloopINIT! 512 8 endif exec 'let requested_for_tests = exists(VAR) && ' . VAR . ' == 0' exec 'let suppressed_for_tests = ' . VAR . ' != 0' let used_in_tests = CheckThrow(Type) exec 'let ' . VAR . ' = 0' let request_works = CheckThrow(Type) exec 'let ' . VAR . ' = 1' let suppress_works = !CheckThrow(Type) if type == "error" XloopINIT! 262144 8 elseif type == "interrupt" XloopINIT! 2097152 8 if g:quits_skipped != 0 Xloop 1 " X: 0*2097152 Xout "Test environment error. Interrupt breakpoints skipped: " \ . g:quits_skipped . ".\n" \ . "Cannot check whether interrupt exceptions are thrown." return endif endif let failure = \ !suppressed_for_tests && !used_in_tests \ || !request_works let contradiction = \ used_in_tests \ ? suppressed_for_tests && !request_works \ : !suppressed_for_tests if failure " Failure in configuration. Xloop 2 " X: 0 * 2* (262144 + 2097152) elseif contradiction " Failure in test logic. Should not happen. Xloop 4 " X: 0 * 4 * (262144 + 2097152) endif let var_control_configured = \ request_works != used_in_tests \ || suppress_works == used_in_tests let var_control_not_configured = \ requested_for_tests || suppressed_for_tests \ ? request_works && !suppress_works \ : request_works == used_in_tests \ && suppress_works != used_in_tests let with = used_in_tests ? "with" : "without" let set = suppressed_for_tests ? "non-zero" : \ requested_for_tests ? "0" : "unset" let although = contradiction && !var_control_not_configured \ ? ",\nalthough " \ : ".\n" let output = "All tests were run " . with . " throwing exceptions on " \ . type . although if !var_control_not_configured let output = output . VAR . " was " . set . "." if !request_works && !requested_for_tests let output = output . \ "\n" . Type . " exceptions are not thrown when " . VAR . \ " is\nset to 0." endif if !suppress_works && (!used_in_tests || \ !request_works && \ !requested_for_tests && !suppressed_for_tests) let output = output . \ "\n" . Type . " exceptions are thrown when " . VAR . \ " is set to 1." endif if !failure && var_control_configured let output = output . \ "\nRun tests also with " . substitute(VAR, '^\$', '', "") \ . "=" . used_in_tests . "." \ . "\nThis is for testing in the development phase only." \ . " Remove the \n" \ . VAR . " control in the final release." endif else let output = output . \ "The " . VAR . " control is not configured." endif Xout output endfunction call CheckConfiguration("error") Xpath 16777216 " X: 16777216 call CheckConfiguration("interrupt") Xpath 33554432 " X: 33554432 endif Xcheck 50443995 " IMPORTANT: No test should be added after this test because it changes " $VIMNOERRTHROW and $VIMNOINTTHROW. "------------------------------------------------------------------------------- " Modelines {{{1 " vim: ts=8 sw=4 tw=80 fdm=marker " vim: fdt=substitute(substitute(foldtext(),\ '\\%(^+--\\)\\@<=\\(\\s*\\)\\(.\\{-}\\)\:\ \\%(\"\ \\)\\=\\(Test\ \\d*\\)\:\\s*',\ '\\3\ (\\2)\:\ \\1',\ \"\"),\ '\\(Test\\s*\\)\\(\\d\\)\\D\\@=',\ '\\1\ \\2',\ "") "-------------------------------------------------------------------------------
zyz2011-vim
src/testdir/test49.vim
Vim Script
gpl2
224,143
# # Makefile to run all tests for Vim, on Dos-like machines. # # Requires a set of Unix tools: echo, diff, etc. VIMPROG = ..\\vim # Omitted: # test2 "\\tmp" doesn't work. # test10 'errorformat' is different # test12 can't unlink a swap file # test25 uses symbolic link # test27 can't edit file with "*" in file name # test31 16 bit version runs out of memory... SCRIPTS16 = test1.out test19.out test20.out test22.out \ test23.out test24.out test28.out test29.out \ test35.out test36.out test43.out \ test44.out test45.out test46.out test47.out \ test48.out test51.out test53.out test54.out \ test55.out test56.out test57.out test58.out test59.out \ test60.out test61.out test62.out test63.out test64.out SCRIPTS = test3.out test4.out test5.out test6.out test7.out \ test8.out test9.out test11.out test13.out test14.out \ test15.out test17.out test18.out test21.out test26.out \ test30.out test31.out test32.out test33.out test34.out \ test37.out test38.out test39.out test40.out test41.out \ test42.out test52.out test65.out test66.out test67.out \ test68.out test69.out test71.out test72.out test73.out \ test74.out test75.out test76.out test77.out test78.out \ test79.out test80.out test81.out test82.out test83.out \ test84.out test85.out SCRIPTS32 = test50.out test70.out SCRIPTS_GUI = test16.out .SUFFIXES: .in .out nongui: fixff $(SCRIPTS16) $(SCRIPTS) echo ALL DONE small: echo ALL DONE gui: fixff $(SCRIPTS16) $(SCRIPTS) $(SCRIPTS_GUI) echo ALL DONE win32: fixff $(SCRIPTS16) $(SCRIPTS) $(SCRIPTS32) echo ALL DONE fixff: -$(VIMPROG) -u dos.vim --noplugin "+argdo set ff=dos|upd" +q *.in *.ok -$(VIMPROG) -u dos.vim --noplugin "+argdo set ff=unix|upd" +q \ dotest.in test60.ok test71.ok test74.ok clean: -del *.out -if exist test.ok del test.ok -if exist small.vim del small.vim -if exist tiny.vim del tiny.vim -if exist mbyte.vim del mbyte.vim -if exist mzscheme.vim del mzscheme.vim -del X* -if exist viminfo del viminfo .in.out: copy $*.ok test.ok $(VIMPROG) -u dos.vim -U NONE --noplugin -s dotest.in $*.in diff test.out $*.ok -if exist $*.out del $*.out rename test.out $*.out -del X* -del X*.* -del test.ok -rmdir /s /q Xfind -if exist viminfo del viminfo
zyz2011-vim
src/testdir/Make_dos.mak
Makefile
gpl2
2,240
Tests for ":highlight". vim: set ft=vim : STARTTEST :so small.vim :" basic test if ":highlight" doesn't crash :highlight :hi Search :" test setting colors. :" test clearing one color and all doesn't generate error or warning :hi NewGroup term=bold cterm=italic ctermfg=DarkBlue ctermbg=Grey gui= guifg=#00ff00 guibg=Cyan :hi Group2 term= cterm= :hi Group3 term=underline cterm=bold :redir! >test.out :hi NewGroup :hi Group2 :hi Group3 :hi clear NewGroup :hi NewGroup :hi Group2 :hi Group2 NONE :hi Group2 :hi clear :hi Group3 :hi Crash term='asdf :redir END :" filter ctermfg and ctermbg, the numbers depend on the terminal :e test.out :%s/ctermfg=\d*/ctermfg=2/ :%s/ctermbg=\d*/ctermbg=3/ :" filter out possibly translated error message :%s/E475: [^:]*:/E475:/ :" fix the fileformat :set ff& :wq! ENDTEST
zyz2011-vim
src/testdir/test51.in
Vim Script
gpl2
808
Tests for multi-line regexps with ":s". vim: set ft=vim : STARTTEST :" test if replacing a line break works with a back reference :/^1/,/^2/s/\n\(.\)/ \1/ :" test if inserting a line break works with a back reference :/^3/,/^4/s/\(.\)$/\r\1/ :" test if replacing a line break with another line break works :/^5/,/^6/s/\(\_d\{3}\)/x\1x/ :/^1/,$w! test.out :qa! ENDTEST 1 aa bb cc 2 dd ee 3 ef gh 4 ij 5 a8 8b c9 9d 6 e7 77f xxxxx
zyz2011-vim
src/testdir/test46.in
Vim Script
gpl2
431
" Vim script for exists() function test " Script-local variables are checked here " Existing script-local variable let s:script_var = 1 echo 's:script_var: 1' if exists('s:script_var') echo "OK" else echo "FAILED" endif " Non-existing script-local variable unlet s:script_var echo 's:script_var: 0' if !exists('s:script_var') echo "OK" else echo "FAILED" endif " Existing script-local list let s:script_list = ["blue", "orange"] echo 's:script_list: 1' if exists('s:script_list') echo "OK" else echo "FAILED" endif " Non-existing script-local list unlet s:script_list echo 's:script_list: 0' if !exists('s:script_list') echo "OK" else echo "FAILED" endif " Existing script-local dictionary let s:script_dict = {"xcord":100, "ycord":2} echo 's:script_dict: 1' if exists('s:script_dict') echo "OK" else echo "FAILED" endif " Non-existing script-local dictionary unlet s:script_dict echo 's:script_dict: 0' if !exists('s:script_dict') echo "OK" else echo "FAILED" endif " Existing script curly-brace variable let str = "script" let s:curly_{str}_var = 1 echo 's:curly_' . str . '_var: 1' if exists('s:curly_{str}_var') echo "OK" else echo "FAILED" endif " Non-existing script-local curly-brace variable unlet s:curly_{str}_var echo 's:curly_' . str . '_var: 0' if !exists('s:curly_{str}_var') echo "OK" else echo "FAILED" endif " Existing script-local function function! s:my_script_func() endfunction echo '*s:my_script_func: 1' if exists('*s:my_script_func') echo "OK" else echo "FAILED" endif " Non-existing script-local function delfunction s:my_script_func echo '*s:my_script_func: 0' if !exists('*s:my_script_func') echo "OK" else echo "FAILED" endif unlet str
zyz2011-vim
src/testdir/test60.vim
Vim Script
gpl2
1,757
" Settings for test script execution " Always use "COMMAND.COM", don't use the value of "$SHELL". set shell=c:\COMMAND.COM shellquote= shellxquote= shellcmdflag=/c shellredir=> " This is used only when the +eval feature is available. if executable("cmd.exe") set shell=cmd.exe endif
zyz2011-vim
src/testdir/dos.vim
Vim Script
gpl2
286
" Tests for storing global variables in the .viminfo file vim: set ft=vim: STARTTEST :so small.vim :" Do all test in a separate window to avoid E211 when we recursively :" delete the Xfind directory during cleanup :" :" This will cause a few errors, do it silently. :set visualbell :set nocp viminfo+=!,nviminfo :let MY_GLOBAL_DICT={'foo': 1, 'bar': 0, 'longvarible': 1000} :" store a really long list, so line wrapping will occur in viminfo file :let MY_GLOBAL_LIST=range(1,100) :wv! Xviminfo :unlet MY_GLOBAL_DICT :unlet MY_GLOBAL_LIST :rv! Xviminfo :call delete('Xviminfo') :if exists("MY_GLOBAL_DICT") :redir >> test.out :echo MY_GLOBAL_DICT :redir end :endif :if exists("MY_GLOBAL_LIST") :redir >> test.out :echo MY_GLOBAL_LIST :redir end :endif :redir >> test.out :echo "foobar" :redir end :endif :qa! ENDTEST eof
zyz2011-vim
src/testdir/test74.in
Vim Script
gpl2
822
" Settings for test script execution under OpenVMS " Do not make any swap files set noswapfile
zyz2011-vim
src/testdir/vms.vim
Vim Script
gpl2
96
" Settings for test script execution " Always use "sh", don't use the value of "$SHELL". set shell=sh
zyz2011-vim
src/testdir/unix.vim
Vim Script
gpl2
102
Tests for :sort command. vim: set ft=vim : STARTTEST :so small.vim :" :/^t01:/+1,/^t02/-1sort :/^t02:/+1,/^t03/-1sort n :/^t03:/+1,/^t04/-1sort x :/^t04:/+1,/^t05/-1sort u :/^t05:/+1,/^t06/-1sort! :/^t06:/+1,/^t07/-1sort! n :/^t07:/+1,/^t08/-1sort! u :/^t08:/+1,/^t09/-1sort o :/^t09:/+1,/^t10/-1sort! x :/^t10:/+1,/^t11/-1sort/./ :/^t11:/+1,/^t12/-1sort/../ :/^t12:/+1,/^t13/-1sort/../u :/^t13:/+1,/^t14/-1sort/./n :/^t14:/+1,/^t15/-1sort/./r :/^t15:/+1,/^t16/-1sort/../r :/^t16:/+1,/^t17/-1sort/./rn :/^t17:/+1,/^t18/-1sort/\d/ :/^t18:/+1,/^t19/-1sort/\d/r :/^t19:/+1,/^t20/-1sort/\d/n :/^t20:/+1,/^t21/-1sort/\d/rn :/^t21:/+1,/^t22/-1sort/\d\d/ :/^t22:/+1,/^t23/-1sort/\d\d/n :/^t23:/+1,/^t24/-1sort/\d\d/x :/^t24:/+1,/^t25/-1sort/\d\d/r :/^t25:/+1,/^t26/-1sort/\d\d/rn :/^t26:/+1,/^t27/-1sort/\d\d/rx :/^t27:/+1,/^t28/-1sort no :/^t01:/,$wq! test.out ENDTEST t01: alphebetical abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t02: numeric abc ab a321 a123 a122 a x-22 b321 b123 c123d -24 123b c321d 0 b322b b321 b321b t03: hexadecimal abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t04: alpha, unique abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t05: alpha, reverse abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t06: numeric, reverse abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t07: unique, reverse abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t08: octal abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t09: reverse, hexadecimal abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t10: alpha, skip first character abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t11: alpha, skip first 2 characters abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t12: alpha, unique, skip first 2 characters abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t13: numeric, skip first character abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t14: alpha, sort on first character abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t15: alpha, sort on first 2 characters abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t16: numeric, sort on first character abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t17: alpha, skip past first digit abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t18: alpha, sort on first digit abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t19: numeric, skip past first digit abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t20: numeric, sort on first digit abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t21: alpha, skip past first 2 digits abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t22: numeric, skip past first 2 digits abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t23: hexadecimal, skip past first 2 digits abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t24: alpha, sort on first 2 digits abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t25: numeric, sort on first 2 digits abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t26: hexadecimal, sort on first 2 digits abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t27: wrong arguments abc ab a a321 a123 a122 b321 b123 c123d 123b c321d b322b b321 b321b t28: done
zyz2011-vim
src/testdir/test57.in
Vim Script
gpl2
3,666
:" Script to make sure a file is in "dos" file format. :set ff=dos :wq
zyz2011-vim
src/testdir/todos.vim
Vim Script
gpl2
71
# # Makefile to run all tests for Vim, on OS/2 # # Requires a set of Unix tools: echo, diff, etc. VIMPROG = ../vim.exe # Omitted: # test2 "\\tmp" doesn't work. # test10 'errorformat' is different # test11 requires sed # test12 can't unlink a swap file # test25 uses symbolic link # test27 can't edit file with "*" in file name # test52 only for Win32 # test85 no Lua interface SCRIPTS = test1.out test3.out test4.out test5.out test6.out \ test7.out test8.out test9.out \ test13.out test14.out test15.out test17.out \ test18.out test19.out test20.out test21.out test22.out \ test23.out test24.out test26.out \ test28.out test29.out test30.out test31.out test32.out \ test33.out test34.out test35.out test36.out test37.out \ test38.out test39.out test40.out test41.out test42.out \ test43.out test44.out test45.out test46.out test47.out \ test48.out test51.out test53.out test54.out test55.out \ test56.out test57.out test58.out test59.out test60.out \ test61.out test62.out test63.out test64.out test65.out \ test66.out test67.out test68.out test69.out test70.out \ test71.out test72.out test73.out test74.out test75.out \ test76.out test77.out test78.out test79.out test80.out \ test81.out test82.out test83.out test84.out .SUFFIXES: .in .out all: /tmp $(SCRIPTS) @echo ALL DONE $(SCRIPTS): $(VIMPROG) clean: -rm -rf *.out Xdotest test.ok tiny.vim small.vim mbyte.vim viminfo # Make sure all .in and .out files are in DOS fileformat. .in.out: $(VIMPROG) -u NONE -s todos.vim $*.in $(VIMPROG) -u NONE -s todos.vim $*.ok copy $*.ok test.ok $(VIMPROG) -u os2.vim --noplugin -s dotest.in $*.in $(VIMPROG) -u NONE -s todos.vim test.out diff test.out $*.ok rename test.out $*.out -rm -rf X* viminfo -del test.ok # Create a directory for temp files /tmp: -mkdir /tmp
zyz2011-vim
src/testdir/Make_os2.mak
Makefile
gpl2
1,812
Tests for folding. vim: set ft=vim : STARTTEST :so small.vim :" We also need the +syntax feature here. :if !has("syntax") e! test.ok w! test.out qa! :endif :" basic test if a fold can be created, opened, moving to the end and closed /^1 zf2j:call append("$", "manual " . getline(foldclosed("."))) zo:call append("$", foldclosed(".")) ]z:call append("$", getline(".")) zc:call append("$", getline(foldclosed("."))) :" test folding with markers. :set fdm=marker fdl=1 fdc=3 /^5 :call append("$", "marker " . foldlevel(".")) [z:call append("$", foldlevel(".")) jo{{ r{jj:call append("$", foldlevel(".")) kYpj:call append("$", foldlevel(".")) :" test folding with indent :set fdm=indent sw=2 /^2 b i jI :call append("$", "indent " . foldlevel(".")) k:call append("$", foldlevel(".")) :" test syntax folding :set fdm=syntax fdl=0 :syn region Hup start="dd" end="ii" fold contains=Fd1,Fd2,Fd3 :syn region Fd1 start="ee" end="ff" fold contained :syn region Fd2 start="gg" end="hh" fold contained :syn region Fd3 start="commentstart" end="commentend" fold contained Gzk:call append("$", "folding " . getline(".")) k:call append("$", getline(".")) jAcommentstart Acommentend:set fdl=1 3j:call append("$", getline(".")) :set fdl=0 zO j:call append("$", getline(".")) :" test expression folding :fun Flvl() let l = getline(v:lnum) if l =~ "bb$" return 2 elseif l =~ "gg$" return "s1" elseif l =~ "ii$" return ">2" elseif l =~ "kk$" return "0" endif return "=" endfun :set fdm=expr fde=Flvl() /bb$ :call append("$", "expr " . foldlevel(".")) /hh$ :call append("$", foldlevel(".")) /ii$ :call append("$", foldlevel(".")) /kk$ :call append("$", foldlevel(".")) :/^last/+1,$w! test.out :delfun Flvl :qa! ENDTEST 1 aa 2 bb 3 cc 4 dd {{{ 5 ee {{{ }}} 6 ff }}} 7 gg 8 hh 9 ii a jj b kk last
zyz2011-vim
src/testdir/test45.in
Vim Script
gpl2
1,824
Tests for the exists() function. vim: set ft=vim : STARTTEST :so small.vim :function! RunTest(str, result) if exists(a:str) == a:result echo "OK" else echo "FAILED: Checking for " . a:str endif endfunction :function! TestExists() augroup myagroup autocmd! BufEnter *.my echo 'myfile edited' augroup END let test_cases = [] " valid autocmd group let test_cases += [['#myagroup', 1]] " valid autocmd group with garbage let test_cases += [['#myagroup+b', 0]] " Valid autocmd group and event let test_cases += [['#myagroup#BufEnter', 1]] " Valid autocmd group, event and pattern let test_cases += [['#myagroup#BufEnter#*.my', 1]] " Valid autocmd event let test_cases += [['#BufEnter', 1]] " Valid autocmd event and pattern let test_cases += [['#BufEnter#*.my', 1]] " Non-existing autocmd group or event let test_cases += [['#xyzagroup', 0]] " Non-existing autocmd group and valid autocmd event let test_cases += [['#xyzagroup#BufEnter', 0]] " Valid autocmd group and event with no matching pattern let test_cases += [['#myagroup#CmdwinEnter', 0]] " Valid autocmd group and non-existing autocmd event let test_cases += [['#myagroup#xyzacmd', 0]] " Valid autocmd group and event and non-matching pattern let test_cases += [['#myagroup#BufEnter#xyzpat', 0]] " Valid autocmd event and non-matching pattern let test_cases += [['#BufEnter#xyzpat', 0]] " Empty autocmd group, event and pattern let test_cases += [['###', 0]] " Empty autocmd group and event or empty event and pattern let test_cases += [['##', 0]] " Valid autocmd event let test_cases += [['##FileReadCmd', 1]] " Non-existing autocmd event let test_cases += [['##MySpecialCmd', 0]] " Existing and working option (long form) let test_cases += [['&textwidth', 1]] " Existing and working option (short form) let test_cases += [['&tw', 1]] " Existing and working option with garbage let test_cases += [['&tw-', 0]] " Global option let test_cases += [['&g:errorformat', 1]] " Local option let test_cases += [['&l:errorformat', 1]] " Negative form of existing and working option (long form) let test_cases += [['&nojoinspaces', 0]] " Negative form of existing and working option (short form) let test_cases += [['&nojs', 0]] " Non-existing option let test_cases += [['&myxyzoption', 0]] " Existing and working option (long form) let test_cases += [['+incsearch', 1]] " Existing and working option with garbage let test_cases += [['+incsearch!1', 0]] " Existing and working option (short form) let test_cases += [['+is', 1]] " Existing option that is hidden. let test_cases += [['+autoprint', 0]] " Existing environment variable let $EDITOR_NAME = 'Vim Editor' let test_cases += [['$EDITOR_NAME', 1]] " Non-existing environment variable let test_cases += [['$NON_ENV_VAR', 0]] " Valid internal function let test_cases += [['*bufnr', 1]] " Valid internal function with () let test_cases += [['*bufnr()', 1]] " Non-existing internal function let test_cases += [['*myxyzfunc', 0]] " Valid internal function with garbage let test_cases += [['*bufnr&6', 0]] " Valid user defined function let test_cases += [['*TestExists', 1]] " Non-existing user defined function let test_cases += [['*MyxyzFunc', 0]] redir! > test.out for [test_case, result] in test_cases echo test_case . ": " . result call RunTest(test_case, result) endfor " Valid internal command (full match) echo ':edit: 2' if exists(':edit') == 2 echo "OK" else echo "FAILED" endif " Valid internal command (full match) with garbage echo ':edit/a: 0' if exists(':edit/a') == 0 echo "OK" else echo "FAILED" endif " Valid internal command (partial match) echo ':q: 1' if exists(':q') == 1 echo "OK" else echo "FAILED" endif " Non-existing internal command echo ':invalidcmd: 0' if !exists(':invalidcmd') echo "OK" else echo "FAILED" endif " User defined command (full match) command! MyCmd :echo 'My command' echo ':MyCmd: 2' if exists(':MyCmd') == 2 echo "OK" else echo "FAILED" endif " User defined command (partial match) command! MyOtherCmd :echo 'Another command' echo ':My: 3' if exists(':My') == 3 echo "OK" else echo "FAILED" endif " Command modifier echo ':rightbelow: 2' if exists(':rightbelow') == 2 echo "OK" else echo "FAILED" endif " Non-existing user defined command (full match) delcommand MyCmd echo ':MyCmd: 0' if !exists(':MyCmd') echo "OK" else echo "FAILED" endif " Non-existing user defined command (partial match) delcommand MyOtherCmd echo ':My: 0' if !exists(':My') echo "OK" else echo "FAILED" endif " Valid local variable let local_var = 1 echo 'local_var: 1' if exists('local_var') echo "OK" else echo "FAILED" endif " Valid local variable with garbage let local_var = 1 echo 'local_var%n: 0' if !exists('local_var%n') echo "OK" else echo "FAILED" endif " Non-existing local variable unlet local_var echo 'local_var: 0' if !exists('local_var') echo "OK" else echo "FAILED" endif " Valid local list let local_list = ["blue", "orange"] echo 'local_list: 1' if exists('local_list') echo "OK" else echo "FAILED" endif " Valid local list item echo 'local_list[1]: 1' if exists('local_list[1]') echo "OK" else echo "FAILED" endif " Valid local list item with garbage echo 'local_list[1]+5: 0' if !exists('local_list[1]+5') echo "OK" else echo "FAILED" endif " Invalid local list item echo 'local_list[2]: 0' if !exists('local_list[2]') echo "OK" else echo "FAILED" endif " Non-existing local list unlet local_list echo 'local_list: 0' if !exists('local_list') echo "OK" else echo "FAILED" endif " Valid local dictionary let local_dict = {"xcord":100, "ycord":2} echo 'local_dict: 1' if exists('local_dict') echo "OK" else echo "FAILED" endif " Non-existing local dictionary unlet local_dict echo 'local_dict: 0' if !exists('local_dict') echo "OK" else echo "FAILED" endif " Existing local curly-brace variable let str = "local" let curly_{str}_var = 1 echo 'curly_' . str . '_var: 1' if exists('curly_{str}_var') echo "OK" else echo "FAILED" endif " Non-existing local curly-brace variable unlet curly_{str}_var echo 'curly_' . str . '_var: 0' if !exists('curly_{str}_var') echo "OK" else echo "FAILED" endif " Existing global variable let g:global_var = 1 echo 'g:global_var: 1' if exists('g:global_var') echo "OK" else echo "FAILED" endif " Existing global variable with garbage echo 'g:global_var-n: 1' if !exists('g:global_var-n') echo "OK" else echo "FAILED" endif " Non-existing global variable unlet g:global_var echo 'g:global_var: 0' if !exists('g:global_var') echo "OK" else echo "FAILED" endif " Existing global list let g:global_list = ["blue", "orange"] echo 'g:global_list: 1' if exists('g:global_list') echo "OK" else echo "FAILED" endif " Non-existing global list unlet g:global_list echo 'g:global_list: 0' if !exists('g:global_list') echo "OK" else echo "FAILED" endif " Existing global dictionary let g:global_dict = {"xcord":100, "ycord":2} echo 'g:global_dict: 1' if exists('g:global_dict') echo "OK" else echo "FAILED" endif " Non-existing global dictionary unlet g:global_dict echo 'g:global_dict: 0' if !exists('g:global_dict') echo "OK" else echo "FAILED" endif " Existing global curly-brace variable let str = "global" let g:curly_{str}_var = 1 echo 'g:curly_' . str . '_var: 1' if exists('g:curly_{str}_var') echo "OK" else echo "FAILED" endif " Non-existing global curly-brace variable unlet g:curly_{str}_var echo 'g:curly_' . str . '_var: 0' if !exists('g:curly_{str}_var') echo "OK" else echo "FAILED" endif " Existing window variable echo 'w:window_var: 1' let w:window_var = 1 if exists('w:window_var') echo "OK" else echo "FAILED" endif " Non-existing window variable unlet w:window_var echo 'w:window_var: 0' if !exists('w:window_var') echo "OK" else echo "FAILED" endif " Existing window list let w:window_list = ["blue", "orange"] echo 'w:window_list: 1' if exists('w:window_list') echo "OK" else echo "FAILED" endif " Non-existing window list unlet w:window_list echo 'w:window_list: 0' if !exists('w:window_list') echo "OK" else echo "FAILED" endif " Existing window dictionary let w:window_dict = {"xcord":100, "ycord":2} echo 'w:window_dict: 1' if exists('w:window_dict') echo "OK" else echo "FAILED" endif " Non-existing window dictionary unlet w:window_dict echo 'w:window_dict: 0' if !exists('w:window_dict') echo "OK" else echo "FAILED" endif " Existing window curly-brace variable let str = "window" let w:curly_{str}_var = 1 echo 'w:curly_' . str . '_var: 1' if exists('w:curly_{str}_var') echo "OK" else echo "FAILED" endif " Non-existing window curly-brace variable unlet w:curly_{str}_var echo 'w:curly_' . str . '_var: 0' if !exists('w:curly_{str}_var') echo "OK" else echo "FAILED" endif " Existing buffer variable echo 'b:buffer_var: 1' let b:buffer_var = 1 if exists('b:buffer_var') echo "OK" else echo "FAILED" endif " Non-existing buffer variable unlet b:buffer_var echo 'b:buffer_var: 0' if !exists('b:buffer_var') echo "OK" else echo "FAILED" endif " Existing buffer list let b:buffer_list = ["blue", "orange"] echo 'b:buffer_list: 1' if exists('b:buffer_list') echo "OK" else echo "FAILED" endif " Non-existing buffer list unlet b:buffer_list echo 'b:buffer_list: 0' if !exists('b:buffer_list') echo "OK" else echo "FAILED" endif " Existing buffer dictionary let b:buffer_dict = {"xcord":100, "ycord":2} echo 'b:buffer_dict: 1' if exists('b:buffer_dict') echo "OK" else echo "FAILED" endif " Non-existing buffer dictionary unlet b:buffer_dict echo 'b:buffer_dict: 0' if !exists('b:buffer_dict') echo "OK" else echo "FAILED" endif " Existing buffer curly-brace variable let str = "buffer" let b:curly_{str}_var = 1 echo 'b:curly_' . str . '_var: 1' if exists('b:curly_{str}_var') echo "OK" else echo "FAILED" endif " Non-existing buffer curly-brace variable unlet b:curly_{str}_var echo 'b:curly_' . str . '_var: 0' if !exists('b:curly_{str}_var') echo "OK" else echo "FAILED" endif " Script-local tests source test60.vim " Existing Vim internal variable echo 'v:version: 1' if exists('v:version') echo "OK" else echo "FAILED" endif " Non-existing Vim internal variable echo 'v:non_exists_var: 0' if !exists('v:non_exists_var') echo "OK" else echo "FAILED" endif " Function arguments function TestFuncArg(func_arg, ...) echo 'a:func_arg: 1' if exists('a:func_arg') echo "OK" else echo "FAILED" endif echo 'a:non_exists_arg: 0' if !exists('a:non_exists_arg') echo "OK" else echo "FAILED" endif echo 'a:1: 1' if exists('a:1') echo "OK" else echo "FAILED" endif echo 'a:2: 0' if !exists('a:2') echo "OK" else echo "FAILED" endif endfunction call TestFuncArg("arg1", "arg2") redir END endfunction :call TestExists() :delfunc TestExists :delfunc RunTest :delfunc TestFuncArg :edit! test.out :set ff=unix :w :qa! ENDTEST
zyz2011-vim
src/testdir/test60.in
Vim Script
gpl2
12,483
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. */ /* * This file defines the Ex commands. * When DO_DECLARE_EXCMD is defined, the table with ex command names and * options results. * When DO_DECLARE_EXCMD is NOT defined, the enum with all the Ex commands * results. * This clever trick was invented by Ron Aaron. */ /* * When adding an Ex command: * 1. Add an entry in the table below. Keep it sorted on the shortest * version of the command name that works. If it doesn't start with a * lower case letter, add it at the end. * 2. Add a "case: CMD_xxx" in the big switch in ex_docmd.c. * 3. Add an entry in the index for Ex commands at ":help ex-cmd-index". * 4. Add documentation in ../doc/xxx.txt. Add a tag for both the short and * long name of the command. */ #ifdef RANGE # undef RANGE /* SASC on Amiga defines it */ #endif #define RANGE 0x001 /* allow a linespecs */ #define BANG 0x002 /* allow a ! after the command name */ #define EXTRA 0x004 /* allow extra args after command name */ #define XFILE 0x008 /* expand wildcards in extra part */ #define NOSPC 0x010 /* no spaces allowed in the extra part */ #define DFLALL 0x020 /* default file range is 1,$ */ #define WHOLEFOLD 0x040 /* extend range to include whole fold also when less than two numbers given */ #define NEEDARG 0x080 /* argument required */ #define TRLBAR 0x100 /* check for trailing vertical bar */ #define REGSTR 0x200 /* allow "x for register designation */ #define COUNT 0x400 /* allow count in argument, after command */ #define NOTRLCOM 0x800 /* no trailing comment allowed */ #define ZEROR 0x1000 /* zero line number allowed */ #define USECTRLV 0x2000 /* do not remove CTRL-V from argument */ #define NOTADR 0x4000 /* number before command is not an address */ #define EDITCMD 0x8000 /* allow "+command" argument */ #define BUFNAME 0x10000L /* accepts buffer name */ #define BUFUNL 0x20000L /* accepts unlisted buffer too */ #define ARGOPT 0x40000L /* allow "++opt=val" argument */ #define SBOXOK 0x80000L /* allowed in the sandbox */ #define CMDWIN 0x100000L /* allowed in cmdline window */ #define MODIFY 0x200000L /* forbidden in non-'modifiable' buffer */ #define EXFLAGS 0x400000L /* allow flags after count in argument */ #define FILES (XFILE | EXTRA) /* multiple extra files allowed */ #define WORD1 (EXTRA | NOSPC) /* one extra word allowed */ #define FILE1 (FILES | NOSPC) /* 1 file allowed, defaults to current file */ #ifndef DO_DECLARE_EXCMD typedef struct exarg exarg_T; #endif /* * This array maps ex command names to command codes. * The order in which command names are listed below is significant -- * ambiguous abbreviations are always resolved to be the first possible match * (e.g. "r" is taken to mean "read", not "rewind", because "read" comes * before "rewind"). * Not supported commands are included to avoid ambiguities. */ #ifdef EX # undef EX /* just in case */ #endif #ifdef DO_DECLARE_EXCMD # define EX(a, b, c, d) {(char_u *)b, c, (long_u)(d)} typedef void (*ex_func_T) __ARGS((exarg_T *eap)); static struct cmdname { char_u *cmd_name; /* name of the command */ ex_func_T cmd_func; /* function for this command */ long_u cmd_argt; /* flags declared above */ } # if defined(FEAT_GUI_W16) _far # endif cmdnames[] = #else # define EX(a, b, c, d) a enum CMD_index #endif { EX(CMD_append, "append", ex_append, BANG|RANGE|ZEROR|TRLBAR|CMDWIN|MODIFY), EX(CMD_abbreviate, "abbreviate", ex_abbreviate, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_abclear, "abclear", ex_abclear, EXTRA|TRLBAR|CMDWIN), EX(CMD_aboveleft, "aboveleft", ex_wrongmodifier, NEEDARG|EXTRA|NOTRLCOM), EX(CMD_all, "all", ex_all, BANG|RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_amenu, "amenu", ex_menu, RANGE|NOTADR|ZEROR|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_anoremenu, "anoremenu", ex_menu, RANGE|NOTADR|ZEROR|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_args, "args", ex_args, BANG|FILES|EDITCMD|ARGOPT|TRLBAR), EX(CMD_argadd, "argadd", ex_argadd, BANG|NEEDARG|RANGE|NOTADR|ZEROR|FILES|TRLBAR), EX(CMD_argdelete, "argdelete", ex_argdelete, BANG|RANGE|NOTADR|FILES|TRLBAR), EX(CMD_argdo, "argdo", ex_listdo, BANG|NEEDARG|EXTRA|NOTRLCOM), EX(CMD_argedit, "argedit", ex_argedit, BANG|NEEDARG|RANGE|NOTADR|FILE1|EDITCMD|ARGOPT|TRLBAR), EX(CMD_argglobal, "argglobal", ex_args, BANG|FILES|EDITCMD|ARGOPT|TRLBAR), EX(CMD_arglocal, "arglocal", ex_args, BANG|FILES|EDITCMD|ARGOPT|TRLBAR), EX(CMD_argument, "argument", ex_argument, BANG|RANGE|NOTADR|COUNT|EXTRA|EDITCMD|ARGOPT|TRLBAR), EX(CMD_ascii, "ascii", do_ascii, TRLBAR|SBOXOK|CMDWIN), EX(CMD_autocmd, "autocmd", ex_autocmd, BANG|EXTRA|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_augroup, "augroup", ex_autocmd, BANG|WORD1|TRLBAR|CMDWIN), EX(CMD_aunmenu, "aunmenu", ex_menu, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_buffer, "buffer", ex_buffer, BANG|RANGE|NOTADR|BUFNAME|BUFUNL|COUNT|EXTRA|TRLBAR), EX(CMD_bNext, "bNext", ex_bprevious, BANG|RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_ball, "ball", ex_buffer_all, RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_badd, "badd", ex_edit, NEEDARG|FILE1|EDITCMD|TRLBAR|CMDWIN), EX(CMD_bdelete, "bdelete", ex_bunload, BANG|RANGE|NOTADR|BUFNAME|COUNT|EXTRA|TRLBAR), EX(CMD_behave, "behave", ex_behave, NEEDARG|WORD1|TRLBAR|CMDWIN), EX(CMD_belowright, "belowright", ex_wrongmodifier, NEEDARG|EXTRA|NOTRLCOM), EX(CMD_bfirst, "bfirst", ex_brewind, BANG|RANGE|NOTADR|TRLBAR), EX(CMD_blast, "blast", ex_blast, BANG|RANGE|NOTADR|TRLBAR), EX(CMD_bmodified, "bmodified", ex_bmodified, BANG|RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_bnext, "bnext", ex_bnext, BANG|RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_botright, "botright", ex_wrongmodifier, NEEDARG|EXTRA|NOTRLCOM), EX(CMD_bprevious, "bprevious", ex_bprevious, BANG|RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_brewind, "brewind", ex_brewind, BANG|RANGE|NOTADR|TRLBAR), EX(CMD_break, "break", ex_break, TRLBAR|SBOXOK|CMDWIN), EX(CMD_breakadd, "breakadd", ex_breakadd, EXTRA|TRLBAR|CMDWIN), EX(CMD_breakdel, "breakdel", ex_breakdel, EXTRA|TRLBAR|CMDWIN), EX(CMD_breaklist, "breaklist", ex_breaklist, EXTRA|TRLBAR|CMDWIN), EX(CMD_browse, "browse", ex_wrongmodifier, NEEDARG|EXTRA|NOTRLCOM|CMDWIN), EX(CMD_buffers, "buffers", buflist_list, BANG|TRLBAR|CMDWIN), EX(CMD_bufdo, "bufdo", ex_listdo, BANG|NEEDARG|EXTRA|NOTRLCOM), EX(CMD_bunload, "bunload", ex_bunload, BANG|RANGE|NOTADR|BUFNAME|COUNT|EXTRA|TRLBAR), EX(CMD_bwipeout, "bwipeout", ex_bunload, BANG|RANGE|NOTADR|BUFNAME|BUFUNL|COUNT|EXTRA|TRLBAR), EX(CMD_change, "change", ex_change, BANG|WHOLEFOLD|RANGE|COUNT|TRLBAR|CMDWIN|MODIFY), EX(CMD_cNext, "cNext", ex_cnext, RANGE|NOTADR|COUNT|TRLBAR|BANG), EX(CMD_cNfile, "cNfile", ex_cnext, RANGE|NOTADR|COUNT|TRLBAR|BANG), EX(CMD_cabbrev, "cabbrev", ex_abbreviate, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_cabclear, "cabclear", ex_abclear, EXTRA|TRLBAR|CMDWIN), EX(CMD_caddbuffer, "caddbuffer", ex_cbuffer, RANGE|NOTADR|WORD1|TRLBAR), EX(CMD_caddexpr, "caddexpr", ex_cexpr, NEEDARG|WORD1|NOTRLCOM|TRLBAR), EX(CMD_caddfile, "caddfile", ex_cfile, TRLBAR|FILE1), EX(CMD_call, "call", ex_call, RANGE|NEEDARG|EXTRA|NOTRLCOM|SBOXOK|CMDWIN), EX(CMD_catch, "catch", ex_catch, EXTRA|SBOXOK|CMDWIN), EX(CMD_cbuffer, "cbuffer", ex_cbuffer, BANG|RANGE|NOTADR|WORD1|TRLBAR), EX(CMD_cc, "cc", ex_cc, RANGE|NOTADR|COUNT|TRLBAR|BANG), EX(CMD_cclose, "cclose", ex_cclose, RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_cd, "cd", ex_cd, BANG|FILE1|TRLBAR|CMDWIN), EX(CMD_center, "center", ex_align, TRLBAR|RANGE|WHOLEFOLD|EXTRA|CMDWIN|MODIFY), EX(CMD_cexpr, "cexpr", ex_cexpr, NEEDARG|WORD1|NOTRLCOM|TRLBAR|BANG), EX(CMD_cfile, "cfile", ex_cfile, TRLBAR|FILE1|BANG), EX(CMD_cfirst, "cfirst", ex_cc, RANGE|NOTADR|COUNT|TRLBAR|BANG), EX(CMD_cgetfile, "cgetfile", ex_cfile, TRLBAR|FILE1), EX(CMD_cgetbuffer, "cgetbuffer", ex_cbuffer, RANGE|NOTADR|WORD1|TRLBAR), EX(CMD_cgetexpr, "cgetexpr", ex_cexpr, NEEDARG|WORD1|NOTRLCOM|TRLBAR), EX(CMD_chdir, "chdir", ex_cd, BANG|FILE1|TRLBAR|CMDWIN), EX(CMD_changes, "changes", ex_changes, TRLBAR|CMDWIN), EX(CMD_checkpath, "checkpath", ex_checkpath, TRLBAR|BANG|CMDWIN), EX(CMD_checktime, "checktime", ex_checktime, RANGE|NOTADR|BUFNAME|COUNT|EXTRA|TRLBAR), EX(CMD_clist, "clist", qf_list, BANG|EXTRA|TRLBAR|CMDWIN), EX(CMD_clast, "clast", ex_cc, RANGE|NOTADR|COUNT|TRLBAR|BANG), EX(CMD_close, "close", ex_close, BANG|TRLBAR|CMDWIN), EX(CMD_cmap, "cmap", ex_map, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_cmapclear, "cmapclear", ex_mapclear, EXTRA|TRLBAR|CMDWIN), EX(CMD_cmenu, "cmenu", ex_menu, RANGE|NOTADR|ZEROR|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_cnext, "cnext", ex_cnext, RANGE|NOTADR|COUNT|TRLBAR|BANG), EX(CMD_cnewer, "cnewer", qf_age, RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_cnfile, "cnfile", ex_cnext, RANGE|NOTADR|COUNT|TRLBAR|BANG), EX(CMD_cnoremap, "cnoremap", ex_map, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_cnoreabbrev, "cnoreabbrev", ex_abbreviate, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_cnoremenu, "cnoremenu", ex_menu, RANGE|NOTADR|ZEROR|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_copy, "copy", ex_copymove, RANGE|WHOLEFOLD|EXTRA|TRLBAR|CMDWIN|MODIFY), EX(CMD_colder, "colder", qf_age, RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_colorscheme, "colorscheme", ex_colorscheme, WORD1|TRLBAR|CMDWIN), EX(CMD_command, "command", ex_command, EXTRA|BANG|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_comclear, "comclear", ex_comclear, TRLBAR|CMDWIN), EX(CMD_compiler, "compiler", ex_compiler, BANG|TRLBAR|WORD1|CMDWIN), EX(CMD_continue, "continue", ex_continue, TRLBAR|SBOXOK|CMDWIN), EX(CMD_confirm, "confirm", ex_wrongmodifier, NEEDARG|EXTRA|NOTRLCOM|CMDWIN), EX(CMD_copen, "copen", ex_copen, RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_cprevious, "cprevious", ex_cnext, RANGE|NOTADR|COUNT|TRLBAR|BANG), EX(CMD_cpfile, "cpfile", ex_cnext, RANGE|NOTADR|COUNT|TRLBAR|BANG), EX(CMD_cquit, "cquit", ex_cquit, TRLBAR|BANG), EX(CMD_crewind, "crewind", ex_cc, RANGE|NOTADR|COUNT|TRLBAR|BANG), EX(CMD_cscope, "cscope", do_cscope, EXTRA|NOTRLCOM|XFILE), EX(CMD_cstag, "cstag", do_cstag, BANG|TRLBAR|WORD1), EX(CMD_cunmap, "cunmap", ex_unmap, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_cunabbrev, "cunabbrev", ex_abbreviate, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_cunmenu, "cunmenu", ex_menu, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_cwindow, "cwindow", ex_cwindow, RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_delete, "delete", ex_operators, RANGE|WHOLEFOLD|REGSTR|COUNT|TRLBAR|CMDWIN|MODIFY), EX(CMD_delmarks, "delmarks", ex_delmarks, BANG|EXTRA|TRLBAR|CMDWIN), EX(CMD_debug, "debug", ex_debug, NEEDARG|EXTRA|NOTRLCOM|SBOXOK|CMDWIN), EX(CMD_debuggreedy, "debuggreedy", ex_debuggreedy, RANGE|NOTADR|ZEROR|TRLBAR|CMDWIN), EX(CMD_delcommand, "delcommand", ex_delcommand, NEEDARG|WORD1|TRLBAR|CMDWIN), EX(CMD_delfunction, "delfunction", ex_delfunction, NEEDARG|WORD1|CMDWIN), EX(CMD_display, "display", ex_display, EXTRA|NOTRLCOM|TRLBAR|SBOXOK|CMDWIN), EX(CMD_diffupdate, "diffupdate", ex_diffupdate, BANG|TRLBAR), EX(CMD_diffget, "diffget", ex_diffgetput, RANGE|EXTRA|TRLBAR|MODIFY), EX(CMD_diffoff, "diffoff", ex_diffoff, BANG|TRLBAR), EX(CMD_diffpatch, "diffpatch", ex_diffpatch, EXTRA|FILE1|TRLBAR|MODIFY), EX(CMD_diffput, "diffput", ex_diffgetput, RANGE|EXTRA|TRLBAR), EX(CMD_diffsplit, "diffsplit", ex_diffsplit, EXTRA|FILE1|TRLBAR), EX(CMD_diffthis, "diffthis", ex_diffthis, TRLBAR), EX(CMD_digraphs, "digraphs", ex_digraphs, EXTRA|TRLBAR|CMDWIN), EX(CMD_djump, "djump", ex_findpat, BANG|RANGE|DFLALL|WHOLEFOLD|EXTRA), EX(CMD_dlist, "dlist", ex_findpat, BANG|RANGE|DFLALL|WHOLEFOLD|EXTRA|CMDWIN), EX(CMD_doautocmd, "doautocmd", ex_doautocmd, EXTRA|TRLBAR|CMDWIN), EX(CMD_doautoall, "doautoall", ex_doautoall, EXTRA|TRLBAR|CMDWIN), EX(CMD_drop, "drop", ex_drop, FILES|EDITCMD|NEEDARG|ARGOPT|TRLBAR), EX(CMD_dsearch, "dsearch", ex_findpat, BANG|RANGE|DFLALL|WHOLEFOLD|EXTRA|CMDWIN), EX(CMD_dsplit, "dsplit", ex_findpat, BANG|RANGE|DFLALL|WHOLEFOLD|EXTRA), EX(CMD_edit, "edit", ex_edit, BANG|FILE1|EDITCMD|ARGOPT|TRLBAR), EX(CMD_earlier, "earlier", ex_later, TRLBAR|EXTRA|NOSPC|CMDWIN), EX(CMD_echo, "echo", ex_echo, EXTRA|NOTRLCOM|SBOXOK|CMDWIN), EX(CMD_echoerr, "echoerr", ex_execute, EXTRA|NOTRLCOM|SBOXOK|CMDWIN), EX(CMD_echohl, "echohl", ex_echohl, EXTRA|TRLBAR|SBOXOK|CMDWIN), EX(CMD_echomsg, "echomsg", ex_execute, EXTRA|NOTRLCOM|SBOXOK|CMDWIN), EX(CMD_echon, "echon", ex_echo, EXTRA|NOTRLCOM|SBOXOK|CMDWIN), EX(CMD_else, "else", ex_else, TRLBAR|SBOXOK|CMDWIN), EX(CMD_elseif, "elseif", ex_else, EXTRA|NOTRLCOM|SBOXOK|CMDWIN), EX(CMD_emenu, "emenu", ex_emenu, NEEDARG|EXTRA|TRLBAR|NOTRLCOM|RANGE|NOTADR|CMDWIN), EX(CMD_endif, "endif", ex_endif, TRLBAR|SBOXOK|CMDWIN), EX(CMD_endfunction, "endfunction", ex_endfunction, TRLBAR|CMDWIN), EX(CMD_endfor, "endfor", ex_endwhile, TRLBAR|SBOXOK|CMDWIN), EX(CMD_endtry, "endtry", ex_endtry, TRLBAR|SBOXOK|CMDWIN), EX(CMD_endwhile, "endwhile", ex_endwhile, TRLBAR|SBOXOK|CMDWIN), EX(CMD_enew, "enew", ex_edit, BANG|TRLBAR), EX(CMD_ex, "ex", ex_edit, BANG|FILE1|EDITCMD|ARGOPT|TRLBAR), EX(CMD_execute, "execute", ex_execute, EXTRA|NOTRLCOM|SBOXOK|CMDWIN), EX(CMD_exit, "exit", ex_exit, RANGE|WHOLEFOLD|BANG|FILE1|ARGOPT|DFLALL|TRLBAR|CMDWIN), EX(CMD_exusage, "exusage", ex_exusage, TRLBAR), EX(CMD_file, "file", ex_file, RANGE|NOTADR|ZEROR|BANG|FILE1|TRLBAR), EX(CMD_files, "files", buflist_list, BANG|TRLBAR|CMDWIN), EX(CMD_filetype, "filetype", ex_filetype, EXTRA|TRLBAR|CMDWIN), EX(CMD_find, "find", ex_find, RANGE|NOTADR|BANG|FILE1|EDITCMD|ARGOPT|TRLBAR), EX(CMD_finally, "finally", ex_finally, TRLBAR|SBOXOK|CMDWIN), EX(CMD_finish, "finish", ex_finish, TRLBAR|SBOXOK|CMDWIN), EX(CMD_first, "first", ex_rewind, EXTRA|BANG|EDITCMD|ARGOPT|TRLBAR), EX(CMD_fixdel, "fixdel", do_fixdel, TRLBAR|CMDWIN), EX(CMD_fold, "fold", ex_fold, RANGE|WHOLEFOLD|TRLBAR|SBOXOK|CMDWIN), EX(CMD_foldclose, "foldclose", ex_foldopen, RANGE|BANG|WHOLEFOLD|TRLBAR|SBOXOK|CMDWIN), EX(CMD_folddoopen, "folddoopen", ex_folddo, RANGE|DFLALL|NEEDARG|EXTRA|NOTRLCOM), EX(CMD_folddoclosed, "folddoclosed", ex_folddo, RANGE|DFLALL|NEEDARG|EXTRA|NOTRLCOM), EX(CMD_foldopen, "foldopen", ex_foldopen, RANGE|BANG|WHOLEFOLD|TRLBAR|SBOXOK|CMDWIN), EX(CMD_for, "for", ex_while, EXTRA|NOTRLCOM|SBOXOK|CMDWIN), EX(CMD_function, "function", ex_function, EXTRA|BANG|CMDWIN), EX(CMD_global, "global", ex_global, RANGE|WHOLEFOLD|BANG|EXTRA|DFLALL|SBOXOK|CMDWIN), EX(CMD_goto, "goto", ex_goto, RANGE|NOTADR|COUNT|TRLBAR|SBOXOK|CMDWIN), EX(CMD_grep, "grep", ex_make, RANGE|NOTADR|BANG|NEEDARG|EXTRA|NOTRLCOM|TRLBAR|XFILE), EX(CMD_grepadd, "grepadd", ex_make, RANGE|NOTADR|BANG|NEEDARG|EXTRA|NOTRLCOM|TRLBAR|XFILE), EX(CMD_gui, "gui", ex_gui, BANG|FILES|EDITCMD|ARGOPT|TRLBAR|CMDWIN), EX(CMD_gvim, "gvim", ex_gui, BANG|FILES|EDITCMD|ARGOPT|TRLBAR|CMDWIN), EX(CMD_help, "help", ex_help, BANG|EXTRA|NOTRLCOM), EX(CMD_helpfind, "helpfind", ex_helpfind, EXTRA|NOTRLCOM), EX(CMD_helpgrep, "helpgrep", ex_helpgrep, EXTRA|NOTRLCOM|NEEDARG), EX(CMD_helptags, "helptags", ex_helptags, NEEDARG|FILES|TRLBAR|CMDWIN), EX(CMD_hardcopy, "hardcopy", ex_hardcopy, RANGE|COUNT|EXTRA|TRLBAR|DFLALL|BANG), EX(CMD_highlight, "highlight", ex_highlight, BANG|EXTRA|TRLBAR|SBOXOK|CMDWIN), EX(CMD_hide, "hide", ex_hide, BANG|EXTRA|NOTRLCOM), EX(CMD_history, "history", ex_history, EXTRA|TRLBAR|CMDWIN), EX(CMD_insert, "insert", ex_append, BANG|RANGE|TRLBAR|CMDWIN|MODIFY), EX(CMD_iabbrev, "iabbrev", ex_abbreviate, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_iabclear, "iabclear", ex_abclear, EXTRA|TRLBAR|CMDWIN), EX(CMD_if, "if", ex_if, EXTRA|NOTRLCOM|SBOXOK|CMDWIN), EX(CMD_ijump, "ijump", ex_findpat, BANG|RANGE|DFLALL|WHOLEFOLD|EXTRA), EX(CMD_ilist, "ilist", ex_findpat, BANG|RANGE|DFLALL|WHOLEFOLD|EXTRA|CMDWIN), EX(CMD_imap, "imap", ex_map, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_imapclear, "imapclear", ex_mapclear, EXTRA|TRLBAR|CMDWIN), EX(CMD_imenu, "imenu", ex_menu, RANGE|NOTADR|ZEROR|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_inoremap, "inoremap", ex_map, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_inoreabbrev, "inoreabbrev", ex_abbreviate, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_inoremenu, "inoremenu", ex_menu, RANGE|NOTADR|ZEROR|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_intro, "intro", ex_intro, TRLBAR|CMDWIN), EX(CMD_isearch, "isearch", ex_findpat, BANG|RANGE|DFLALL|WHOLEFOLD|EXTRA|CMDWIN), EX(CMD_isplit, "isplit", ex_findpat, BANG|RANGE|DFLALL|WHOLEFOLD|EXTRA), EX(CMD_iunmap, "iunmap", ex_unmap, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_iunabbrev, "iunabbrev", ex_abbreviate, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_iunmenu, "iunmenu", ex_menu, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_join, "join", ex_join, BANG|RANGE|WHOLEFOLD|COUNT|EXFLAGS|TRLBAR|CMDWIN|MODIFY), EX(CMD_jumps, "jumps", ex_jumps, TRLBAR|CMDWIN), EX(CMD_k, "k", ex_mark, RANGE|WORD1|TRLBAR|SBOXOK|CMDWIN), EX(CMD_keepmarks, "keepmarks", ex_wrongmodifier, NEEDARG|EXTRA|NOTRLCOM), EX(CMD_keepjumps, "keepjumps", ex_wrongmodifier, NEEDARG|EXTRA|NOTRLCOM), EX(CMD_keepalt, "keepalt", ex_wrongmodifier, NEEDARG|EXTRA|NOTRLCOM), EX(CMD_list, "list", ex_print, RANGE|WHOLEFOLD|COUNT|EXFLAGS|TRLBAR|CMDWIN), EX(CMD_lNext, "lNext", ex_cnext, RANGE|NOTADR|COUNT|TRLBAR|BANG), EX(CMD_lNfile, "lNfile", ex_cnext, RANGE|NOTADR|COUNT|TRLBAR|BANG), EX(CMD_last, "last", ex_last, EXTRA|BANG|EDITCMD|ARGOPT|TRLBAR), EX(CMD_language, "language", ex_language, EXTRA|TRLBAR|CMDWIN), EX(CMD_laddexpr, "laddexpr", ex_cexpr, NEEDARG|WORD1|NOTRLCOM|TRLBAR), EX(CMD_laddbuffer, "laddbuffer", ex_cbuffer, RANGE|NOTADR|WORD1|TRLBAR), EX(CMD_laddfile, "laddfile", ex_cfile, TRLBAR|FILE1), EX(CMD_later, "later", ex_later, TRLBAR|EXTRA|NOSPC|CMDWIN), EX(CMD_lbuffer, "lbuffer", ex_cbuffer, BANG|RANGE|NOTADR|WORD1|TRLBAR), EX(CMD_lcd, "lcd", ex_cd, BANG|FILE1|TRLBAR|CMDWIN), EX(CMD_lchdir, "lchdir", ex_cd, BANG|FILE1|TRLBAR|CMDWIN), EX(CMD_lclose, "lclose", ex_cclose, RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_lcscope, "lcscope", do_cscope, EXTRA|NOTRLCOM|XFILE), EX(CMD_left, "left", ex_align, TRLBAR|RANGE|WHOLEFOLD|EXTRA|CMDWIN|MODIFY), EX(CMD_leftabove, "leftabove", ex_wrongmodifier, NEEDARG|EXTRA|NOTRLCOM), EX(CMD_let, "let", ex_let, EXTRA|NOTRLCOM|SBOXOK|CMDWIN), EX(CMD_lexpr, "lexpr", ex_cexpr, NEEDARG|WORD1|NOTRLCOM|TRLBAR|BANG), EX(CMD_lfile, "lfile", ex_cfile, TRLBAR|FILE1|BANG), EX(CMD_lfirst, "lfirst", ex_cc, RANGE|NOTADR|COUNT|TRLBAR|BANG), EX(CMD_lgetfile, "lgetfile", ex_cfile, TRLBAR|FILE1), EX(CMD_lgetbuffer, "lgetbuffer", ex_cbuffer, RANGE|NOTADR|WORD1|TRLBAR), EX(CMD_lgetexpr, "lgetexpr", ex_cexpr, NEEDARG|WORD1|NOTRLCOM|TRLBAR), EX(CMD_lgrep, "lgrep", ex_make, RANGE|NOTADR|BANG|NEEDARG|EXTRA|NOTRLCOM|TRLBAR|XFILE), EX(CMD_lgrepadd, "lgrepadd", ex_make, RANGE|NOTADR|BANG|NEEDARG|EXTRA|NOTRLCOM|TRLBAR|XFILE), EX(CMD_lhelpgrep, "lhelpgrep", ex_helpgrep, EXTRA|NOTRLCOM|NEEDARG), EX(CMD_ll, "ll", ex_cc, RANGE|NOTADR|COUNT|TRLBAR|BANG), EX(CMD_llast, "llast", ex_cc, RANGE|NOTADR|COUNT|TRLBAR|BANG), EX(CMD_llist, "llist", qf_list, BANG|EXTRA|TRLBAR|CMDWIN), EX(CMD_lmap, "lmap", ex_map, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_lmapclear, "lmapclear", ex_mapclear, EXTRA|TRLBAR|CMDWIN), EX(CMD_lmake, "lmake", ex_make, BANG|EXTRA|NOTRLCOM|TRLBAR|XFILE), EX(CMD_lnoremap, "lnoremap", ex_map, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_lnext, "lnext", ex_cnext, RANGE|NOTADR|COUNT|TRLBAR|BANG), EX(CMD_lnewer, "lnewer", qf_age, RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_lnfile, "lnfile", ex_cnext, RANGE|NOTADR|COUNT|TRLBAR|BANG), EX(CMD_loadview, "loadview", ex_loadview, FILE1|TRLBAR), EX(CMD_loadkeymap, "loadkeymap", ex_loadkeymap, CMDWIN), EX(CMD_lockmarks, "lockmarks", ex_wrongmodifier, NEEDARG|EXTRA|NOTRLCOM), EX(CMD_lockvar, "lockvar", ex_lockvar, BANG|EXTRA|NEEDARG|SBOXOK|CMDWIN), EX(CMD_lolder, "lolder", qf_age, RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_lopen, "lopen", ex_copen, RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_lprevious, "lprevious", ex_cnext, RANGE|NOTADR|COUNT|TRLBAR|BANG), EX(CMD_lpfile, "lpfile", ex_cnext, RANGE|NOTADR|COUNT|TRLBAR|BANG), EX(CMD_lrewind, "lrewind", ex_cc, RANGE|NOTADR|COUNT|TRLBAR|BANG), EX(CMD_ltag, "ltag", ex_tag, NOTADR|TRLBAR|BANG|WORD1), EX(CMD_lua, "lua", ex_lua, RANGE|EXTRA|NEEDARG|CMDWIN), EX(CMD_luado, "luado", ex_luado, RANGE|DFLALL|EXTRA|NEEDARG|CMDWIN), EX(CMD_luafile, "luafile", ex_luafile, RANGE|FILE1|NEEDARG|CMDWIN), EX(CMD_lunmap, "lunmap", ex_unmap, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_lvimgrep, "lvimgrep", ex_vimgrep, RANGE|NOTADR|BANG|NEEDARG|EXTRA|NOTRLCOM|TRLBAR|XFILE), EX(CMD_lvimgrepadd, "lvimgrepadd", ex_vimgrep, RANGE|NOTADR|BANG|NEEDARG|EXTRA|NOTRLCOM|TRLBAR|XFILE), EX(CMD_lwindow, "lwindow", ex_cwindow, RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_ls, "ls", buflist_list, BANG|TRLBAR|CMDWIN), EX(CMD_move, "move", ex_copymove, RANGE|WHOLEFOLD|EXTRA|TRLBAR|CMDWIN|MODIFY), EX(CMD_mark, "mark", ex_mark, RANGE|WORD1|TRLBAR|SBOXOK|CMDWIN), EX(CMD_make, "make", ex_make, BANG|EXTRA|NOTRLCOM|TRLBAR|XFILE), EX(CMD_map, "map", ex_map, BANG|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_mapclear, "mapclear", ex_mapclear, EXTRA|BANG|TRLBAR|CMDWIN), EX(CMD_marks, "marks", do_marks, EXTRA|TRLBAR|CMDWIN), EX(CMD_match, "match", ex_match, RANGE|NOTADR|EXTRA|CMDWIN), EX(CMD_menu, "menu", ex_menu, RANGE|NOTADR|ZEROR|BANG|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_menutranslate, "menutranslate", ex_menutranslate, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_messages, "messages", ex_messages, TRLBAR|CMDWIN), EX(CMD_mkexrc, "mkexrc", ex_mkrc, BANG|FILE1|TRLBAR|CMDWIN), EX(CMD_mksession, "mksession", ex_mkrc, BANG|FILE1|TRLBAR), EX(CMD_mkspell, "mkspell", ex_mkspell, BANG|NEEDARG|EXTRA|NOTRLCOM|TRLBAR|XFILE), EX(CMD_mkvimrc, "mkvimrc", ex_mkrc, BANG|FILE1|TRLBAR|CMDWIN), EX(CMD_mkview, "mkview", ex_mkrc, BANG|FILE1|TRLBAR), EX(CMD_mode, "mode", ex_mode, WORD1|TRLBAR|CMDWIN), EX(CMD_mzscheme, "mzscheme", ex_mzscheme, RANGE|EXTRA|DFLALL|NEEDARG|CMDWIN|SBOXOK), EX(CMD_mzfile, "mzfile", ex_mzfile, RANGE|FILE1|NEEDARG|CMDWIN), EX(CMD_next, "next", ex_next, RANGE|NOTADR|BANG|FILES|EDITCMD|ARGOPT|TRLBAR), EX(CMD_nbkey, "nbkey", ex_nbkey, EXTRA|NOTADR|NEEDARG), EX(CMD_nbclose, "nbclose", ex_nbclose, TRLBAR|CMDWIN), EX(CMD_nbstart, "nbstart", ex_nbstart, WORD1|TRLBAR|CMDWIN), EX(CMD_new, "new", ex_splitview, BANG|FILE1|RANGE|NOTADR|EDITCMD|ARGOPT|TRLBAR), EX(CMD_nmap, "nmap", ex_map, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_nmapclear, "nmapclear", ex_mapclear, EXTRA|TRLBAR|CMDWIN), EX(CMD_nmenu, "nmenu", ex_menu, RANGE|NOTADR|ZEROR|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_nnoremap, "nnoremap", ex_map, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_nnoremenu, "nnoremenu", ex_menu, RANGE|NOTADR|ZEROR|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_noremap, "noremap", ex_map, BANG|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_noautocmd, "noautocmd", ex_wrongmodifier, NEEDARG|EXTRA|NOTRLCOM), EX(CMD_nohlsearch, "nohlsearch", ex_nohlsearch, TRLBAR|SBOXOK|CMDWIN), EX(CMD_noreabbrev, "noreabbrev", ex_abbreviate, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_noremenu, "noremenu", ex_menu, RANGE|NOTADR|ZEROR|BANG|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_normal, "normal", ex_normal, RANGE|BANG|EXTRA|NEEDARG|NOTRLCOM|USECTRLV|SBOXOK|CMDWIN), EX(CMD_number, "number", ex_print, RANGE|WHOLEFOLD|COUNT|EXFLAGS|TRLBAR|CMDWIN), EX(CMD_nunmap, "nunmap", ex_unmap, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_nunmenu, "nunmenu", ex_menu, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_open, "open", ex_open, RANGE|EXTRA), EX(CMD_oldfiles, "oldfiles", ex_oldfiles, BANG|TRLBAR|SBOXOK|CMDWIN), EX(CMD_omap, "omap", ex_map, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_omapclear, "omapclear", ex_mapclear, EXTRA|TRLBAR|CMDWIN), EX(CMD_omenu, "omenu", ex_menu, RANGE|NOTADR|ZEROR|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_only, "only", ex_only, BANG|TRLBAR), EX(CMD_onoremap, "onoremap", ex_map, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_onoremenu, "onoremenu", ex_menu, RANGE|NOTADR|ZEROR|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_options, "options", ex_options, TRLBAR), EX(CMD_ounmap, "ounmap", ex_unmap, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_ounmenu, "ounmenu", ex_menu, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_ownsyntax, "ownsyntax", ex_ownsyntax, EXTRA|NOTRLCOM|SBOXOK|CMDWIN), EX(CMD_print, "print", ex_print, RANGE|WHOLEFOLD|COUNT|EXFLAGS|TRLBAR|CMDWIN|SBOXOK), EX(CMD_pclose, "pclose", ex_pclose, BANG|TRLBAR), EX(CMD_perl, "perl", ex_perl, RANGE|EXTRA|DFLALL|NEEDARG|SBOXOK|CMDWIN), EX(CMD_perldo, "perldo", ex_perldo, RANGE|EXTRA|DFLALL|NEEDARG|CMDWIN), EX(CMD_pedit, "pedit", ex_pedit, BANG|FILE1|EDITCMD|ARGOPT|TRLBAR), EX(CMD_pop, "pop", ex_tag, RANGE|NOTADR|BANG|COUNT|TRLBAR|ZEROR), EX(CMD_popup, "popup", ex_popup, NEEDARG|EXTRA|BANG|TRLBAR|NOTRLCOM|CMDWIN), EX(CMD_ppop, "ppop", ex_ptag, RANGE|NOTADR|BANG|COUNT|TRLBAR|ZEROR), EX(CMD_preserve, "preserve", ex_preserve, TRLBAR), EX(CMD_previous, "previous", ex_previous, EXTRA|RANGE|NOTADR|COUNT|BANG|EDITCMD|ARGOPT|TRLBAR), EX(CMD_promptfind, "promptfind", gui_mch_find_dialog, EXTRA|NOTRLCOM|CMDWIN), EX(CMD_promptrepl, "promptrepl", gui_mch_replace_dialog, EXTRA|NOTRLCOM|CMDWIN), EX(CMD_profile, "profile", ex_profile, BANG|EXTRA|TRLBAR|CMDWIN), EX(CMD_profdel, "profdel", ex_breakdel, EXTRA|TRLBAR|CMDWIN), EX(CMD_psearch, "psearch", ex_psearch, BANG|RANGE|WHOLEFOLD|DFLALL|EXTRA), EX(CMD_ptag, "ptag", ex_ptag, RANGE|NOTADR|BANG|WORD1|TRLBAR|ZEROR), EX(CMD_ptNext, "ptNext", ex_ptag, RANGE|NOTADR|BANG|TRLBAR|ZEROR), EX(CMD_ptfirst, "ptfirst", ex_ptag, RANGE|NOTADR|BANG|TRLBAR|ZEROR), EX(CMD_ptjump, "ptjump", ex_ptag, BANG|TRLBAR|WORD1), EX(CMD_ptlast, "ptlast", ex_ptag, BANG|TRLBAR), EX(CMD_ptnext, "ptnext", ex_ptag, RANGE|NOTADR|BANG|TRLBAR|ZEROR), EX(CMD_ptprevious, "ptprevious", ex_ptag, RANGE|NOTADR|BANG|TRLBAR|ZEROR), EX(CMD_ptrewind, "ptrewind", ex_ptag, RANGE|NOTADR|BANG|TRLBAR|ZEROR), EX(CMD_ptselect, "ptselect", ex_ptag, BANG|TRLBAR|WORD1), EX(CMD_put, "put", ex_put, RANGE|WHOLEFOLD|BANG|REGSTR|TRLBAR|ZEROR|CMDWIN|MODIFY), EX(CMD_pwd, "pwd", ex_pwd, TRLBAR|CMDWIN), EX(CMD_python, "python", ex_python, RANGE|EXTRA|NEEDARG|CMDWIN), EX(CMD_pyfile, "pyfile", ex_pyfile, RANGE|FILE1|NEEDARG|CMDWIN), EX(CMD_py3, "py3", ex_py3, RANGE|EXTRA|NEEDARG|CMDWIN), EX(CMD_python3, "python3", ex_py3, RANGE|EXTRA|NEEDARG|CMDWIN), EX(CMD_py3file, "py3file", ex_py3file, RANGE|FILE1|NEEDARG|CMDWIN), EX(CMD_quit, "quit", ex_quit, BANG|TRLBAR|CMDWIN), EX(CMD_quitall, "quitall", ex_quit_all, BANG|TRLBAR), EX(CMD_qall, "qall", ex_quit_all, BANG|TRLBAR|CMDWIN), EX(CMD_read, "read", ex_read, BANG|RANGE|WHOLEFOLD|FILE1|ARGOPT|TRLBAR|ZEROR|CMDWIN|MODIFY), EX(CMD_recover, "recover", ex_recover, BANG|FILE1|TRLBAR), EX(CMD_redo, "redo", ex_redo, TRLBAR|CMDWIN), EX(CMD_redir, "redir", ex_redir, BANG|FILES|TRLBAR|CMDWIN), EX(CMD_redraw, "redraw", ex_redraw, BANG|TRLBAR|CMDWIN), EX(CMD_redrawstatus, "redrawstatus", ex_redrawstatus, BANG|TRLBAR|CMDWIN), EX(CMD_registers, "registers", ex_display, EXTRA|NOTRLCOM|TRLBAR|CMDWIN), EX(CMD_resize, "resize", ex_resize, RANGE|NOTADR|TRLBAR|WORD1), EX(CMD_retab, "retab", ex_retab, TRLBAR|RANGE|WHOLEFOLD|DFLALL|BANG|WORD1|CMDWIN|MODIFY), EX(CMD_return, "return", ex_return, EXTRA|NOTRLCOM|SBOXOK|CMDWIN), EX(CMD_rewind, "rewind", ex_rewind, EXTRA|BANG|EDITCMD|ARGOPT|TRLBAR), EX(CMD_right, "right", ex_align, TRLBAR|RANGE|WHOLEFOLD|EXTRA|CMDWIN|MODIFY), EX(CMD_rightbelow, "rightbelow", ex_wrongmodifier, NEEDARG|EXTRA|NOTRLCOM), EX(CMD_runtime, "runtime", ex_runtime, BANG|NEEDARG|FILES|TRLBAR|SBOXOK|CMDWIN), EX(CMD_ruby, "ruby", ex_ruby, RANGE|EXTRA|NEEDARG|CMDWIN), EX(CMD_rubydo, "rubydo", ex_rubydo, RANGE|DFLALL|EXTRA|NEEDARG|CMDWIN), EX(CMD_rubyfile, "rubyfile", ex_rubyfile, RANGE|FILE1|NEEDARG|CMDWIN), EX(CMD_rundo, "rundo", ex_rundo, NEEDARG|FILE1), EX(CMD_rviminfo, "rviminfo", ex_viminfo, BANG|FILE1|TRLBAR|CMDWIN), EX(CMD_substitute, "substitute", do_sub, RANGE|WHOLEFOLD|EXTRA|CMDWIN), EX(CMD_sNext, "sNext", ex_previous, EXTRA|RANGE|NOTADR|COUNT|BANG|EDITCMD|ARGOPT|TRLBAR), EX(CMD_sargument, "sargument", ex_argument, BANG|RANGE|NOTADR|COUNT|EXTRA|EDITCMD|ARGOPT|TRLBAR), EX(CMD_sall, "sall", ex_all, BANG|RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_sandbox, "sandbox", ex_wrongmodifier, NEEDARG|EXTRA|NOTRLCOM), EX(CMD_saveas, "saveas", ex_write, BANG|DFLALL|FILE1|ARGOPT|CMDWIN|TRLBAR), EX(CMD_sbuffer, "sbuffer", ex_buffer, BANG|RANGE|NOTADR|BUFNAME|BUFUNL|COUNT|EXTRA|TRLBAR), EX(CMD_sbNext, "sbNext", ex_bprevious, RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_sball, "sball", ex_buffer_all, RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_sbfirst, "sbfirst", ex_brewind, TRLBAR), EX(CMD_sblast, "sblast", ex_blast, TRLBAR), EX(CMD_sbmodified, "sbmodified", ex_bmodified, RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_sbnext, "sbnext", ex_bnext, RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_sbprevious, "sbprevious", ex_bprevious, RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_sbrewind, "sbrewind", ex_brewind, TRLBAR), EX(CMD_scriptnames, "scriptnames", ex_scriptnames, TRLBAR|CMDWIN), EX(CMD_scriptencoding, "scriptencoding", ex_scriptencoding, WORD1|TRLBAR|CMDWIN), EX(CMD_scscope, "scscope", do_scscope, EXTRA|NOTRLCOM), EX(CMD_set, "set", ex_set, TRLBAR|EXTRA|CMDWIN|SBOXOK), EX(CMD_setfiletype, "setfiletype", ex_setfiletype, TRLBAR|EXTRA|NEEDARG|CMDWIN), EX(CMD_setglobal, "setglobal", ex_set, TRLBAR|EXTRA|CMDWIN), EX(CMD_setlocal, "setlocal", ex_set, TRLBAR|EXTRA|CMDWIN), EX(CMD_sfind, "sfind", ex_splitview, BANG|FILE1|RANGE|NOTADR|EDITCMD|ARGOPT|TRLBAR), EX(CMD_sfirst, "sfirst", ex_rewind, EXTRA|BANG|EDITCMD|ARGOPT|TRLBAR), EX(CMD_shell, "shell", ex_shell, TRLBAR|CMDWIN), EX(CMD_simalt, "simalt", ex_simalt, NEEDARG|WORD1|TRLBAR|CMDWIN), EX(CMD_sign, "sign", ex_sign, NEEDARG|RANGE|NOTADR|EXTRA|CMDWIN), EX(CMD_silent, "silent", ex_wrongmodifier, NEEDARG|EXTRA|BANG|NOTRLCOM|SBOXOK|CMDWIN), EX(CMD_sleep, "sleep", ex_sleep, RANGE|NOTADR|COUNT|EXTRA|TRLBAR|CMDWIN), EX(CMD_slast, "slast", ex_last, EXTRA|BANG|EDITCMD|ARGOPT|TRLBAR), EX(CMD_smagic, "smagic", ex_submagic, RANGE|WHOLEFOLD|EXTRA|CMDWIN), EX(CMD_smap, "smap", ex_map, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_smapclear, "smapclear", ex_mapclear, EXTRA|TRLBAR|CMDWIN), EX(CMD_smenu, "smenu", ex_menu, RANGE|NOTADR|ZEROR|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_snext, "snext", ex_next, RANGE|NOTADR|BANG|FILES|EDITCMD|ARGOPT|TRLBAR), EX(CMD_sniff, "sniff", ex_sniff, EXTRA|TRLBAR), EX(CMD_snomagic, "snomagic", ex_submagic, RANGE|WHOLEFOLD|EXTRA|CMDWIN), EX(CMD_snoremap, "snoremap", ex_map, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_snoremenu, "snoremenu", ex_menu, RANGE|NOTADR|ZEROR|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_source, "source", ex_source, BANG|FILE1|TRLBAR|SBOXOK|CMDWIN), EX(CMD_sort, "sort", ex_sort, RANGE|DFLALL|WHOLEFOLD|BANG|EXTRA|NOTRLCOM|MODIFY), EX(CMD_split, "split", ex_splitview, BANG|FILE1|RANGE|NOTADR|EDITCMD|ARGOPT|TRLBAR), EX(CMD_spellgood, "spellgood", ex_spell, BANG|RANGE|NOTADR|NEEDARG|EXTRA|TRLBAR), EX(CMD_spelldump, "spelldump", ex_spelldump, BANG|TRLBAR), EX(CMD_spellinfo, "spellinfo", ex_spellinfo, TRLBAR), EX(CMD_spellrepall, "spellrepall", ex_spellrepall, TRLBAR), EX(CMD_spellundo, "spellundo", ex_spell, BANG|RANGE|NOTADR|NEEDARG|EXTRA|TRLBAR), EX(CMD_spellwrong, "spellwrong", ex_spell, BANG|RANGE|NOTADR|NEEDARG|EXTRA|TRLBAR), EX(CMD_sprevious, "sprevious", ex_previous, EXTRA|RANGE|NOTADR|COUNT|BANG|EDITCMD|ARGOPT|TRLBAR), EX(CMD_srewind, "srewind", ex_rewind, EXTRA|BANG|EDITCMD|ARGOPT|TRLBAR), EX(CMD_stop, "stop", ex_stop, TRLBAR|BANG|CMDWIN), EX(CMD_stag, "stag", ex_stag, RANGE|NOTADR|BANG|WORD1|TRLBAR|ZEROR), EX(CMD_startinsert, "startinsert", ex_startinsert, BANG|TRLBAR|CMDWIN), EX(CMD_startgreplace, "startgreplace", ex_startinsert, BANG|TRLBAR|CMDWIN), EX(CMD_startreplace, "startreplace", ex_startinsert, BANG|TRLBAR|CMDWIN), EX(CMD_stopinsert, "stopinsert", ex_stopinsert, BANG|TRLBAR|CMDWIN), EX(CMD_stjump, "stjump", ex_stag, BANG|TRLBAR|WORD1), EX(CMD_stselect, "stselect", ex_stag, BANG|TRLBAR|WORD1), EX(CMD_sunhide, "sunhide", ex_buffer_all, RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_sunmap, "sunmap", ex_unmap, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_sunmenu, "sunmenu", ex_menu, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_suspend, "suspend", ex_stop, TRLBAR|BANG|CMDWIN), EX(CMD_sview, "sview", ex_splitview, BANG|FILE1|RANGE|NOTADR|EDITCMD|ARGOPT|TRLBAR), EX(CMD_swapname, "swapname", ex_swapname, TRLBAR|CMDWIN), EX(CMD_syntax, "syntax", ex_syntax, EXTRA|NOTRLCOM|CMDWIN), EX(CMD_syncbind, "syncbind", ex_syncbind, TRLBAR), EX(CMD_t, "t", ex_copymove, RANGE|WHOLEFOLD|EXTRA|TRLBAR|CMDWIN|MODIFY), EX(CMD_tNext, "tNext", ex_tag, RANGE|NOTADR|BANG|TRLBAR|ZEROR), EX(CMD_tag, "tag", ex_tag, RANGE|NOTADR|BANG|WORD1|TRLBAR|ZEROR), EX(CMD_tags, "tags", do_tags, TRLBAR|CMDWIN), EX(CMD_tab, "tab", ex_wrongmodifier, NEEDARG|EXTRA|NOTRLCOM), EX(CMD_tabclose, "tabclose", ex_tabclose, RANGE|NOTADR|COUNT|BANG|TRLBAR|CMDWIN), EX(CMD_tabdo, "tabdo", ex_listdo, NEEDARG|EXTRA|NOTRLCOM), EX(CMD_tabedit, "tabedit", ex_splitview, BANG|FILE1|RANGE|NOTADR|ZEROR|EDITCMD|ARGOPT|TRLBAR), EX(CMD_tabfind, "tabfind", ex_splitview, BANG|FILE1|RANGE|NOTADR|ZEROR|EDITCMD|ARGOPT|NEEDARG|TRLBAR), EX(CMD_tabfirst, "tabfirst", ex_tabnext, TRLBAR), EX(CMD_tabmove, "tabmove", ex_tabmove, RANGE|NOTADR|ZEROR|COUNT|TRLBAR|ZEROR), EX(CMD_tablast, "tablast", ex_tabnext, TRLBAR), EX(CMD_tabnext, "tabnext", ex_tabnext, RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_tabnew, "tabnew", ex_splitview, BANG|FILE1|RANGE|NOTADR|ZEROR|EDITCMD|ARGOPT|TRLBAR), EX(CMD_tabonly, "tabonly", ex_tabonly, BANG|TRLBAR|CMDWIN), EX(CMD_tabprevious, "tabprevious", ex_tabnext, RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_tabNext, "tabNext", ex_tabnext, RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_tabrewind, "tabrewind", ex_tabnext, TRLBAR), EX(CMD_tabs, "tabs", ex_tabs, TRLBAR|CMDWIN), EX(CMD_tcl, "tcl", ex_tcl, RANGE|EXTRA|NEEDARG|CMDWIN), EX(CMD_tcldo, "tcldo", ex_tcldo, RANGE|DFLALL|EXTRA|NEEDARG|CMDWIN), EX(CMD_tclfile, "tclfile", ex_tclfile, RANGE|FILE1|NEEDARG|CMDWIN), EX(CMD_tearoff, "tearoff", ex_tearoff, NEEDARG|EXTRA|TRLBAR|NOTRLCOM|CMDWIN), EX(CMD_tfirst, "tfirst", ex_tag, RANGE|NOTADR|BANG|TRLBAR|ZEROR), EX(CMD_throw, "throw", ex_throw, EXTRA|NEEDARG|SBOXOK|CMDWIN), EX(CMD_tjump, "tjump", ex_tag, BANG|TRLBAR|WORD1), EX(CMD_tlast, "tlast", ex_tag, BANG|TRLBAR), EX(CMD_tmenu, "tmenu", ex_menu, RANGE|NOTADR|ZEROR|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_tnext, "tnext", ex_tag, RANGE|NOTADR|BANG|TRLBAR|ZEROR), EX(CMD_topleft, "topleft", ex_wrongmodifier, NEEDARG|EXTRA|NOTRLCOM), EX(CMD_tprevious, "tprevious", ex_tag, RANGE|NOTADR|BANG|TRLBAR|ZEROR), EX(CMD_trewind, "trewind", ex_tag, RANGE|NOTADR|BANG|TRLBAR|ZEROR), EX(CMD_try, "try", ex_try, TRLBAR|SBOXOK|CMDWIN), EX(CMD_tselect, "tselect", ex_tag, BANG|TRLBAR|WORD1), EX(CMD_tunmenu, "tunmenu", ex_menu, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_undo, "undo", ex_undo, RANGE|NOTADR|COUNT|ZEROR|TRLBAR|CMDWIN), EX(CMD_undojoin, "undojoin", ex_undojoin, TRLBAR|CMDWIN), EX(CMD_undolist, "undolist", ex_undolist, TRLBAR|CMDWIN), EX(CMD_unabbreviate, "unabbreviate", ex_abbreviate, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_unhide, "unhide", ex_buffer_all, RANGE|NOTADR|COUNT|TRLBAR), EX(CMD_unlet, "unlet", ex_unlet, BANG|EXTRA|NEEDARG|SBOXOK|CMDWIN), EX(CMD_unlockvar, "unlockvar", ex_lockvar, BANG|EXTRA|NEEDARG|SBOXOK|CMDWIN), EX(CMD_unmap, "unmap", ex_unmap, BANG|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_unmenu, "unmenu", ex_menu, BANG|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_unsilent, "unsilent", ex_wrongmodifier, NEEDARG|EXTRA|NOTRLCOM|SBOXOK|CMDWIN), EX(CMD_update, "update", ex_update, RANGE|WHOLEFOLD|BANG|FILE1|ARGOPT|DFLALL|TRLBAR), EX(CMD_vglobal, "vglobal", ex_global, RANGE|WHOLEFOLD|EXTRA|DFLALL|CMDWIN), EX(CMD_version, "version", ex_version, EXTRA|TRLBAR|CMDWIN), EX(CMD_verbose, "verbose", ex_wrongmodifier, NEEDARG|RANGE|NOTADR|EXTRA|NOTRLCOM|SBOXOK|CMDWIN), EX(CMD_vertical, "vertical", ex_wrongmodifier, NEEDARG|EXTRA|NOTRLCOM), EX(CMD_visual, "visual", ex_edit, BANG|FILE1|EDITCMD|ARGOPT|TRLBAR), EX(CMD_view, "view", ex_edit, BANG|FILE1|EDITCMD|ARGOPT|TRLBAR), EX(CMD_vimgrep, "vimgrep", ex_vimgrep, RANGE|NOTADR|BANG|NEEDARG|EXTRA|NOTRLCOM|TRLBAR|XFILE), EX(CMD_vimgrepadd, "vimgrepadd", ex_vimgrep, RANGE|NOTADR|BANG|NEEDARG|EXTRA|NOTRLCOM|TRLBAR|XFILE), EX(CMD_viusage, "viusage", ex_viusage, TRLBAR), EX(CMD_vmap, "vmap", ex_map, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_vmapclear, "vmapclear", ex_mapclear, EXTRA|TRLBAR|CMDWIN), EX(CMD_vmenu, "vmenu", ex_menu, RANGE|NOTADR|ZEROR|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_vnoremap, "vnoremap", ex_map, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_vnew, "vnew", ex_splitview, BANG|FILE1|RANGE|NOTADR|EDITCMD|ARGOPT|TRLBAR), EX(CMD_vnoremenu, "vnoremenu", ex_menu, RANGE|NOTADR|ZEROR|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_vsplit, "vsplit", ex_splitview, BANG|FILE1|RANGE|NOTADR|EDITCMD|ARGOPT|TRLBAR), EX(CMD_vunmap, "vunmap", ex_unmap, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_vunmenu, "vunmenu", ex_menu, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_write, "write", ex_write, RANGE|WHOLEFOLD|BANG|FILE1|ARGOPT|DFLALL|TRLBAR|CMDWIN), EX(CMD_wNext, "wNext", ex_wnext, RANGE|WHOLEFOLD|NOTADR|BANG|FILE1|ARGOPT|TRLBAR), EX(CMD_wall, "wall", do_wqall, BANG|TRLBAR|CMDWIN), EX(CMD_while, "while", ex_while, EXTRA|NOTRLCOM|SBOXOK|CMDWIN), EX(CMD_winsize, "winsize", ex_winsize, EXTRA|NEEDARG|TRLBAR), EX(CMD_wincmd, "wincmd", ex_wincmd, NEEDARG|WORD1|RANGE|NOTADR), EX(CMD_windo, "windo", ex_listdo, BANG|NEEDARG|EXTRA|NOTRLCOM), EX(CMD_winpos, "winpos", ex_winpos, EXTRA|TRLBAR|CMDWIN), EX(CMD_wnext, "wnext", ex_wnext, RANGE|NOTADR|BANG|FILE1|ARGOPT|TRLBAR), EX(CMD_wprevious, "wprevious", ex_wnext, RANGE|NOTADR|BANG|FILE1|ARGOPT|TRLBAR), EX(CMD_wq, "wq", ex_exit, RANGE|WHOLEFOLD|BANG|FILE1|ARGOPT|DFLALL|TRLBAR), EX(CMD_wqall, "wqall", do_wqall, BANG|FILE1|ARGOPT|DFLALL|TRLBAR), EX(CMD_wsverb, "wsverb", ex_wsverb, EXTRA|NOTADR|NEEDARG), EX(CMD_wundo, "wundo", ex_wundo, BANG|NEEDARG|FILE1), EX(CMD_wviminfo, "wviminfo", ex_viminfo, BANG|FILE1|TRLBAR|CMDWIN), EX(CMD_xit, "xit", ex_exit, RANGE|WHOLEFOLD|BANG|FILE1|ARGOPT|DFLALL|TRLBAR|CMDWIN), EX(CMD_xall, "xall", do_wqall, BANG|TRLBAR), EX(CMD_xmap, "xmap", ex_map, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_xmapclear, "xmapclear", ex_mapclear, EXTRA|TRLBAR|CMDWIN), EX(CMD_xmenu, "xmenu", ex_menu, RANGE|NOTADR|ZEROR|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_xnoremap, "xnoremap", ex_map, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_xnoremenu, "xnoremenu", ex_menu, RANGE|NOTADR|ZEROR|EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_xunmap, "xunmap", ex_unmap, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_xunmenu, "xunmenu", ex_menu, EXTRA|TRLBAR|NOTRLCOM|USECTRLV|CMDWIN), EX(CMD_yank, "yank", ex_operators, RANGE|WHOLEFOLD|REGSTR|COUNT|TRLBAR|CMDWIN), EX(CMD_z, "z", ex_z, RANGE|WHOLEFOLD|EXTRA|EXFLAGS|TRLBAR|CMDWIN), /* commands that don't start with a lowercase letter */ EX(CMD_bang, "!", ex_bang, RANGE|WHOLEFOLD|BANG|FILES|CMDWIN), EX(CMD_pound, "#", ex_print, RANGE|WHOLEFOLD|COUNT|EXFLAGS|TRLBAR|CMDWIN), EX(CMD_and, "&", do_sub, RANGE|WHOLEFOLD|EXTRA|CMDWIN|MODIFY), EX(CMD_star, "*", ex_at, RANGE|WHOLEFOLD|EXTRA|TRLBAR|CMDWIN), EX(CMD_lshift, "<", ex_operators, RANGE|WHOLEFOLD|COUNT|EXFLAGS|TRLBAR|CMDWIN|MODIFY), EX(CMD_equal, "=", ex_equal, RANGE|TRLBAR|DFLALL|EXFLAGS|CMDWIN), EX(CMD_rshift, ">", ex_operators, RANGE|WHOLEFOLD|COUNT|EXFLAGS|TRLBAR|CMDWIN|MODIFY), EX(CMD_at, "@", ex_at, RANGE|WHOLEFOLD|EXTRA|TRLBAR|CMDWIN), EX(CMD_Next, "Next", ex_previous, EXTRA|RANGE|NOTADR|COUNT|BANG|EDITCMD|ARGOPT|TRLBAR), EX(CMD_Print, "Print", ex_print, RANGE|WHOLEFOLD|COUNT|EXFLAGS|TRLBAR|CMDWIN), EX(CMD_X, "X", ex_X, TRLBAR), EX(CMD_tilde, "~", do_sub, RANGE|WHOLEFOLD|EXTRA|CMDWIN|MODIFY), #ifndef DO_DECLARE_EXCMD #ifdef FEAT_USR_CMDS CMD_SIZE, /* MUST be after all real commands! */ CMD_USER = -1, /* User-defined command */ CMD_USER_BUF = -2 /* User-defined command local to buffer */ #else CMD_SIZE /* MUST be the last one! */ #endif #endif }; #define USER_CMDIDX(idx) ((int)(idx) < 0) #ifndef DO_DECLARE_EXCMD typedef enum CMD_index cmdidx_T; /* * Arguments used for Ex commands. */ struct exarg { char_u *arg; /* argument of the command */ char_u *nextcmd; /* next command (NULL if none) */ char_u *cmd; /* the name of the command (except for :make) */ char_u **cmdlinep; /* pointer to pointer of allocated cmdline */ cmdidx_T cmdidx; /* the index for the command */ long argt; /* flags for the command */ int skip; /* don't execute the command, only parse it */ int forceit; /* TRUE if ! present */ int addr_count; /* the number of addresses given */ linenr_T line1; /* the first line number */ linenr_T line2; /* the second line number or count */ int flags; /* extra flags after count: EXFLAG_ */ char_u *do_ecmd_cmd; /* +command arg to be used in edited file */ linenr_T do_ecmd_lnum; /* the line number in an edited file */ int append; /* TRUE with ":w >>file" command */ int usefilter; /* TRUE with ":w !command" and ":r!command" */ int amount; /* number of '>' or '<' for shift command */ int regname; /* register name (NUL if none) */ int force_bin; /* 0, FORCE_BIN or FORCE_NOBIN */ int read_edit; /* ++edit argument */ int force_ff; /* ++ff= argument (index in cmd[]) */ #ifdef FEAT_MBYTE int force_enc; /* ++enc= argument (index in cmd[]) */ int bad_char; /* BAD_KEEP, BAD_DROP or replacement byte */ #endif #ifdef FEAT_USR_CMDS int useridx; /* user command index */ #endif char_u *errmsg; /* returned error message */ char_u *(*getline) __ARGS((int, void *, int)); void *cookie; /* argument for getline() */ #ifdef FEAT_EVAL struct condstack *cstack; /* condition stack for ":if" etc. */ #endif }; #define FORCE_BIN 1 /* ":edit ++bin file" */ #define FORCE_NOBIN 2 /* ":edit ++nobin file" */ /* Values for "flags" */ #define EXFLAG_LIST 0x01 /* 'l': list */ #define EXFLAG_NR 0x02 /* '#': number */ #define EXFLAG_PRINT 0x04 /* 'p': print */ #endif
zyz2011-vim
src/ex_cmds.h
C
gpl2
44,166
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * os_amiga.c * * Amiga system-dependent routines. */ #include "vim.h" #ifdef Window # undef Window /* Amiga has its own Window definition */ #endif #undef TRUE /* will be redefined by exec/types.h */ #undef FALSE #ifndef LATTICE # include <exec/types.h> # include <exec/exec.h> # include <libraries/dos.h> # include <intuition/intuition.h> #endif /* XXX These are included from os_amiga.h #include <proto/exec.h> #include <proto/dos.h> #include <proto/intuition.h> */ #include <exec/memory.h> #include <libraries/dosextens.h> #include <dos/dostags.h> /* for 2.0 functions */ #include <dos/dosasl.h> /* From version 4 of AmigaOS, several system structures must be allocated * and freed using system functions. "struct AnchorPath" is one. */ #ifdef __amigaos4__ # include <dos/anchorpath.h> # define free_fib(x) FreeDosObject(DOS_FIB, x) #else # define free_fib(x) vim_free(fib) #endif #if defined(LATTICE) && !defined(SASC) && defined(FEAT_ARP) # include <libraries/arp_pragmas.h> #endif /* * At this point TRUE and FALSE are defined as 1L and 0L, but we want 1 and 0. */ #undef TRUE #define TRUE (1) #undef FALSE #define FALSE (0) #ifdef __amigaos4__ # define dos_packet(a, b, c) DoPkt(a, b, c, 0, 0, 0, 0) #elif !defined(AZTEC_C) && !defined(__AROS__) static long dos_packet __ARGS((struct MsgPort *, long, long)); #endif static int lock2name __ARGS((BPTR lock, char_u *buf, long len)); static void out_num __ARGS((long n)); static struct FileInfoBlock *get_fib __ARGS((char_u *)); static int sortcmp __ARGS((const void *a, const void *b)); static BPTR raw_in = (BPTR)NULL; static BPTR raw_out = (BPTR)NULL; static int close_win = FALSE; /* set if Vim opened the window */ #ifndef __amigaos4__ /* Use autoopen for AmigaOS4 */ struct IntuitionBase *IntuitionBase = NULL; #endif #ifdef FEAT_ARP struct ArpBase *ArpBase = NULL; #endif static struct Window *wb_window; static char_u *oldwindowtitle = NULL; #ifdef FEAT_ARP int dos2 = FALSE; /* Amiga DOS 2.0x or higher */ #endif int size_set = FALSE; /* set to TRUE if window size was set */ void win_resize_on() { OUT_STR_NF("\033[12{"); } void win_resize_off() { OUT_STR_NF("\033[12}"); } void mch_write(p, len) char_u *p; int len; { Write(raw_out, (char *)p, (long)len); } /* * mch_inchar(): low level input funcion. * Get a characters from the keyboard. * If time == 0 do not wait for characters. * If time == n wait a short time for characters. * If time == -1 wait forever for characters. * * Return number of characters read. */ int mch_inchar(buf, maxlen, time, tb_change_cnt) char_u *buf; int maxlen; long time; /* milli seconds */ int tb_change_cnt; { int len; long utime; if (time >= 0) { if (time == 0) utime = 100L; /* time = 0 causes problems in DOS 1.2 */ else utime = time * 1000L; /* convert from milli to micro secs */ if (WaitForChar(raw_in, utime) == 0) /* no character available */ return 0; } else /* time == -1 */ { /* * If there is no character available within 2 seconds (default) * write the autoscript file to disk. Or cause the CursorHold event * to be triggered. */ if (WaitForChar(raw_in, p_ut * 1000L) == 0) { #ifdef FEAT_AUTOCMD if (trigger_cursorhold() && maxlen >= 3) { buf[0] = K_SPECIAL; buf[1] = KS_EXTRA; buf[2] = (int)KE_CURSORHOLD; return 3; } #endif before_blocking(); } } for (;;) /* repeat until we got a character */ { # ifdef FEAT_MBYTE len = Read(raw_in, (char *)buf, (long)maxlen / input_conv.vc_factor); # else len = Read(raw_in, (char *)buf, (long)maxlen); # endif if (len > 0) { #ifdef FEAT_MBYTE /* Convert from 'termencoding' to 'encoding'. */ if (input_conv.vc_type != CONV_NONE) len = convert_input(buf, len, maxlen); #endif return len; } } } /* * return non-zero if a character is available */ int mch_char_avail() { return (WaitForChar(raw_in, 100L) != 0); } /* * Return amount of memory still available. */ long_u mch_avail_mem(special) int special; { #ifdef __amigaos4__ return (long_u)AvailMem(MEMF_ANY); #else return (long_u)AvailMem(special ? (long)MEMF_CHIP : (long)MEMF_ANY); #endif } /* * Waits a specified amount of time, or until input arrives if * ignoreinput is FALSE. */ void mch_delay(msec, ignoreinput) long msec; int ignoreinput; { #ifndef LATTICE /* SAS declares void Delay(ULONG) */ void Delay __ARGS((long)); #endif if (msec > 0) { if (ignoreinput) Delay(msec / 20L); /* Delay works with 20 msec intervals */ else WaitForChar(raw_in, msec * 1000L); } } /* * We have no job control, fake it by starting a new shell. */ void mch_suspend() { suspend_shell(); } #ifndef DOS_LIBRARY # define DOS_LIBRARY ((UBYTE *)"dos.library") #endif void mch_init() { static char intlibname[] = "intuition.library"; #ifdef AZTEC_C Enable_Abort = 0; /* disallow vim to be aborted */ #endif Columns = 80; Rows = 24; /* * Set input and output channels, unless we have opened our own window */ if (raw_in == (BPTR)NULL) { raw_in = Input(); raw_out = Output(); /* * If Input() is not interactive, then Output() will be (because of * check in mch_check_win()). Used for "Vim -". * Also check the other way around, for "Vim -h | more". */ if (!IsInteractive(raw_in)) raw_in = raw_out; else if (!IsInteractive(raw_out)) raw_out = raw_in; } out_flush(); wb_window = NULL; #ifndef __amigaos4__ if ((IntuitionBase = (struct IntuitionBase *) OpenLibrary((UBYTE *)intlibname, 0L)) == NULL) { mch_errmsg(_("cannot open ")); mch_errmsg(intlibname); mch_errmsg("!?\n"); mch_exit(3); } #endif } #include <workbench/startup.h> /* * Check_win checks whether we have an interactive window. * If not, a new window is opened with the newcli command. * If we would open a window ourselves, the :sh and :! commands would not * work properly (Why? probably because we are then running in a background * CLI). This also is the best way to assure proper working in a next * Workbench release. * * For the -f option (foreground mode) we open our own window and disable :sh. * Otherwise the calling program would never know when editing is finished. */ #define BUF2SIZE 320 /* length of buffer for argument with complete path */ int mch_check_win(argc, argv) int argc; char **argv; { int i; BPTR nilfh, fh; char_u buf1[24]; char_u buf2[BUF2SIZE]; static char_u *(constrings[3]) = {(char_u *)"con:0/0/662/210/", (char_u *)"con:0/0/640/200/", (char_u *)"con:0/0/320/200/"}; static char_u *winerr = (char_u *)N_("VIM: Can't open window!\n"); struct WBArg *argp; int ac; char *av; char_u *device = NULL; int exitval = 4; #ifndef __amigaos4__ struct Library *DosBase; #endif int usewin = FALSE; /* * check if we are running under DOS 2.0x or higher */ #ifndef __amigaos4__ DosBase = OpenLibrary(DOS_LIBRARY, 37L); if (DosBase != NULL) /* if (((struct Library *)DOSBase)->lib_Version >= 37) */ { CloseLibrary(DosBase); # ifdef FEAT_ARP dos2 = TRUE; # endif } else /* without arp functions we NEED 2.0 */ { # ifndef FEAT_ARP mch_errmsg(_("Need Amigados version 2.04 or later\n")); exit(3); # else /* need arp functions for dos 1.x */ if (!(ArpBase = (struct ArpBase *) OpenLibrary((UBYTE *)ArpName, ArpVersion))) { fprintf(stderr, _("Need %s version %ld\n"), ArpName, ArpVersion); exit(3); } # endif } #endif /* __amigaos4__ */ /* * scan argv[] for the "-f" and "-d" arguments */ for (i = 1; i < argc; ++i) if (argv[i][0] == '-') { switch (argv[i][1]) { case 'f': usewin = TRUE; break; case 'd': if (i < argc - 1 #ifdef FEAT_DIFF /* require using "-dev", "-d" means diff mode */ && argv[i][2] == 'e' && argv[i][3] == 'v' #endif ) device = (char_u *)argv[i + 1]; break; } } /* * If we were not started from workbench, do not have a "-d" or "-dev" * argument and we have been started with an interactive window, use that * window. */ if (argc != 0 && device == NULL && (IsInteractive(Input()) || IsInteractive(Output()))) return OK; /* * When given the "-f" argument, we open our own window. We can't use the * newcli trick below, because the calling program (mail, rn, etc.) would not * know when we are finished. */ if (usewin) { /* * Try to open a window. First try the specified device. * Then try a 24 line 80 column window. * If that fails, try two smaller ones. */ for (i = -1; i < 3; ++i) { if (i >= 0) device = constrings[i]; if (device != NULL && (raw_in = Open((UBYTE *)device, (long)MODE_NEWFILE)) != (BPTR)NULL) break; } if (raw_in == (BPTR)NULL) /* all three failed */ { mch_errmsg(_(winerr)); goto exit; } raw_out = raw_in; close_win = TRUE; return OK; } if ((nilfh = Open((UBYTE *)"NIL:", (long)MODE_NEWFILE)) == (BPTR)NULL) { mch_errmsg(_("Cannot open NIL:\n")); goto exit; } /* * Make a unique name for the temp file (which we will not delete!). * Use a pointer on the stack (nobody else will be using it). * Under AmigaOS4, this assumption might change in the future, so * we use a pointer to the current task instead. This should be a * shared structure and thus globally unique. */ #ifdef __amigaos4__ sprintf((char *)buf1, "t:nc%p", FindTask(0)); #else sprintf((char *)buf1, "t:nc%ld", (long)buf1); #endif if ((fh = Open((UBYTE *)buf1, (long)MODE_NEWFILE)) == (BPTR)NULL) { mch_errmsg(_("Cannot create ")); mch_errmsg((char *)buf1); mch_errmsg("\n"); goto exit; } /* * Write the command into the file, put quotes around the arguments that * have a space in them. */ if (argc == 0) /* run from workbench */ ac = ((struct WBStartup *)argv)->sm_NumArgs; else ac = argc; for (i = 0; i < ac; ++i) { if (argc == 0) { *buf2 = NUL; argp = &(((struct WBStartup *)argv)->sm_ArgList[i]); if (argp->wa_Lock) (void)lock2name(argp->wa_Lock, buf2, (long)(BUF2SIZE - 1)); #ifdef FEAT_ARP if (dos2) /* use 2.0 function */ #endif AddPart((UBYTE *)buf2, (UBYTE *)argp->wa_Name, (long)(BUF2SIZE - 1)); #ifdef FEAT_ARP else /* use arp function */ TackOn((char *)buf2, argp->wa_Name); #endif av = (char *)buf2; } else av = argv[i]; /* skip '-d' or "-dev" option */ if (av[0] == '-' && av[1] == 'd' #ifdef FEAT_DIFF && av[2] == 'e' && av[3] == 'v' #endif ) { ++i; continue; } if (vim_strchr((char_u *)av, ' ')) Write(fh, "\"", 1L); Write(fh, av, (long)strlen(av)); if (vim_strchr((char_u *)av, ' ')) Write(fh, "\"", 1L); Write(fh, " ", 1L); } Write(fh, "\nendcli\n", 8L); Close(fh); /* * Try to open a new cli in a window. If "-d" or "-dev" argument was given try * to open the specified device. Then try a 24 line 80 column window. If that * fails, try two smaller ones. */ for (i = -1; i < 3; ++i) { if (i >= 0) device = constrings[i]; else if (device == NULL) continue; sprintf((char *)buf2, "newcli <nil: >nil: %s from %s", (char *)device, (char *)buf1); #ifdef FEAT_ARP if (dos2) { #endif if (!SystemTags((UBYTE *)buf2, SYS_UserShell, TRUE, TAG_DONE)) break; #ifdef FEAT_ARP } else { if (Execute((UBYTE *)buf2, nilfh, nilfh)) break; } #endif } if (i == 3) /* all three failed */ { DeleteFile((UBYTE *)buf1); mch_errmsg(_(winerr)); goto exit; } exitval = 0; /* The Execute succeeded: exit this program */ exit: #ifdef FEAT_ARP if (ArpBase) CloseLibrary((struct Library *) ArpBase); #endif exit(exitval); /* NOTREACHED */ return FAIL; } /* * Return TRUE if the input comes from a terminal, FALSE otherwise. * We fake there is a window, because we can always open one! */ int mch_input_isatty() { return TRUE; } /* * fname_case(): Set the case of the file name, if it already exists. * This will cause the file name to remain exactly the same * if the file system ignores, but preserves case. */ /*ARGSUSED*/ void fname_case(name, len) char_u *name; int len; /* buffer size, ignored here */ { struct FileInfoBlock *fib; size_t flen; fib = get_fib(name); if (fib != NULL) { flen = STRLEN(name); /* TODO: Check if this fix applies to AmigaOS < 4 too.*/ #ifdef __amigaos4__ if (fib->fib_DirEntryType == ST_ROOT) strcat(fib->fib_FileName, ":"); #endif if (flen == strlen(fib->fib_FileName)) /* safety check */ mch_memmove(name, fib->fib_FileName, flen); free_fib(fib); } } /* * Get the FileInfoBlock for file "fname" * The returned structure has to be free()d. * Returns NULL on error. */ static struct FileInfoBlock * get_fib(fname) char_u *fname; { BPTR flock; struct FileInfoBlock *fib; if (fname == NULL) /* safety check */ return NULL; #ifdef __amigaos4__ fib = AllocDosObject(DOS_FIB,0); #else fib = (struct FileInfoBlock *)alloc(sizeof(struct FileInfoBlock)); #endif if (fib != NULL) { flock = Lock((UBYTE *)fname, (long)ACCESS_READ); if (flock == (BPTR)NULL || !Examine(flock, fib)) { free_fib(fib); /* in case of an error the memory is freed here */ fib = NULL; } if (flock) UnLock(flock); } return fib; } #ifdef FEAT_TITLE /* * set the title of our window * icon name is not set */ void mch_settitle(title, icon) char_u *title; char_u *icon; { if (wb_window != NULL && title != NULL) SetWindowTitles(wb_window, (UBYTE *)title, (UBYTE *)-1L); } /* * Restore the window/icon title. * which is one of: * 1 Just restore title * 2 Just restore icon (which we don't have) * 3 Restore title and icon (which we don't have) */ void mch_restore_title(which) int which; { if (which & 1) mch_settitle(oldwindowtitle, NULL); } int mch_can_restore_title() { return (wb_window != NULL); } int mch_can_restore_icon() { return FALSE; } #endif /* * Insert user name in s[len]. */ int mch_get_user_name(s, len) char_u *s; int len; { /* TODO: Implement this. */ *s = NUL; return FAIL; } /* * Insert host name is s[len]. */ void mch_get_host_name(s, len) char_u *s; int len; { #if defined(__amigaos4__) && defined(__CLIB2__) gethostname(s, len); #else vim_strncpy(s, "Amiga", len - 1); #endif } /* * return process ID */ long mch_get_pid() { #ifdef __amigaos4__ /* This is as close to a pid as we can come. We could use CLI numbers also, * but then we would have two different types of process identifiers. */ return((long)FindTask(0)); #else return (long)0; #endif } /* * Get name of current directory into buffer 'buf' of length 'len' bytes. * Return OK for success, FAIL for failure. */ int mch_dirname(buf, len) char_u *buf; int len; { return mch_FullName((char_u *)"", buf, len, FALSE); } /* * get absolute file name into buffer 'buf' of length 'len' bytes * * return FAIL for failure, OK otherwise */ int mch_FullName(fname, buf, len, force) char_u *fname, *buf; int len; int force; { BPTR l; int retval = FAIL; int i; /* Lock the file. If it exists, we can get the exact name. */ if ((l = Lock((UBYTE *)fname, (long)ACCESS_READ)) != (BPTR)0) { retval = lock2name(l, buf, (long)len - 1); UnLock(l); } else if (force || !mch_isFullName(fname)) /* not a full path yet */ { /* * If the file cannot be locked (doesn't exist), try to lock the * current directory and concatenate the file name. */ if ((l = Lock((UBYTE *)"", (long)ACCESS_READ)) != (BPTR)NULL) { retval = lock2name(l, buf, (long)len); UnLock(l); if (retval == OK) { i = STRLEN(buf); /* Concatenate the fname to the directory. Don't add a slash * if fname is empty, but do change "" to "/". */ if (i == 0 || *fname != NUL) { if (i < len - 1 && (i == 0 || buf[i - 1] != ':')) buf[i++] = '/'; vim_strncpy(buf + i, fname, len - i - 1); } } } } if (*buf == 0 || *buf == ':') retval = FAIL; /* something failed; use the file name */ return retval; } /* * Return TRUE if "fname" does not depend on the current directory. */ int mch_isFullName(fname) char_u *fname; { return (vim_strchr(fname, ':') != NULL && *fname != ':'); } /* * Get the full file name from a lock. Use 2.0 function if possible, because * the arp function has more restrictions on the path length. * * return FAIL for failure, OK otherwise */ static int lock2name(lock, buf, len) BPTR lock; char_u *buf; long len; { #ifdef FEAT_ARP if (dos2) /* use 2.0 function */ #endif return ((int)NameFromLock(lock, (UBYTE *)buf, len) ? OK : FAIL); #ifdef FEAT_ARP else /* use arp function */ return ((int)PathName(lock, (char *)buf, (long)(len/32)) ? OK : FAIL); #endif } /* * get file permissions for 'name' * Returns -1 when it doesn't exist. */ long mch_getperm(name) char_u *name; { struct FileInfoBlock *fib; long retval = -1; fib = get_fib(name); if (fib != NULL) { retval = fib->fib_Protection; free_fib(fib); } return retval; } /* * set file permission for 'name' to 'perm' * * return FAIL for failure, OK otherwise */ int mch_setperm(name, perm) char_u *name; long perm; { perm &= ~FIBF_ARCHIVE; /* reset archived bit */ return (SetProtection((UBYTE *)name, (long)perm) ? OK : FAIL); } /* * Set hidden flag for "name". */ void mch_hide(name) char_u *name; { /* can't hide a file */ } /* * return FALSE if "name" is not a directory * return TRUE if "name" is a directory. * return FALSE for error. */ int mch_isdir(name) char_u *name; { struct FileInfoBlock *fib; int retval = FALSE; fib = get_fib(name); if (fib != NULL) { #ifdef __amigaos4__ retval = (FIB_IS_DRAWER(fib)) ? TRUE : FALSE; #else retval = ((fib->fib_DirEntryType >= 0) ? TRUE : FALSE); #endif free_fib(fib); } return retval; } /* * Create directory "name". */ int mch_mkdir(name) char_u *name; { BPTR lock; lock = CreateDir(name); if (lock != NULL) { UnLock(lock); return 0; } return -1; } /* * Return 1 if "name" can be executed, 0 if not. * Return -1 if unknown. */ int mch_can_exe(name) char_u *name; { /* TODO */ return -1; } /* * Check what "name" is: * NODE_NORMAL: file or directory (or doesn't exist) * NODE_WRITABLE: writable device, socket, fifo, etc. * NODE_OTHER: non-writable things */ int mch_nodetype(name) char_u *name; { /* TODO */ return NODE_NORMAL; } void mch_early_init() { } /* * Careful: mch_exit() may be called before mch_init()! */ void mch_exit(r) int r; { if (raw_in) /* put terminal in 'normal' mode */ { settmode(TMODE_COOK); stoptermcap(); } out_char('\n'); if (raw_out) { if (term_console) { win_resize_off(); /* window resize events de-activated */ if (size_set) OUT_STR("\233t\233u"); /* reset window size (CSI t CSI u) */ } out_flush(); } #ifdef FEAT_TITLE mch_restore_title(3); /* restore window title */ #endif ml_close_all(TRUE); /* remove all memfiles */ #ifdef FEAT_ARP if (ArpBase) CloseLibrary((struct Library *) ArpBase); #endif if (close_win) Close(raw_in); if (r) printf(_("Vim exiting with %d\n"), r); /* somehow this makes :cq work!? */ exit(r); } /* * This is a routine for setting a given stream to raw or cooked mode on the * Amiga . This is useful when you are using Lattice C to produce programs * that want to read single characters with the "getch()" or "fgetc" call. * * Written : 18-Jun-87 By Chuck McManis. */ #define MP(xx) ((struct MsgPort *)((struct FileHandle *) (BADDR(xx)))->fh_Type) /* * Function mch_settmode() - Convert the specified file pointer to 'raw' or * 'cooked' mode. This only works on TTY's. * * Raw: keeps DOS from translating keys for you, also (BIG WIN) it means * getch() will return immediately rather than wait for a return. You * lose editing features though. * * Cooked: This function returns the designate file pointer to it's normal, * wait for a <CR> mode. This is exactly like raw() except that * it sends a 0 to the console to make it back into a CON: from a RAW: */ void mch_settmode(tmode) int tmode; { #if defined(__AROS__) || defined(__amigaos4__) if (!SetMode(raw_in, tmode == TMODE_RAW ? 1 : 0)) #else if (dos_packet(MP(raw_in), (long)ACTION_SCREEN_MODE, tmode == TMODE_RAW ? -1L : 0L) == 0) #endif mch_errmsg(_("cannot change console mode ?!\n")); } /* * set screen mode, always fails. */ int mch_screenmode(arg) char_u *arg; { EMSG(_(e_screenmode)); return FAIL; } /* * Code for this routine came from the following : * * ConPackets.c - C. Scheppner, A. Finkel, P. Lindsay CBM * DOS packet example * Requires 1.2 * * Found on Fish Disk 56. * * Heavely modified by mool. */ #include <devices/conunit.h> /* * try to get the real window size * return FAIL for failure, OK otherwise */ int mch_get_shellsize() { struct ConUnit *conUnit; #ifndef __amigaos4__ char id_a[sizeof(struct InfoData) + 3]; #endif struct InfoData *id=0; if (!term_console) /* not an amiga window */ goto out; /* insure longword alignment */ #ifdef __amigaos4__ if (!(id = AllocDosObject(DOS_INFODATA, 0))) goto out; #else id = (struct InfoData *)(((long)id_a + 3L) & ~3L); #endif /* * Should make console aware of real window size, not the one we set. * Unfortunately, under DOS 2.0x this redraws the window and it * is rarely needed, so we skip it now, unless we changed the size. */ if (size_set) OUT_STR("\233t\233u"); /* CSI t CSI u */ out_flush(); #ifdef __AROS__ if (!Info(raw_out, id) || (wb_window = (struct Window *) id->id_VolumeNode) == NULL) #else if (dos_packet(MP(raw_out), (long)ACTION_DISK_INFO, ((ULONG) id) >> 2) == 0 || (wb_window = (struct Window *)id->id_VolumeNode) == NULL) #endif { /* it's not an amiga window, maybe aux device */ /* terminal type should be set */ term_console = FALSE; goto out; } if (oldwindowtitle == NULL) oldwindowtitle = (char_u *)wb_window->Title; if (id->id_InUse == (BPTR)NULL) { mch_errmsg(_("mch_get_shellsize: not a console??\n")); return FAIL; } conUnit = (struct ConUnit *) ((struct IOStdReq *) id->id_InUse)->io_Unit; /* get window size */ Rows = conUnit->cu_YMax + 1; Columns = conUnit->cu_XMax + 1; if (Rows < 0 || Rows > 200) /* cannot be an amiga window */ { Columns = 80; Rows = 24; term_console = FALSE; return FAIL; } return OK; out: #ifdef __amigaos4__ FreeDosObject(DOS_INFODATA, id); /* Safe to pass NULL */ #endif return FAIL; } /* * Try to set the real window size to Rows and Columns. */ void mch_set_shellsize() { if (term_console) { size_set = TRUE; out_char(CSI); out_num((long)Rows); out_char('t'); out_char(CSI); out_num((long)Columns); out_char('u'); out_flush(); } } /* * Rows and/or Columns has changed. */ void mch_new_shellsize() { /* Nothing to do. */ } /* * out_num - output a (big) number fast */ static void out_num(n) long n; { OUT_STR_NF(tltoa((unsigned long)n)); } #if !defined(AZTEC_C) && !defined(__AROS__) && !defined(__amigaos4__) /* * Sendpacket.c * * An invaluable addition to your Amiga.lib file. This code sends a packet to * the given message port. This makes working around DOS lots easier. * * Note, I didn't write this, those wonderful folks at CBM did. I do suggest * however that you may wish to add it to Amiga.Lib, to do so, compile it and * say 'oml lib:amiga.lib -r sendpacket.o' */ /* #include <proto/exec.h> */ /* #include <proto/dos.h> */ #include <exec/memory.h> /* * Function - dos_packet written by Phil Lindsay, Carolyn Scheppner, and Andy * Finkel. This function will send a packet of the given type to the Message * Port supplied. */ static long dos_packet(pid, action, arg) struct MsgPort *pid; /* process identifier ... (handlers message port) */ long action, /* packet type ... (what you want handler to do) */ arg; /* single argument */ { # ifdef FEAT_ARP struct MsgPort *replyport; struct StandardPacket *packet; long res1; if (dos2) # endif return DoPkt(pid, action, arg, 0L, 0L, 0L, 0L); /* use 2.0 function */ # ifdef FEAT_ARP replyport = (struct MsgPort *) CreatePort(NULL, 0); /* use arp function */ if (!replyport) return (0); /* Allocate space for a packet, make it public and clear it */ packet = (struct StandardPacket *) AllocMem((long) sizeof(struct StandardPacket), MEMF_PUBLIC | MEMF_CLEAR); if (!packet) { DeletePort(replyport); return (0); } packet->sp_Msg.mn_Node.ln_Name = (char *) &(packet->sp_Pkt); packet->sp_Pkt.dp_Link = &(packet->sp_Msg); packet->sp_Pkt.dp_Port = replyport; packet->sp_Pkt.dp_Type = action; packet->sp_Pkt.dp_Arg1 = arg; PutMsg(pid, (struct Message *)packet); /* send packet */ WaitPort(replyport); GetMsg(replyport); res1 = packet->sp_Pkt.dp_Res1; FreeMem(packet, (long) sizeof(struct StandardPacket)); DeletePort(replyport); return (res1); # endif } #endif /* !defined(AZTEC_C) && !defined(__AROS__) */ /* * Call shell. * Return error number for failure, 0 otherwise */ int mch_call_shell(cmd, options) char_u *cmd; int options; /* SHELL_*, see vim.h */ { BPTR mydir; int x; int tmode = cur_tmode; #ifdef AZTEC_C int use_execute; char_u *shellcmd = NULL; char_u *shellarg; #endif int retval = 0; if (close_win) { /* if Vim opened a window: Executing a shell may cause crashes */ EMSG(_("E360: Cannot execute shell with -f option")); return -1; } if (term_console) win_resize_off(); /* window resize events de-activated */ out_flush(); if (options & SHELL_COOKED) settmode(TMODE_COOK); /* set to normal mode */ mydir = Lock((UBYTE *)"", (long)ACCESS_READ); /* remember current dir */ #if !defined(AZTEC_C) /* not tested very much */ if (cmd == NULL) { # ifdef FEAT_ARP if (dos2) # endif x = SystemTags(p_sh, SYS_UserShell, TRUE, TAG_DONE); # ifdef FEAT_ARP else x = Execute(p_sh, raw_in, raw_out); # endif } else { # ifdef FEAT_ARP if (dos2) # endif x = SystemTags((char *)cmd, SYS_UserShell, TRUE, TAG_DONE); # ifdef FEAT_ARP else x = Execute((char *)cmd, 0L, raw_out); # endif } # ifdef FEAT_ARP if ((dos2 && x < 0) || (!dos2 && !x)) # else if (x < 0) # endif { MSG_PUTS(_("Cannot execute ")); if (cmd == NULL) { MSG_PUTS(_("shell ")); msg_outtrans(p_sh); } else msg_outtrans(cmd); msg_putchar('\n'); retval = -1; } # ifdef FEAT_ARP else if (!dos2 || x) # else else if (x) # endif { if ((x = IoErr()) != 0) { if (!(options & SHELL_SILENT)) { msg_putchar('\n'); msg_outnum((long)x); MSG_PUTS(_(" returned\n")); } retval = x; } } #else /* else part is for AZTEC_C */ if (p_st >= 4 || (p_st >= 2 && !(options & SHELL_FILTER))) use_execute = 1; else use_execute = 0; if (!use_execute) { /* * separate shell name from argument */ shellcmd = vim_strsave(p_sh); if (shellcmd == NULL) /* out of memory, use Execute */ use_execute = 1; else { shellarg = skiptowhite(shellcmd); /* find start of arguments */ if (*shellarg != NUL) { *shellarg++ = NUL; shellarg = skipwhite(shellarg); } } } if (cmd == NULL) { if (use_execute) { # ifdef FEAT_ARP if (dos2) # endif x = SystemTags((UBYTE *)p_sh, SYS_UserShell, TRUE, TAG_DONE); # ifdef FEAT_ARP else x = !Execute((UBYTE *)p_sh, raw_in, raw_out); # endif } else x = fexecl((char *)shellcmd, (char *)shellcmd, (char *)shellarg, NULL); } else if (use_execute) { # ifdef FEAT_ARP if (dos2) # endif x = SystemTags((UBYTE *)cmd, SYS_UserShell, TRUE, TAG_DONE); # ifdef FEAT_ARP else x = !Execute((UBYTE *)cmd, 0L, raw_out); # endif } else if (p_st & 1) x = fexecl((char *)shellcmd, (char *)shellcmd, (char *)shellarg, (char *)cmd, NULL); else x = fexecl((char *)shellcmd, (char *)shellcmd, (char *)shellarg, (char *)p_shcf, (char *)cmd, NULL); # ifdef FEAT_ARP if ((dos2 && x < 0) || (!dos2 && x)) # else if (x < 0) # endif { MSG_PUTS(_("Cannot execute ")); if (use_execute) { if (cmd == NULL) msg_outtrans(p_sh); else msg_outtrans(cmd); } else { MSG_PUTS(_("shell ")); msg_outtrans(shellcmd); } msg_putchar('\n'); retval = -1; } else { if (use_execute) { # ifdef FEAT_ARP if (!dos2 || x) # else if (x) # endif x = IoErr(); } else x = wait(); if (x) { if (!(options & SHELL_SILENT) && !emsg_silent) { msg_putchar('\n'); msg_outnum((long)x); MSG_PUTS(_(" returned\n")); } retval = x; } } vim_free(shellcmd); #endif /* AZTEC_C */ if ((mydir = CurrentDir(mydir)) != 0) /* make sure we stay in the same directory */ UnLock(mydir); if (tmode == TMODE_RAW) settmode(TMODE_RAW); /* set to raw mode */ #ifdef FEAT_TITLE resettitle(); #endif if (term_console) win_resize_on(); /* window resize events activated */ return retval; } /* * check for an "interrupt signal" * We only react to a CTRL-C, but also clear the other break signals to avoid * trouble with lattice-c programs. */ void mch_breakcheck() { if (SetSignal(0L, (long)(SIGBREAKF_CTRL_C|SIGBREAKF_CTRL_D|SIGBREAKF_CTRL_E|SIGBREAKF_CTRL_F)) & SIGBREAKF_CTRL_C) got_int = TRUE; } /* this routine causes manx to use this Chk_Abort() rather than it's own */ /* otherwise it resets our ^C when doing any I/O (even when Enable_Abort */ /* is zero). Since we want to check for our own ^C's */ #ifdef _DCC #define Chk_Abort chkabort #endif #ifdef LATTICE void __regargs __chkabort(void); void __regargs __chkabort(void) {} #else long Chk_Abort(void) { return(0L); } #endif /* * mch_expandpath() - this code does wild-card pattern matching using the arp * routines. * * "pat" has backslashes before chars that are not to be expanded. * Returns the number of matches found. * * This is based on WildDemo2.c (found in arp1.1 distribution). * That code's copyright follows: * Copyright (c) 1987, Scott Ballantyne * Use and abuse as you please. */ #ifdef __amigaos4__ # define ANCHOR_BUF_SIZE 1024 #else # define ANCHOR_BUF_SIZE (512) # define ANCHOR_SIZE (sizeof(struct AnchorPath) + ANCHOR_BUF_SIZE) #endif int mch_expandpath(gap, pat, flags) garray_T *gap; char_u *pat; int flags; /* EW_* flags */ { struct AnchorPath *Anchor; LONG Result; char_u *starbuf, *sp, *dp; int start_len; int matches; #ifdef __amigaos4__ struct TagItem AnchorTags[] = { {ADO_Strlen, ANCHOR_BUF_SIZE}, {ADO_Flags, APF_DODOT|APF_DOWILD|APF_MultiAssigns}, {TAG_DONE, 0L} }; #endif start_len = gap->ga_len; /* Get our AnchorBase */ #ifdef __amigaos4__ Anchor = AllocDosObject(DOS_ANCHORPATH, AnchorTags); #else Anchor = (struct AnchorPath *)alloc_clear((unsigned)ANCHOR_SIZE); #endif if (Anchor == NULL) return 0; #ifndef __amigaos4__ Anchor->ap_Strlen = ANCHOR_BUF_SIZE; /* ap_Length not supported anymore */ # ifdef APF_DODOT Anchor->ap_Flags = APF_DODOT | APF_DOWILD; /* allow '.' for current dir */ # else Anchor->ap_Flags = APF_DoDot | APF_DoWild; /* allow '.' for current dir */ # endif #endif #ifdef FEAT_ARP if (dos2) { #endif /* hack to replace '*' by '#?' */ starbuf = alloc((unsigned)(2 * STRLEN(pat) + 1)); if (starbuf == NULL) goto Return; for (sp = pat, dp = starbuf; *sp; ++sp) { if (*sp == '*') { *dp++ = '#'; *dp++ = '?'; } else *dp++ = *sp; } *dp = NUL; Result = MatchFirst((UBYTE *)starbuf, Anchor); vim_free(starbuf); #ifdef FEAT_ARP } else Result = FindFirst((char *)pat, Anchor); #endif /* * Loop to get all matches. */ while (Result == 0) { #ifdef __amigaos4__ addfile(gap, (char_u *)Anchor->ap_Buffer, flags); #else addfile(gap, (char_u *)Anchor->ap_Buf, flags); #endif #ifdef FEAT_ARP if (dos2) #endif Result = MatchNext(Anchor); #ifdef FEAT_ARP else Result = FindNext(Anchor); #endif } matches = gap->ga_len - start_len; if (Result == ERROR_BUFFER_OVERFLOW) EMSG(_("ANCHOR_BUF_SIZE too small.")); else if (matches == 0 && Result != ERROR_OBJECT_NOT_FOUND && Result != ERROR_DEVICE_NOT_MOUNTED && Result != ERROR_NO_MORE_ENTRIES) EMSG(_("I/O ERROR")); /* * Sort the files for this pattern. */ if (matches) qsort((void *)(((char_u **)gap->ga_data) + start_len), (size_t)matches, sizeof(char_u *), sortcmp); /* Free the wildcard stuff */ #ifdef FEAT_ARP if (dos2) #endif MatchEnd(Anchor); #ifdef FEAT_ARP else FreeAnchorChain(Anchor); #endif Return: #ifdef __amigaos4__ FreeDosObject(DOS_ANCHORPATH, Anchor); #else vim_free(Anchor); #endif return matches; } static int sortcmp(a, b) const void *a, *b; { char *s = *(char **)a; char *t = *(char **)b; return pathcmp(s, t, -1); } /* * Return TRUE if "p" has wildcards that can be expanded by mch_expandpath(). */ int mch_has_exp_wildcard(p) char_u *p; { for ( ; *p; mb_ptr_adv(p)) { if (*p == '\\' && p[1] != NUL) ++p; else if (vim_strchr((char_u *)"*?[(#", *p) != NULL) return TRUE; } return FALSE; } int mch_has_wildcard(p) char_u *p; { for ( ; *p; mb_ptr_adv(p)) { if (*p == '\\' && p[1] != NUL) ++p; else if (vim_strchr((char_u *) # ifdef VIM_BACKTICK "*?[(#$`" # else "*?[(#$" # endif , *p) != NULL || (*p == '~' && p[1] != NUL)) return TRUE; } return FALSE; } /* * With AmigaDOS 2.0 support for reading local environment variables * * Two buffers are allocated: * - A big one to do the expansion into. It is freed before returning. * - A small one to hold the return value. It is kept until the next call. */ char_u * mch_getenv(var) char_u *var; { int len; UBYTE *buf; /* buffer to expand in */ char_u *retval; /* return value */ static char_u *alloced = NULL; /* allocated memory */ #ifdef FEAT_ARP if (!dos2) retval = (char_u *)getenv((char *)var); else #endif { vim_free(alloced); alloced = NULL; retval = NULL; buf = alloc(IOSIZE); if (buf == NULL) return NULL; len = GetVar((UBYTE *)var, buf, (long)(IOSIZE - 1), (long)0); if (len >= 0) { retval = vim_strsave((char_u *)buf); alloced = retval; } vim_free(buf); } /* if $VIM is not defined, use "vim:" instead */ if (retval == NULL && STRCMP(var, "VIM") == 0) retval = (char_u *)"vim:"; return retval; } /* * Amiga version of setenv() with AmigaDOS 2.0 support. */ /* ARGSUSED */ int mch_setenv(var, value, x) char *var; char *value; int x; { #ifdef FEAT_ARP if (!dos2) return setenv(var, value); #endif if (SetVar((UBYTE *)var, (UBYTE *)value, (LONG)-1, (ULONG)GVF_LOCAL_ONLY)) return 0; /* success */ return -1; /* failure */ }
zyz2011-vim
src/os_amiga.c
C
gpl2
36,302
#!/bin/sh # toolcheck -- check for tools that have severe bugs. Good that all the buggy # tools identify by version numbers. This is the spirit of GNU :-) # # 24.7.95 jw. retval=0 reply="`sh -version -c exit 2>&1 < /dev/null`" case "$reply" in GNU*1.14.3*) echo "- sh is '$reply'"; echo " CAUTION: This shell has a buggy 'trap' command."; echo " The configure script may fail silently."; retval=1; ;; GNU*) echo "- sh is '$reply' - probably OK."; ;; *) ;; esac reply="`sed --version 2>&1 < /dev/null`" case "$reply" in GNU\ sed\ version\ 2.0[34]) echo "- sed is '$reply'"; echo " CAUTION: This sed cannot configure screen properly." retval=1; ;; GNU\ sed\ version\ 2.05|GNU\ sed\ version\ 2.03\ kevin) echo "- sed is '$reply' - good."; ;; GNU*) echo "- sed is '$reply'."; ;; *) ;; esac exit $retval
zyz2011-vim
src/toolcheck
Shell
gpl2
855
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * * (C) 2002,2005 by Marcin Dalecki <martin@dalecki.de> * * MARCIN DALECKI ASSUMES NO RESPONSIBILITY FOR THE USE OR INABILITY TO USE ANY * OF THIS SOFTWARE . THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY * KIND, AND MARCIN DALECKI EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES, * INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE. */ #ifndef EnhancedBP_H #define EnhancedBP_H #include <Xm/PushBP.h> #include "gui_xmebw.h" /* * EnahncedButton class structure. */ typedef struct _XmEnhancedButtonClassPart { Pixmap stipple_bitmap; } XmEnhancedButtonClassPart; /* * Full class record declaration for EnhancedButton class. */ typedef struct { CoreClassPart core_class; XmPrimitiveClassPart primitive_class; XmLabelClassPart label_class; XmPushButtonClassPart pushbutton_class; XmEnhancedButtonClassPart enhancedbutton_class; } XmEnhancedButtonClassRec; extern XmEnhancedButtonClassRec xmEnhancedButtonClassRec; /* * EnahncedButton instance record. */ typedef struct _XmEnhancedButtonPart { /* public resources */ String pixmap_data; String pixmap_file; Dimension spacing; int label_location; /* private resources */ int pixmap_depth; Dimension pixmap_width; Dimension pixmap_height; Pixmap normal_pixmap; Pixmap armed_pixmap; Pixmap insensitive_pixmap; Pixmap highlight_pixmap; int doing_setvalues; int doing_destroy; } XmEnhancedButtonPart; /* * Full instance record declaration. */ typedef struct _XmEnhancedButtonRec { CorePart core; XmPrimitivePart primitive; XmLabelPart label; XmPushButtonPart pushbutton; XmEnhancedButtonPart enhancedbutton; } XmEnhancedButtonRec; #endif
zyz2011-vim
src/gui_xmebwp.h
C
gpl2
2,053
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * ex_docmd.c: functions for executing an Ex command line. */ #include "vim.h" static int quitmore = 0; static int ex_pressedreturn = FALSE; #ifndef FEAT_PRINTER # define ex_hardcopy ex_ni #endif #ifdef FEAT_USR_CMDS typedef struct ucmd { char_u *uc_name; /* The command name */ long_u uc_argt; /* The argument type */ char_u *uc_rep; /* The command's replacement string */ long uc_def; /* The default value for a range/count */ int uc_compl; /* completion type */ # ifdef FEAT_EVAL scid_T uc_scriptID; /* SID where the command was defined */ # ifdef FEAT_CMDL_COMPL char_u *uc_compl_arg; /* completion argument if any */ # endif # endif } ucmd_T; #define UC_BUFFER 1 /* -buffer: local to current buffer */ static garray_T ucmds = {0, 0, sizeof(ucmd_T), 4, NULL}; #define USER_CMD(i) (&((ucmd_T *)(ucmds.ga_data))[i]) #define USER_CMD_GA(gap, i) (&((ucmd_T *)((gap)->ga_data))[i]) static void do_ucmd __ARGS((exarg_T *eap)); static void ex_command __ARGS((exarg_T *eap)); static void ex_delcommand __ARGS((exarg_T *eap)); # ifdef FEAT_CMDL_COMPL static char_u *get_user_command_name __ARGS((int idx)); # endif #else # define ex_command ex_ni # define ex_comclear ex_ni # define ex_delcommand ex_ni #endif #ifdef FEAT_EVAL static char_u *do_one_cmd __ARGS((char_u **, int, struct condstack *, char_u *(*fgetline)(int, void *, int), void *cookie)); #else static char_u *do_one_cmd __ARGS((char_u **, int, char_u *(*fgetline)(int, void *, int), void *cookie)); static int if_level = 0; /* depth in :if */ #endif static void append_command __ARGS((char_u *cmd)); static char_u *find_command __ARGS((exarg_T *eap, int *full)); static void ex_abbreviate __ARGS((exarg_T *eap)); static void ex_map __ARGS((exarg_T *eap)); static void ex_unmap __ARGS((exarg_T *eap)); static void ex_mapclear __ARGS((exarg_T *eap)); static void ex_abclear __ARGS((exarg_T *eap)); #ifndef FEAT_MENU # define ex_emenu ex_ni # define ex_menu ex_ni # define ex_menutranslate ex_ni #endif #ifdef FEAT_AUTOCMD static void ex_autocmd __ARGS((exarg_T *eap)); static void ex_doautocmd __ARGS((exarg_T *eap)); #else # define ex_autocmd ex_ni # define ex_doautocmd ex_ni # define ex_doautoall ex_ni #endif #ifdef FEAT_LISTCMDS static void ex_bunload __ARGS((exarg_T *eap)); static void ex_buffer __ARGS((exarg_T *eap)); static void ex_bmodified __ARGS((exarg_T *eap)); static void ex_bnext __ARGS((exarg_T *eap)); static void ex_bprevious __ARGS((exarg_T *eap)); static void ex_brewind __ARGS((exarg_T *eap)); static void ex_blast __ARGS((exarg_T *eap)); #else # define ex_bunload ex_ni # define ex_buffer ex_ni # define ex_bmodified ex_ni # define ex_bnext ex_ni # define ex_bprevious ex_ni # define ex_brewind ex_ni # define ex_blast ex_ni # define buflist_list ex_ni # define ex_checktime ex_ni #endif #if !defined(FEAT_LISTCMDS) || !defined(FEAT_WINDOWS) # define ex_buffer_all ex_ni #endif static char_u *getargcmd __ARGS((char_u **)); static char_u *skip_cmd_arg __ARGS((char_u *p, int rembs)); static int getargopt __ARGS((exarg_T *eap)); #ifndef FEAT_QUICKFIX # define ex_make ex_ni # define ex_cbuffer ex_ni # define ex_cc ex_ni # define ex_cnext ex_ni # define ex_cfile ex_ni # define qf_list ex_ni # define qf_age ex_ni # define ex_helpgrep ex_ni # define ex_vimgrep ex_ni #endif #if !defined(FEAT_QUICKFIX) || !defined(FEAT_WINDOWS) # define ex_cclose ex_ni # define ex_copen ex_ni # define ex_cwindow ex_ni #endif #if !defined(FEAT_QUICKFIX) || !defined(FEAT_EVAL) # define ex_cexpr ex_ni #endif static int check_more __ARGS((int, int)); static linenr_T get_address __ARGS((char_u **, int skip, int to_other_file)); static void get_flags __ARGS((exarg_T *eap)); #if !defined(FEAT_PERL) \ || !defined(FEAT_PYTHON) || !defined(FEAT_PYTHON3) \ || !defined(FEAT_TCL) \ || !defined(FEAT_RUBY) \ || !defined(FEAT_LUA) \ || !defined(FEAT_MZSCHEME) # define HAVE_EX_SCRIPT_NI static void ex_script_ni __ARGS((exarg_T *eap)); #endif static char_u *invalid_range __ARGS((exarg_T *eap)); static void correct_range __ARGS((exarg_T *eap)); #ifdef FEAT_QUICKFIX static char_u *replace_makeprg __ARGS((exarg_T *eap, char_u *p, char_u **cmdlinep)); #endif static char_u *repl_cmdline __ARGS((exarg_T *eap, char_u *src, int srclen, char_u *repl, char_u **cmdlinep)); static void ex_highlight __ARGS((exarg_T *eap)); static void ex_colorscheme __ARGS((exarg_T *eap)); static void ex_quit __ARGS((exarg_T *eap)); static void ex_cquit __ARGS((exarg_T *eap)); static void ex_quit_all __ARGS((exarg_T *eap)); #ifdef FEAT_WINDOWS static void ex_close __ARGS((exarg_T *eap)); static void ex_win_close __ARGS((int forceit, win_T *win, tabpage_T *tp)); static void ex_only __ARGS((exarg_T *eap)); static void ex_resize __ARGS((exarg_T *eap)); static void ex_stag __ARGS((exarg_T *eap)); static void ex_tabclose __ARGS((exarg_T *eap)); static void ex_tabonly __ARGS((exarg_T *eap)); static void ex_tabnext __ARGS((exarg_T *eap)); static void ex_tabmove __ARGS((exarg_T *eap)); static void ex_tabs __ARGS((exarg_T *eap)); #else # define ex_close ex_ni # define ex_only ex_ni # define ex_all ex_ni # define ex_resize ex_ni # define ex_splitview ex_ni # define ex_stag ex_ni # define ex_tabnext ex_ni # define ex_tabmove ex_ni # define ex_tabs ex_ni # define ex_tabclose ex_ni # define ex_tabonly ex_ni #endif #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX) static void ex_pclose __ARGS((exarg_T *eap)); static void ex_ptag __ARGS((exarg_T *eap)); static void ex_pedit __ARGS((exarg_T *eap)); #else # define ex_pclose ex_ni # define ex_ptag ex_ni # define ex_pedit ex_ni #endif static void ex_hide __ARGS((exarg_T *eap)); static void ex_stop __ARGS((exarg_T *eap)); static void ex_exit __ARGS((exarg_T *eap)); static void ex_print __ARGS((exarg_T *eap)); #ifdef FEAT_BYTEOFF static void ex_goto __ARGS((exarg_T *eap)); #else # define ex_goto ex_ni #endif static void ex_shell __ARGS((exarg_T *eap)); static void ex_preserve __ARGS((exarg_T *eap)); static void ex_recover __ARGS((exarg_T *eap)); #ifndef FEAT_LISTCMDS # define ex_argedit ex_ni # define ex_argadd ex_ni # define ex_argdelete ex_ni # define ex_listdo ex_ni #endif static void ex_mode __ARGS((exarg_T *eap)); static void ex_wrongmodifier __ARGS((exarg_T *eap)); static void ex_find __ARGS((exarg_T *eap)); static void ex_open __ARGS((exarg_T *eap)); static void ex_edit __ARGS((exarg_T *eap)); #if !defined(FEAT_GUI) && !defined(FEAT_CLIENTSERVER) # define ex_drop ex_ni #endif #ifndef FEAT_GUI # define ex_gui ex_nogui static void ex_nogui __ARGS((exarg_T *eap)); #endif #if defined(FEAT_GUI_W32) && defined(FEAT_MENU) && defined(FEAT_TEAROFF) static void ex_tearoff __ARGS((exarg_T *eap)); #else # define ex_tearoff ex_ni #endif #if (defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_GTK)) && defined(FEAT_MENU) static void ex_popup __ARGS((exarg_T *eap)); #else # define ex_popup ex_ni #endif #ifndef FEAT_GUI_MSWIN # define ex_simalt ex_ni #endif #if !defined(FEAT_GUI_MSWIN) && !defined(FEAT_GUI_GTK) && !defined(FEAT_GUI_MOTIF) # define gui_mch_find_dialog ex_ni # define gui_mch_replace_dialog ex_ni #endif #if !defined(FEAT_GUI_GTK) # define ex_helpfind ex_ni #endif #ifndef FEAT_CSCOPE # define do_cscope ex_ni # define do_scscope ex_ni # define do_cstag ex_ni #endif #ifndef FEAT_SYN_HL # define ex_syntax ex_ni # define ex_ownsyntax ex_ni #endif #ifndef FEAT_SPELL # define ex_spell ex_ni # define ex_mkspell ex_ni # define ex_spelldump ex_ni # define ex_spellinfo ex_ni # define ex_spellrepall ex_ni #endif #ifndef FEAT_PERSISTENT_UNDO # define ex_rundo ex_ni # define ex_wundo ex_ni #endif #ifndef FEAT_LUA # define ex_lua ex_script_ni # define ex_luado ex_ni # define ex_luafile ex_ni #endif #ifndef FEAT_MZSCHEME # define ex_mzscheme ex_script_ni # define ex_mzfile ex_ni #endif #ifndef FEAT_PERL # define ex_perl ex_script_ni # define ex_perldo ex_ni #endif #ifndef FEAT_PYTHON # define ex_python ex_script_ni # define ex_pyfile ex_ni #endif #ifndef FEAT_PYTHON3 # define ex_py3 ex_script_ni # define ex_py3file ex_ni #endif #ifndef FEAT_TCL # define ex_tcl ex_script_ni # define ex_tcldo ex_ni # define ex_tclfile ex_ni #endif #ifndef FEAT_RUBY # define ex_ruby ex_script_ni # define ex_rubydo ex_ni # define ex_rubyfile ex_ni #endif #ifndef FEAT_SNIFF # define ex_sniff ex_ni #endif #ifndef FEAT_KEYMAP # define ex_loadkeymap ex_ni #endif static void ex_swapname __ARGS((exarg_T *eap)); static void ex_syncbind __ARGS((exarg_T *eap)); static void ex_read __ARGS((exarg_T *eap)); static void ex_pwd __ARGS((exarg_T *eap)); static void ex_equal __ARGS((exarg_T *eap)); static void ex_sleep __ARGS((exarg_T *eap)); static void do_exmap __ARGS((exarg_T *eap, int isabbrev)); static void ex_winsize __ARGS((exarg_T *eap)); #ifdef FEAT_WINDOWS static void ex_wincmd __ARGS((exarg_T *eap)); #else # define ex_wincmd ex_ni #endif #if defined(FEAT_GUI) || defined(UNIX) || defined(VMS) || defined(MSWIN) static void ex_winpos __ARGS((exarg_T *eap)); #else # define ex_winpos ex_ni #endif static void ex_operators __ARGS((exarg_T *eap)); static void ex_put __ARGS((exarg_T *eap)); static void ex_copymove __ARGS((exarg_T *eap)); static void ex_may_print __ARGS((exarg_T *eap)); static void ex_submagic __ARGS((exarg_T *eap)); static void ex_join __ARGS((exarg_T *eap)); static void ex_at __ARGS((exarg_T *eap)); static void ex_bang __ARGS((exarg_T *eap)); static void ex_undo __ARGS((exarg_T *eap)); #ifdef FEAT_PERSISTENT_UNDO static void ex_wundo __ARGS((exarg_T *eap)); static void ex_rundo __ARGS((exarg_T *eap)); #endif static void ex_redo __ARGS((exarg_T *eap)); static void ex_later __ARGS((exarg_T *eap)); static void ex_redir __ARGS((exarg_T *eap)); static void ex_redraw __ARGS((exarg_T *eap)); static void ex_redrawstatus __ARGS((exarg_T *eap)); static void close_redir __ARGS((void)); static void ex_mkrc __ARGS((exarg_T *eap)); static void ex_mark __ARGS((exarg_T *eap)); #ifdef FEAT_USR_CMDS static char_u *uc_fun_cmd __ARGS((void)); static char_u *find_ucmd __ARGS((exarg_T *eap, char_u *p, int *full, expand_T *xp, int *compl)); #endif #ifdef FEAT_EX_EXTRA static void ex_normal __ARGS((exarg_T *eap)); static void ex_startinsert __ARGS((exarg_T *eap)); static void ex_stopinsert __ARGS((exarg_T *eap)); #else # define ex_normal ex_ni # define ex_align ex_ni # define ex_retab ex_ni # define ex_startinsert ex_ni # define ex_stopinsert ex_ni # define ex_helptags ex_ni # define ex_sort ex_ni #endif #ifdef FEAT_FIND_ID static void ex_checkpath __ARGS((exarg_T *eap)); static void ex_findpat __ARGS((exarg_T *eap)); #else # define ex_findpat ex_ni # define ex_checkpath ex_ni #endif #if defined(FEAT_FIND_ID) && defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX) static void ex_psearch __ARGS((exarg_T *eap)); #else # define ex_psearch ex_ni #endif static void ex_tag __ARGS((exarg_T *eap)); static void ex_tag_cmd __ARGS((exarg_T *eap, char_u *name)); #ifndef FEAT_EVAL # define ex_scriptnames ex_ni # define ex_finish ex_ni # define ex_echo ex_ni # define ex_echohl ex_ni # define ex_execute ex_ni # define ex_call ex_ni # define ex_if ex_ni # define ex_endif ex_ni # define ex_else ex_ni # define ex_while ex_ni # define ex_continue ex_ni # define ex_break ex_ni # define ex_endwhile ex_ni # define ex_throw ex_ni # define ex_try ex_ni # define ex_catch ex_ni # define ex_finally ex_ni # define ex_endtry ex_ni # define ex_endfunction ex_ni # define ex_let ex_ni # define ex_unlet ex_ni # define ex_lockvar ex_ni # define ex_unlockvar ex_ni # define ex_function ex_ni # define ex_delfunction ex_ni # define ex_return ex_ni # define ex_oldfiles ex_ni #endif static char_u *arg_all __ARGS((void)); #ifdef FEAT_SESSION static int makeopens __ARGS((FILE *fd, char_u *dirnow)); static int put_view __ARGS((FILE *fd, win_T *wp, int add_edit, unsigned *flagp, int current_arg_idx)); static void ex_loadview __ARGS((exarg_T *eap)); static char_u *get_view_file __ARGS((int c)); static int did_lcd; /* whether ":lcd" was produced for a session */ #else # define ex_loadview ex_ni #endif #ifndef FEAT_EVAL # define ex_compiler ex_ni #endif #ifdef FEAT_VIMINFO static void ex_viminfo __ARGS((exarg_T *eap)); #else # define ex_viminfo ex_ni #endif static void ex_behave __ARGS((exarg_T *eap)); #ifdef FEAT_AUTOCMD static void ex_filetype __ARGS((exarg_T *eap)); static void ex_setfiletype __ARGS((exarg_T *eap)); #else # define ex_filetype ex_ni # define ex_setfiletype ex_ni #endif #ifndef FEAT_DIFF # define ex_diffoff ex_ni # define ex_diffpatch ex_ni # define ex_diffgetput ex_ni # define ex_diffsplit ex_ni # define ex_diffthis ex_ni # define ex_diffupdate ex_ni #endif static void ex_digraphs __ARGS((exarg_T *eap)); static void ex_set __ARGS((exarg_T *eap)); #if !defined(FEAT_EVAL) || !defined(FEAT_AUTOCMD) # define ex_options ex_ni #endif #ifdef FEAT_SEARCH_EXTRA static void ex_nohlsearch __ARGS((exarg_T *eap)); static void ex_match __ARGS((exarg_T *eap)); #else # define ex_nohlsearch ex_ni # define ex_match ex_ni #endif #ifdef FEAT_CRYPT static void ex_X __ARGS((exarg_T *eap)); #else # define ex_X ex_ni #endif #ifdef FEAT_FOLDING static void ex_fold __ARGS((exarg_T *eap)); static void ex_foldopen __ARGS((exarg_T *eap)); static void ex_folddo __ARGS((exarg_T *eap)); #else # define ex_fold ex_ni # define ex_foldopen ex_ni # define ex_folddo ex_ni #endif #if !((defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \ && (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE))) # define ex_language ex_ni #endif #ifndef FEAT_SIGNS # define ex_sign ex_ni #endif #ifndef FEAT_SUN_WORKSHOP # define ex_wsverb ex_ni #endif #ifndef FEAT_NETBEANS_INTG # define ex_nbclose ex_ni # define ex_nbkey ex_ni # define ex_nbstart ex_ni #endif #ifndef FEAT_EVAL # define ex_debug ex_ni # define ex_breakadd ex_ni # define ex_debuggreedy ex_ni # define ex_breakdel ex_ni # define ex_breaklist ex_ni #endif #ifndef FEAT_CMDHIST # define ex_history ex_ni #endif #ifndef FEAT_JUMPLIST # define ex_jumps ex_ni # define ex_changes ex_ni #endif #ifndef FEAT_PROFILE # define ex_profile ex_ni #endif /* * Declare cmdnames[]. */ #define DO_DECLARE_EXCMD #include "ex_cmds.h" /* * Table used to quickly search for a command, based on its first character. */ static cmdidx_T cmdidxs[27] = { CMD_append, CMD_buffer, CMD_change, CMD_delete, CMD_edit, CMD_file, CMD_global, CMD_help, CMD_insert, CMD_join, CMD_k, CMD_list, CMD_move, CMD_next, CMD_open, CMD_print, CMD_quit, CMD_read, CMD_substitute, CMD_t, CMD_undo, CMD_vglobal, CMD_write, CMD_xit, CMD_yank, CMD_z, CMD_bang }; static char_u dollar_command[2] = {'$', 0}; #ifdef FEAT_EVAL /* Struct for storing a line inside a while/for loop */ typedef struct { char_u *line; /* command line */ linenr_T lnum; /* sourcing_lnum of the line */ } wcmd_T; /* * Structure used to store info for line position in a while or for loop. * This is required, because do_one_cmd() may invoke ex_function(), which * reads more lines that may come from the while/for loop. */ struct loop_cookie { garray_T *lines_gap; /* growarray with line info */ int current_line; /* last read line from growarray */ int repeating; /* TRUE when looping a second time */ /* When "repeating" is FALSE use "getline" and "cookie" to get lines */ char_u *(*getline) __ARGS((int, void *, int)); void *cookie; }; static char_u *get_loop_line __ARGS((int c, void *cookie, int indent)); static int store_loop_line __ARGS((garray_T *gap, char_u *line)); static void free_cmdlines __ARGS((garray_T *gap)); /* Struct to save a few things while debugging. Used in do_cmdline() only. */ struct dbg_stuff { int trylevel; int force_abort; except_T *caught_stack; char_u *vv_exception; char_u *vv_throwpoint; int did_emsg; int got_int; int did_throw; int need_rethrow; int check_cstack; except_T *current_exception; }; static void save_dbg_stuff __ARGS((struct dbg_stuff *dsp)); static void restore_dbg_stuff __ARGS((struct dbg_stuff *dsp)); static void save_dbg_stuff(dsp) struct dbg_stuff *dsp; { dsp->trylevel = trylevel; trylevel = 0; dsp->force_abort = force_abort; force_abort = FALSE; dsp->caught_stack = caught_stack; caught_stack = NULL; dsp->vv_exception = v_exception(NULL); dsp->vv_throwpoint = v_throwpoint(NULL); /* Necessary for debugging an inactive ":catch", ":finally", ":endtry" */ dsp->did_emsg = did_emsg; did_emsg = FALSE; dsp->got_int = got_int; got_int = FALSE; dsp->did_throw = did_throw; did_throw = FALSE; dsp->need_rethrow = need_rethrow; need_rethrow = FALSE; dsp->check_cstack = check_cstack; check_cstack = FALSE; dsp->current_exception = current_exception; current_exception = NULL; } static void restore_dbg_stuff(dsp) struct dbg_stuff *dsp; { suppress_errthrow = FALSE; trylevel = dsp->trylevel; force_abort = dsp->force_abort; caught_stack = dsp->caught_stack; (void)v_exception(dsp->vv_exception); (void)v_throwpoint(dsp->vv_throwpoint); did_emsg = dsp->did_emsg; got_int = dsp->got_int; did_throw = dsp->did_throw; need_rethrow = dsp->need_rethrow; check_cstack = dsp->check_cstack; current_exception = dsp->current_exception; } #endif /* * do_exmode(): Repeatedly get commands for the "Ex" mode, until the ":vi" * command is given. */ void do_exmode(improved) int improved; /* TRUE for "improved Ex" mode */ { int save_msg_scroll; int prev_msg_row; linenr_T prev_line; int changedtick; if (improved) exmode_active = EXMODE_VIM; else exmode_active = EXMODE_NORMAL; State = NORMAL; /* When using ":global /pat/ visual" and then "Q" we return to continue * the :global command. */ if (global_busy) return; save_msg_scroll = msg_scroll; ++RedrawingDisabled; /* don't redisplay the window */ ++no_wait_return; /* don't wait for return */ #ifdef FEAT_GUI /* Ignore scrollbar and mouse events in Ex mode */ ++hold_gui_events; #endif #ifdef FEAT_SNIFF want_sniff_request = 0; /* No K_SNIFF wanted */ #endif MSG(_("Entering Ex mode. Type \"visual\" to go to Normal mode.")); while (exmode_active) { #ifdef FEAT_EX_EXTRA /* Check for a ":normal" command and no more characters left. */ if (ex_normal_busy > 0 && typebuf.tb_len == 0) { exmode_active = FALSE; break; } #endif msg_scroll = TRUE; need_wait_return = FALSE; ex_pressedreturn = FALSE; ex_no_reprint = FALSE; changedtick = curbuf->b_changedtick; prev_msg_row = msg_row; prev_line = curwin->w_cursor.lnum; #ifdef FEAT_SNIFF ProcessSniffRequests(); #endif if (improved) { cmdline_row = msg_row; do_cmdline(NULL, getexline, NULL, 0); } else do_cmdline(NULL, getexmodeline, NULL, DOCMD_NOWAIT); lines_left = Rows - 1; if ((prev_line != curwin->w_cursor.lnum || changedtick != curbuf->b_changedtick) && !ex_no_reprint) { if (curbuf->b_ml.ml_flags & ML_EMPTY) EMSG(_(e_emptybuf)); else { if (ex_pressedreturn) { /* go up one line, to overwrite the ":<CR>" line, so the * output doesn't contain empty lines. */ msg_row = prev_msg_row; if (prev_msg_row == Rows - 1) msg_row--; } msg_col = 0; print_line_no_prefix(curwin->w_cursor.lnum, FALSE, FALSE); msg_clr_eos(); } } else if (ex_pressedreturn && !ex_no_reprint) /* must be at EOF */ { if (curbuf->b_ml.ml_flags & ML_EMPTY) EMSG(_(e_emptybuf)); else EMSG(_("E501: At end-of-file")); } } #ifdef FEAT_GUI --hold_gui_events; #endif --RedrawingDisabled; --no_wait_return; update_screen(CLEAR); need_wait_return = FALSE; msg_scroll = save_msg_scroll; } /* * Execute a simple command line. Used for translated commands like "*". */ int do_cmdline_cmd(cmd) char_u *cmd; { return do_cmdline(cmd, NULL, NULL, DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED); } /* * do_cmdline(): execute one Ex command line * * 1. Execute "cmdline" when it is not NULL. * If "cmdline" is NULL, or more lines are needed, fgetline() is used. * 2. Split up in parts separated with '|'. * * This function can be called recursively! * * flags: * DOCMD_VERBOSE - The command will be included in the error message. * DOCMD_NOWAIT - Don't call wait_return() and friends. * DOCMD_REPEAT - Repeat execution until fgetline() returns NULL. * DOCMD_KEYTYPED - Don't reset KeyTyped. * DOCMD_EXCRESET - Reset the exception environment (used for debugging). * DOCMD_KEEPLINE - Store first typed line (for repeating with "."). * * return FAIL if cmdline could not be executed, OK otherwise */ int do_cmdline(cmdline, fgetline, cookie, flags) char_u *cmdline; char_u *(*fgetline) __ARGS((int, void *, int)); void *cookie; /* argument for fgetline() */ int flags; { char_u *next_cmdline; /* next cmd to execute */ char_u *cmdline_copy = NULL; /* copy of cmd line */ int used_getline = FALSE; /* used "fgetline" to obtain command */ static int recursive = 0; /* recursive depth */ int msg_didout_before_start = 0; int count = 0; /* line number count */ int did_inc = FALSE; /* incremented RedrawingDisabled */ int retval = OK; #ifdef FEAT_EVAL struct condstack cstack; /* conditional stack */ garray_T lines_ga; /* keep lines for ":while"/":for" */ int current_line = 0; /* active line in lines_ga */ char_u *fname = NULL; /* function or script name */ linenr_T *breakpoint = NULL; /* ptr to breakpoint field in cookie */ int *dbg_tick = NULL; /* ptr to dbg_tick field in cookie */ struct dbg_stuff debug_saved; /* saved things for debug mode */ int initial_trylevel; struct msglist **saved_msg_list = NULL; struct msglist *private_msg_list; /* "fgetline" and "cookie" passed to do_one_cmd() */ char_u *(*cmd_getline) __ARGS((int, void *, int)); void *cmd_cookie; struct loop_cookie cmd_loop_cookie; void *real_cookie; int getline_is_func; #else # define cmd_getline fgetline # define cmd_cookie cookie #endif static int call_depth = 0; /* recursiveness */ #ifdef FEAT_EVAL /* For every pair of do_cmdline()/do_one_cmd() calls, use an extra memory * location for storing error messages to be converted to an exception. * This ensures that the do_errthrow() call in do_one_cmd() does not * combine the messages stored by an earlier invocation of do_one_cmd() * with the command name of the later one. This would happen when * BufWritePost autocommands are executed after a write error. */ saved_msg_list = msg_list; msg_list = &private_msg_list; private_msg_list = NULL; #endif /* It's possible to create an endless loop with ":execute", catch that * here. The value of 200 allows nested function calls, ":source", etc. */ if (call_depth == 200) { EMSG(_("E169: Command too recursive")); #ifdef FEAT_EVAL /* When converting to an exception, we do not include the command name * since this is not an error of the specific command. */ do_errthrow((struct condstack *)NULL, (char_u *)NULL); msg_list = saved_msg_list; #endif return FAIL; } ++call_depth; #ifdef FEAT_EVAL cstack.cs_idx = -1; cstack.cs_looplevel = 0; cstack.cs_trylevel = 0; cstack.cs_emsg_silent_list = NULL; cstack.cs_lflags = 0; ga_init2(&lines_ga, (int)sizeof(wcmd_T), 10); real_cookie = getline_cookie(fgetline, cookie); /* Inside a function use a higher nesting level. */ getline_is_func = getline_equal(fgetline, cookie, get_func_line); if (getline_is_func && ex_nesting_level == func_level(real_cookie)) ++ex_nesting_level; /* Get the function or script name and the address where the next breakpoint * line and the debug tick for a function or script are stored. */ if (getline_is_func) { fname = func_name(real_cookie); breakpoint = func_breakpoint(real_cookie); dbg_tick = func_dbg_tick(real_cookie); } else if (getline_equal(fgetline, cookie, getsourceline)) { fname = sourcing_name; breakpoint = source_breakpoint(real_cookie); dbg_tick = source_dbg_tick(real_cookie); } /* * Initialize "force_abort" and "suppress_errthrow" at the top level. */ if (!recursive) { force_abort = FALSE; suppress_errthrow = FALSE; } /* * If requested, store and reset the global values controlling the * exception handling (used when debugging). Otherwise clear it to avoid * a bogus compiler warning when the optimizer uses inline functions... */ if (flags & DOCMD_EXCRESET) save_dbg_stuff(&debug_saved); else vim_memset(&debug_saved, 0, 1); initial_trylevel = trylevel; /* * "did_throw" will be set to TRUE when an exception is being thrown. */ did_throw = FALSE; #endif /* * "did_emsg" will be set to TRUE when emsg() is used, in which case we * cancel the whole command line, and any if/endif or loop. * If force_abort is set, we cancel everything. */ did_emsg = FALSE; /* * KeyTyped is only set when calling vgetc(). Reset it here when not * calling vgetc() (sourced command lines). */ if (!(flags & DOCMD_KEYTYPED) && !getline_equal(fgetline, cookie, getexline)) KeyTyped = FALSE; /* * Continue executing command lines: * - when inside an ":if", ":while" or ":for" * - for multiple commands on one line, separated with '|' * - when repeating until there are no more lines (for ":source") */ next_cmdline = cmdline; do { #ifdef FEAT_EVAL getline_is_func = getline_equal(fgetline, cookie, get_func_line); #endif /* stop skipping cmds for an error msg after all endif/while/for */ if (next_cmdline == NULL #ifdef FEAT_EVAL && !force_abort && cstack.cs_idx < 0 && !(getline_is_func && func_has_abort(real_cookie)) #endif ) did_emsg = FALSE; /* * 1. If repeating a line in a loop, get a line from lines_ga. * 2. If no line given: Get an allocated line with fgetline(). * 3. If a line is given: Make a copy, so we can mess with it. */ #ifdef FEAT_EVAL /* 1. If repeating, get a previous line from lines_ga. */ if (cstack.cs_looplevel > 0 && current_line < lines_ga.ga_len) { /* Each '|' separated command is stored separately in lines_ga, to * be able to jump to it. Don't use next_cmdline now. */ vim_free(cmdline_copy); cmdline_copy = NULL; /* Check if a function has returned or, unless it has an unclosed * try conditional, aborted. */ if (getline_is_func) { # ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_end(real_cookie); # endif if (func_has_ended(real_cookie)) { retval = FAIL; break; } } #ifdef FEAT_PROFILE else if (do_profiling == PROF_YES && getline_equal(fgetline, cookie, getsourceline)) script_line_end(); #endif /* Check if a sourced file hit a ":finish" command. */ if (source_finished(fgetline, cookie)) { retval = FAIL; break; } /* If breakpoints have been added/deleted need to check for it. */ if (breakpoint != NULL && dbg_tick != NULL && *dbg_tick != debug_tick) { *breakpoint = dbg_find_breakpoint( getline_equal(fgetline, cookie, getsourceline), fname, sourcing_lnum); *dbg_tick = debug_tick; } next_cmdline = ((wcmd_T *)(lines_ga.ga_data))[current_line].line; sourcing_lnum = ((wcmd_T *)(lines_ga.ga_data))[current_line].lnum; /* Did we encounter a breakpoint? */ if (breakpoint != NULL && *breakpoint != 0 && *breakpoint <= sourcing_lnum) { dbg_breakpoint(fname, sourcing_lnum); /* Find next breakpoint. */ *breakpoint = dbg_find_breakpoint( getline_equal(fgetline, cookie, getsourceline), fname, sourcing_lnum); *dbg_tick = debug_tick; } # ifdef FEAT_PROFILE if (do_profiling == PROF_YES) { if (getline_is_func) func_line_start(real_cookie); else if (getline_equal(fgetline, cookie, getsourceline)) script_line_start(); } # endif } if (cstack.cs_looplevel > 0) { /* Inside a while/for loop we need to store the lines and use them * again. Pass a different "fgetline" function to do_one_cmd() * below, so that it stores lines in or reads them from * "lines_ga". Makes it possible to define a function inside a * while/for loop. */ cmd_getline = get_loop_line; cmd_cookie = (void *)&cmd_loop_cookie; cmd_loop_cookie.lines_gap = &lines_ga; cmd_loop_cookie.current_line = current_line; cmd_loop_cookie.getline = fgetline; cmd_loop_cookie.cookie = cookie; cmd_loop_cookie.repeating = (current_line < lines_ga.ga_len); } else { cmd_getline = fgetline; cmd_cookie = cookie; } #endif /* 2. If no line given, get an allocated line with fgetline(). */ if (next_cmdline == NULL) { /* * Need to set msg_didout for the first line after an ":if", * otherwise the ":if" will be overwritten. */ if (count == 1 && getline_equal(fgetline, cookie, getexline)) msg_didout = TRUE; if (fgetline == NULL || (next_cmdline = fgetline(':', cookie, #ifdef FEAT_EVAL cstack.cs_idx < 0 ? 0 : (cstack.cs_idx + 1) * 2 #else 0 #endif )) == NULL) { /* Don't call wait_return for aborted command line. The NULL * returned for the end of a sourced file or executed function * doesn't do this. */ if (KeyTyped && !(flags & DOCMD_REPEAT)) need_wait_return = FALSE; retval = FAIL; break; } used_getline = TRUE; /* * Keep the first typed line. Clear it when more lines are typed. */ if (flags & DOCMD_KEEPLINE) { vim_free(repeat_cmdline); if (count == 0) repeat_cmdline = vim_strsave(next_cmdline); else repeat_cmdline = NULL; } } /* 3. Make a copy of the command so we can mess with it. */ else if (cmdline_copy == NULL) { next_cmdline = vim_strsave(next_cmdline); if (next_cmdline == NULL) { EMSG(_(e_outofmem)); retval = FAIL; break; } } cmdline_copy = next_cmdline; #ifdef FEAT_EVAL /* * Save the current line when inside a ":while" or ":for", and when * the command looks like a ":while" or ":for", because we may need it * later. When there is a '|' and another command, it is stored * separately, because we need to be able to jump back to it from an * :endwhile/:endfor. */ if (current_line == lines_ga.ga_len && (cstack.cs_looplevel || has_loop_cmd(next_cmdline))) { if (store_loop_line(&lines_ga, next_cmdline) == FAIL) { retval = FAIL; break; } } did_endif = FALSE; #endif if (count++ == 0) { /* * All output from the commands is put below each other, without * waiting for a return. Don't do this when executing commands * from a script or when being called recursive (e.g. for ":e * +command file"). */ if (!(flags & DOCMD_NOWAIT) && !recursive) { msg_didout_before_start = msg_didout; msg_didany = FALSE; /* no output yet */ msg_start(); msg_scroll = TRUE; /* put messages below each other */ ++no_wait_return; /* dont wait for return until finished */ ++RedrawingDisabled; did_inc = TRUE; } } if (p_verbose >= 15 && sourcing_name != NULL) { ++no_wait_return; verbose_enter_scroll(); smsg((char_u *)_("line %ld: %s"), (long)sourcing_lnum, cmdline_copy); if (msg_silent == 0) msg_puts((char_u *)"\n"); /* don't overwrite this */ verbose_leave_scroll(); --no_wait_return; } /* * 2. Execute one '|' separated command. * do_one_cmd() will return NULL if there is no trailing '|'. * "cmdline_copy" can change, e.g. for '%' and '#' expansion. */ ++recursive; next_cmdline = do_one_cmd(&cmdline_copy, flags & DOCMD_VERBOSE, #ifdef FEAT_EVAL &cstack, #endif cmd_getline, cmd_cookie); --recursive; #ifdef FEAT_EVAL if (cmd_cookie == (void *)&cmd_loop_cookie) /* Use "current_line" from "cmd_loop_cookie", it may have been * incremented when defining a function. */ current_line = cmd_loop_cookie.current_line; #endif if (next_cmdline == NULL) { vim_free(cmdline_copy); cmdline_copy = NULL; #ifdef FEAT_CMDHIST /* * If the command was typed, remember it for the ':' register. * Do this AFTER executing the command to make :@: work. */ if (getline_equal(fgetline, cookie, getexline) && new_last_cmdline != NULL) { vim_free(last_cmdline); last_cmdline = new_last_cmdline; new_last_cmdline = NULL; } #endif } else { /* need to copy the command after the '|' to cmdline_copy, for the * next do_one_cmd() */ STRMOVE(cmdline_copy, next_cmdline); next_cmdline = cmdline_copy; } #ifdef FEAT_EVAL /* reset did_emsg for a function that is not aborted by an error */ if (did_emsg && !force_abort && getline_equal(fgetline, cookie, get_func_line) && !func_has_abort(real_cookie)) did_emsg = FALSE; if (cstack.cs_looplevel > 0) { ++current_line; /* * An ":endwhile", ":endfor" and ":continue" is handled here. * If we were executing commands, jump back to the ":while" or * ":for". * If we were not executing commands, decrement cs_looplevel. */ if (cstack.cs_lflags & (CSL_HAD_CONT | CSL_HAD_ENDLOOP)) { cstack.cs_lflags &= ~(CSL_HAD_CONT | CSL_HAD_ENDLOOP); /* Jump back to the matching ":while" or ":for". Be careful * not to use a cs_line[] from an entry that isn't a ":while" * or ":for": It would make "current_line" invalid and can * cause a crash. */ if (!did_emsg && !got_int && !did_throw && cstack.cs_idx >= 0 && (cstack.cs_flags[cstack.cs_idx] & (CSF_WHILE | CSF_FOR)) && cstack.cs_line[cstack.cs_idx] >= 0 && (cstack.cs_flags[cstack.cs_idx] & CSF_ACTIVE)) { current_line = cstack.cs_line[cstack.cs_idx]; /* remember we jumped there */ cstack.cs_lflags |= CSL_HAD_LOOP; line_breakcheck(); /* check if CTRL-C typed */ /* Check for the next breakpoint at or after the ":while" * or ":for". */ if (breakpoint != NULL) { *breakpoint = dbg_find_breakpoint( getline_equal(fgetline, cookie, getsourceline), fname, ((wcmd_T *)lines_ga.ga_data)[current_line].lnum-1); *dbg_tick = debug_tick; } } else { /* can only get here with ":endwhile" or ":endfor" */ if (cstack.cs_idx >= 0) rewind_conditionals(&cstack, cstack.cs_idx - 1, CSF_WHILE | CSF_FOR, &cstack.cs_looplevel); } } /* * For a ":while" or ":for" we need to remember the line number. */ else if (cstack.cs_lflags & CSL_HAD_LOOP) { cstack.cs_lflags &= ~CSL_HAD_LOOP; cstack.cs_line[cstack.cs_idx] = current_line - 1; } } /* * When not inside any ":while" loop, clear remembered lines. */ if (cstack.cs_looplevel == 0) { if (lines_ga.ga_len > 0) { sourcing_lnum = ((wcmd_T *)lines_ga.ga_data)[lines_ga.ga_len - 1].lnum; free_cmdlines(&lines_ga); } current_line = 0; } /* * A ":finally" makes did_emsg, got_int, and did_throw pending for * being restored at the ":endtry". Reset them here and set the * ACTIVE and FINALLY flags, so that the finally clause gets executed. * This includes the case where a missing ":endif", ":endwhile" or * ":endfor" was detected by the ":finally" itself. */ if (cstack.cs_lflags & CSL_HAD_FINA) { cstack.cs_lflags &= ~CSL_HAD_FINA; report_make_pending(cstack.cs_pending[cstack.cs_idx] & (CSTP_ERROR | CSTP_INTERRUPT | CSTP_THROW), did_throw ? (void *)current_exception : NULL); did_emsg = got_int = did_throw = FALSE; cstack.cs_flags[cstack.cs_idx] |= CSF_ACTIVE | CSF_FINALLY; } /* Update global "trylevel" for recursive calls to do_cmdline() from * within this loop. */ trylevel = initial_trylevel + cstack.cs_trylevel; /* * If the outermost try conditional (across function calls and sourced * files) is aborted because of an error, an interrupt, or an uncaught * exception, cancel everything. If it is left normally, reset * force_abort to get the non-EH compatible abortion behavior for * the rest of the script. */ if (trylevel == 0 && !did_emsg && !got_int && !did_throw) force_abort = FALSE; /* Convert an interrupt to an exception if appropriate. */ (void)do_intthrow(&cstack); #endif /* FEAT_EVAL */ } /* * Continue executing command lines when: * - no CTRL-C typed, no aborting error, no exception thrown or try * conditionals need to be checked for executing finally clauses or * catching an interrupt exception * - didn't get an error message or lines are not typed * - there is a command after '|', inside a :if, :while, :for or :try, or * looping for ":source" command or function call. */ while (!((got_int #ifdef FEAT_EVAL || (did_emsg && force_abort) || did_throw #endif ) #ifdef FEAT_EVAL && cstack.cs_trylevel == 0 #endif ) && !(did_emsg && used_getline && (getline_equal(fgetline, cookie, getexmodeline) || getline_equal(fgetline, cookie, getexline))) && (next_cmdline != NULL #ifdef FEAT_EVAL || cstack.cs_idx >= 0 #endif || (flags & DOCMD_REPEAT))); vim_free(cmdline_copy); #ifdef FEAT_EVAL free_cmdlines(&lines_ga); ga_clear(&lines_ga); if (cstack.cs_idx >= 0) { /* * If a sourced file or executed function ran to its end, report the * unclosed conditional. */ if (!got_int && !did_throw && ((getline_equal(fgetline, cookie, getsourceline) && !source_finished(fgetline, cookie)) || (getline_equal(fgetline, cookie, get_func_line) && !func_has_ended(real_cookie)))) { if (cstack.cs_flags[cstack.cs_idx] & CSF_TRY) EMSG(_(e_endtry)); else if (cstack.cs_flags[cstack.cs_idx] & CSF_WHILE) EMSG(_(e_endwhile)); else if (cstack.cs_flags[cstack.cs_idx] & CSF_FOR) EMSG(_(e_endfor)); else EMSG(_(e_endif)); } /* * Reset "trylevel" in case of a ":finish" or ":return" or a missing * ":endtry" in a sourced file or executed function. If the try * conditional is in its finally clause, ignore anything pending. * If it is in a catch clause, finish the caught exception. * Also cleanup any "cs_forinfo" structures. */ do { int idx = cleanup_conditionals(&cstack, 0, TRUE); if (idx >= 0) --idx; /* remove try block not in its finally clause */ rewind_conditionals(&cstack, idx, CSF_WHILE | CSF_FOR, &cstack.cs_looplevel); } while (cstack.cs_idx >= 0); trylevel = initial_trylevel; } /* If a missing ":endtry", ":endwhile", ":endfor", or ":endif" or a memory * lack was reported above and the error message is to be converted to an * exception, do this now after rewinding the cstack. */ do_errthrow(&cstack, getline_equal(fgetline, cookie, get_func_line) ? (char_u *)"endfunction" : (char_u *)NULL); if (trylevel == 0) { /* * When an exception is being thrown out of the outermost try * conditional, discard the uncaught exception, disable the conversion * of interrupts or errors to exceptions, and ensure that no more * commands are executed. */ if (did_throw) { void *p = NULL; char_u *saved_sourcing_name; int saved_sourcing_lnum; struct msglist *messages = NULL, *next; /* * If the uncaught exception is a user exception, report it as an * error. If it is an error exception, display the saved error * message now. For an interrupt exception, do nothing; the * interrupt message is given elsewhere. */ switch (current_exception->type) { case ET_USER: vim_snprintf((char *)IObuff, IOSIZE, _("E605: Exception not caught: %s"), current_exception->value); p = vim_strsave(IObuff); break; case ET_ERROR: messages = current_exception->messages; current_exception->messages = NULL; break; case ET_INTERRUPT: break; default: p = vim_strsave((char_u *)_(e_internal)); } saved_sourcing_name = sourcing_name; saved_sourcing_lnum = sourcing_lnum; sourcing_name = current_exception->throw_name; sourcing_lnum = current_exception->throw_lnum; current_exception->throw_name = NULL; discard_current_exception(); /* uses IObuff if 'verbose' */ suppress_errthrow = TRUE; force_abort = TRUE; if (messages != NULL) { do { next = messages->next; emsg(messages->msg); vim_free(messages->msg); vim_free(messages); messages = next; } while (messages != NULL); } else if (p != NULL) { emsg(p); vim_free(p); } vim_free(sourcing_name); sourcing_name = saved_sourcing_name; sourcing_lnum = saved_sourcing_lnum; } /* * On an interrupt or an aborting error not converted to an exception, * disable the conversion of errors to exceptions. (Interrupts are not * converted any more, here.) This enables also the interrupt message * when force_abort is set and did_emsg unset in case of an interrupt * from a finally clause after an error. */ else if (got_int || (did_emsg && force_abort)) suppress_errthrow = TRUE; } /* * The current cstack will be freed when do_cmdline() returns. An uncaught * exception will have to be rethrown in the previous cstack. If a function * has just returned or a script file was just finished and the previous * cstack belongs to the same function or, respectively, script file, it * will have to be checked for finally clauses to be executed due to the * ":return" or ":finish". This is done in do_one_cmd(). */ if (did_throw) need_rethrow = TRUE; if ((getline_equal(fgetline, cookie, getsourceline) && ex_nesting_level > source_level(real_cookie)) || (getline_equal(fgetline, cookie, get_func_line) && ex_nesting_level > func_level(real_cookie) + 1)) { if (!did_throw) check_cstack = TRUE; } else { /* When leaving a function, reduce nesting level. */ if (getline_equal(fgetline, cookie, get_func_line)) --ex_nesting_level; /* * Go to debug mode when returning from a function in which we are * single-stepping. */ if ((getline_equal(fgetline, cookie, getsourceline) || getline_equal(fgetline, cookie, get_func_line)) && ex_nesting_level + 1 <= debug_break_level) do_debug(getline_equal(fgetline, cookie, getsourceline) ? (char_u *)_("End of sourced file") : (char_u *)_("End of function")); } /* * Restore the exception environment (done after returning from the * debugger). */ if (flags & DOCMD_EXCRESET) restore_dbg_stuff(&debug_saved); msg_list = saved_msg_list; #endif /* FEAT_EVAL */ /* * If there was too much output to fit on the command line, ask the user to * hit return before redrawing the screen. With the ":global" command we do * this only once after the command is finished. */ if (did_inc) { --RedrawingDisabled; --no_wait_return; msg_scroll = FALSE; /* * When just finished an ":if"-":else" which was typed, no need to * wait for hit-return. Also for an error situation. */ if (retval == FAIL #ifdef FEAT_EVAL || (did_endif && KeyTyped && !did_emsg) #endif ) { need_wait_return = FALSE; msg_didany = FALSE; /* don't wait when restarting edit */ } else if (need_wait_return) { /* * The msg_start() above clears msg_didout. The wait_return we do * here should not overwrite the command that may be shown before * doing that. */ msg_didout |= msg_didout_before_start; wait_return(FALSE); } } #ifndef FEAT_EVAL /* * Reset if_level, in case a sourced script file contains more ":if" than * ":endif" (could be ":if x | foo | endif"). */ if_level = 0; #endif --call_depth; return retval; } #ifdef FEAT_EVAL /* * Obtain a line when inside a ":while" or ":for" loop. */ static char_u * get_loop_line(c, cookie, indent) int c; void *cookie; int indent; { struct loop_cookie *cp = (struct loop_cookie *)cookie; wcmd_T *wp; char_u *line; if (cp->current_line + 1 >= cp->lines_gap->ga_len) { if (cp->repeating) return NULL; /* trying to read past ":endwhile"/":endfor" */ /* First time inside the ":while"/":for": get line normally. */ if (cp->getline == NULL) line = getcmdline(c, 0L, indent); else line = cp->getline(c, cp->cookie, indent); if (line != NULL && store_loop_line(cp->lines_gap, line) == OK) ++cp->current_line; return line; } KeyTyped = FALSE; ++cp->current_line; wp = (wcmd_T *)(cp->lines_gap->ga_data) + cp->current_line; sourcing_lnum = wp->lnum; return vim_strsave(wp->line); } /* * Store a line in "gap" so that a ":while" loop can execute it again. */ static int store_loop_line(gap, line) garray_T *gap; char_u *line; { if (ga_grow(gap, 1) == FAIL) return FAIL; ((wcmd_T *)(gap->ga_data))[gap->ga_len].line = vim_strsave(line); ((wcmd_T *)(gap->ga_data))[gap->ga_len].lnum = sourcing_lnum; ++gap->ga_len; return OK; } /* * Free the lines stored for a ":while" or ":for" loop. */ static void free_cmdlines(gap) garray_T *gap; { while (gap->ga_len > 0) { vim_free(((wcmd_T *)(gap->ga_data))[gap->ga_len - 1].line); --gap->ga_len; } } #endif /* * If "fgetline" is get_loop_line(), return TRUE if the getline it uses equals * "func". * Otherwise return TRUE when "fgetline" equals "func". */ int getline_equal(fgetline, cookie, func) char_u *(*fgetline) __ARGS((int, void *, int)); void *cookie UNUSED; /* argument for fgetline() */ char_u *(*func) __ARGS((int, void *, int)); { #ifdef FEAT_EVAL char_u *(*gp) __ARGS((int, void *, int)); struct loop_cookie *cp; /* When "fgetline" is "get_loop_line()" use the "cookie" to find the * function that's originally used to obtain the lines. This may be * nested several levels. */ gp = fgetline; cp = (struct loop_cookie *)cookie; while (gp == get_loop_line) { gp = cp->getline; cp = cp->cookie; } return gp == func; #else return fgetline == func; #endif } #if defined(FEAT_EVAL) || defined(FEAT_MBYTE) || defined(PROTO) /* * If "fgetline" is get_loop_line(), return the cookie used by the original * getline function. Otherwise return "cookie". */ void * getline_cookie(fgetline, cookie) char_u *(*fgetline) __ARGS((int, void *, int)) UNUSED; void *cookie; /* argument for fgetline() */ { # ifdef FEAT_EVAL char_u *(*gp) __ARGS((int, void *, int)); struct loop_cookie *cp; /* When "fgetline" is "get_loop_line()" use the "cookie" to find the * cookie that's originally used to obtain the lines. This may be nested * several levels. */ gp = fgetline; cp = (struct loop_cookie *)cookie; while (gp == get_loop_line) { gp = cp->getline; cp = cp->cookie; } return cp; # else return cookie; # endif } #endif /* * Execute one Ex command. * * If 'sourcing' is TRUE, the command will be included in the error message. * * 1. skip comment lines and leading space * 2. handle command modifiers * 3. parse range * 4. parse command * 5. parse arguments * 6. switch on command name * * Note: "fgetline" can be NULL. * * This function may be called recursively! */ #if (_MSC_VER == 1200) /* * Avoid optimisation bug in VC++ version 6.0 */ #pragma optimize( "g", off ) #endif static char_u * do_one_cmd(cmdlinep, sourcing, #ifdef FEAT_EVAL cstack, #endif fgetline, cookie) char_u **cmdlinep; int sourcing; #ifdef FEAT_EVAL struct condstack *cstack; #endif char_u *(*fgetline) __ARGS((int, void *, int)); void *cookie; /* argument for fgetline() */ { char_u *p; linenr_T lnum; long n; char_u *errormsg = NULL; /* error message */ exarg_T ea; /* Ex command arguments */ long verbose_save = -1; int save_msg_scroll = msg_scroll; int save_msg_silent = -1; int did_esilent = 0; #ifdef HAVE_SANDBOX int did_sandbox = FALSE; #endif cmdmod_T save_cmdmod; int ni; /* set when Not Implemented */ vim_memset(&ea, 0, sizeof(ea)); ea.line1 = 1; ea.line2 = 1; #ifdef FEAT_EVAL ++ex_nesting_level; #endif /* when not editing the last file :q has to be typed twice */ if (quitmore #ifdef FEAT_EVAL /* avoid that a function call in 'statusline' does this */ && !getline_equal(fgetline, cookie, get_func_line) #endif ) --quitmore; /* * Reset browse, confirm, etc.. They are restored when returning, for * recursive calls. */ save_cmdmod = cmdmod; vim_memset(&cmdmod, 0, sizeof(cmdmod)); /* "#!anything" is handled like a comment. */ if ((*cmdlinep)[0] == '#' && (*cmdlinep)[1] == '!') goto doend; /* * Repeat until no more command modifiers are found. */ ea.cmd = *cmdlinep; for (;;) { /* * 1. skip comment lines and leading white space and colons */ while (*ea.cmd == ' ' || *ea.cmd == '\t' || *ea.cmd == ':') ++ea.cmd; /* in ex mode, an empty line works like :+ */ if (*ea.cmd == NUL && exmode_active && (getline_equal(fgetline, cookie, getexmodeline) || getline_equal(fgetline, cookie, getexline)) && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count) { ea.cmd = (char_u *)"+"; ex_pressedreturn = TRUE; } /* ignore comment and empty lines */ if (*ea.cmd == '"') goto doend; if (*ea.cmd == NUL) { ex_pressedreturn = TRUE; goto doend; } /* * 2. handle command modifiers. */ p = ea.cmd; if (VIM_ISDIGIT(*ea.cmd)) p = skipwhite(skipdigits(ea.cmd)); switch (*p) { /* When adding an entry, also modify cmd_exists(). */ case 'a': if (!checkforcmd(&ea.cmd, "aboveleft", 3)) break; #ifdef FEAT_WINDOWS cmdmod.split |= WSP_ABOVE; #endif continue; case 'b': if (checkforcmd(&ea.cmd, "belowright", 3)) { #ifdef FEAT_WINDOWS cmdmod.split |= WSP_BELOW; #endif continue; } if (checkforcmd(&ea.cmd, "browse", 3)) { #ifdef FEAT_BROWSE_CMD cmdmod.browse = TRUE; #endif continue; } if (!checkforcmd(&ea.cmd, "botright", 2)) break; #ifdef FEAT_WINDOWS cmdmod.split |= WSP_BOT; #endif continue; case 'c': if (!checkforcmd(&ea.cmd, "confirm", 4)) break; #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) cmdmod.confirm = TRUE; #endif continue; case 'k': if (checkforcmd(&ea.cmd, "keepmarks", 3)) { cmdmod.keepmarks = TRUE; continue; } if (checkforcmd(&ea.cmd, "keepalt", 5)) { cmdmod.keepalt = TRUE; continue; } if (!checkforcmd(&ea.cmd, "keepjumps", 5)) break; cmdmod.keepjumps = TRUE; continue; /* ":hide" and ":hide | cmd" are not modifiers */ case 'h': if (p != ea.cmd || !checkforcmd(&p, "hide", 3) || *p == NUL || ends_excmd(*p)) break; ea.cmd = p; cmdmod.hide = TRUE; continue; case 'l': if (checkforcmd(&ea.cmd, "lockmarks", 3)) { cmdmod.lockmarks = TRUE; continue; } if (!checkforcmd(&ea.cmd, "leftabove", 5)) break; #ifdef FEAT_WINDOWS cmdmod.split |= WSP_ABOVE; #endif continue; case 'n': if (!checkforcmd(&ea.cmd, "noautocmd", 3)) break; #ifdef FEAT_AUTOCMD if (cmdmod.save_ei == NULL) { /* Set 'eventignore' to "all". Restore the * existing option value later. */ cmdmod.save_ei = vim_strsave(p_ei); set_string_option_direct((char_u *)"ei", -1, (char_u *)"all", OPT_FREE, SID_NONE); } #endif continue; case 'r': if (!checkforcmd(&ea.cmd, "rightbelow", 6)) break; #ifdef FEAT_WINDOWS cmdmod.split |= WSP_BELOW; #endif continue; case 's': if (checkforcmd(&ea.cmd, "sandbox", 3)) { #ifdef HAVE_SANDBOX if (!did_sandbox) ++sandbox; did_sandbox = TRUE; #endif continue; } if (!checkforcmd(&ea.cmd, "silent", 3)) break; if (save_msg_silent == -1) save_msg_silent = msg_silent; ++msg_silent; if (*ea.cmd == '!' && !vim_iswhite(ea.cmd[-1])) { /* ":silent!", but not "silent !cmd" */ ea.cmd = skipwhite(ea.cmd + 1); ++emsg_silent; ++did_esilent; } continue; case 't': if (checkforcmd(&p, "tab", 3)) { #ifdef FEAT_WINDOWS if (vim_isdigit(*ea.cmd)) cmdmod.tab = atoi((char *)ea.cmd) + 1; else cmdmod.tab = tabpage_index(curtab) + 1; ea.cmd = p; #endif continue; } if (!checkforcmd(&ea.cmd, "topleft", 2)) break; #ifdef FEAT_WINDOWS cmdmod.split |= WSP_TOP; #endif continue; case 'u': if (!checkforcmd(&ea.cmd, "unsilent", 3)) break; if (save_msg_silent == -1) save_msg_silent = msg_silent; msg_silent = 0; continue; case 'v': if (checkforcmd(&ea.cmd, "vertical", 4)) { #ifdef FEAT_VERTSPLIT cmdmod.split |= WSP_VERT; #endif continue; } if (!checkforcmd(&p, "verbose", 4)) break; if (verbose_save < 0) verbose_save = p_verbose; if (vim_isdigit(*ea.cmd)) p_verbose = atoi((char *)ea.cmd); else p_verbose = 1; ea.cmd = p; continue; } break; } #ifdef FEAT_EVAL ea.skip = did_emsg || got_int || did_throw || (cstack->cs_idx >= 0 && !(cstack->cs_flags[cstack->cs_idx] & CSF_ACTIVE)); #else ea.skip = (if_level > 0); #endif #ifdef FEAT_EVAL # ifdef FEAT_PROFILE /* Count this line for profiling if ea.skip is FALSE. */ if (do_profiling == PROF_YES && !ea.skip) { if (getline_equal(fgetline, cookie, get_func_line)) func_line_exec(getline_cookie(fgetline, cookie)); else if (getline_equal(fgetline, cookie, getsourceline)) script_line_exec(); } #endif /* May go to debug mode. If this happens and the ">quit" debug command is * used, throw an interrupt exception and skip the next command. */ dbg_check_breakpoint(&ea); if (!ea.skip && got_int) { ea.skip = TRUE; (void)do_intthrow(cstack); } #endif /* * 3. parse a range specifier of the form: addr [,addr] [;addr] .. * * where 'addr' is: * * % (entire file) * $ [+-NUM] * 'x [+-NUM] (where x denotes a currently defined mark) * . [+-NUM] * [+-NUM].. * NUM * * The ea.cmd pointer is updated to point to the first character following the * range spec. If an initial address is found, but no second, the upper bound * is equal to the lower. */ /* repeat for all ',' or ';' separated addresses */ for (;;) { ea.line1 = ea.line2; ea.line2 = curwin->w_cursor.lnum; /* default is current line number */ ea.cmd = skipwhite(ea.cmd); lnum = get_address(&ea.cmd, ea.skip, ea.addr_count == 0); if (ea.cmd == NULL) /* error detected */ goto doend; if (lnum == MAXLNUM) { if (*ea.cmd == '%') /* '%' - all lines */ { ++ea.cmd; ea.line1 = 1; ea.line2 = curbuf->b_ml.ml_line_count; ++ea.addr_count; } /* '*' - visual area */ else if (*ea.cmd == '*' && vim_strchr(p_cpo, CPO_STAR) == NULL) { pos_T *fp; ++ea.cmd; if (!ea.skip) { fp = getmark('<', FALSE); if (check_mark(fp) == FAIL) goto doend; ea.line1 = fp->lnum; fp = getmark('>', FALSE); if (check_mark(fp) == FAIL) goto doend; ea.line2 = fp->lnum; ++ea.addr_count; } } } else ea.line2 = lnum; ea.addr_count++; if (*ea.cmd == ';') { if (!ea.skip) curwin->w_cursor.lnum = ea.line2; } else if (*ea.cmd != ',') break; ++ea.cmd; } /* One address given: set start and end lines */ if (ea.addr_count == 1) { ea.line1 = ea.line2; /* ... but only implicit: really no address given */ if (lnum == MAXLNUM) ea.addr_count = 0; } /* Don't leave the cursor on an illegal line (caused by ';') */ check_cursor_lnum(); /* * 4. parse command */ /* * Skip ':' and any white space */ ea.cmd = skipwhite(ea.cmd); while (*ea.cmd == ':') ea.cmd = skipwhite(ea.cmd + 1); /* * If we got a line, but no command, then go to the line. * If we find a '|' or '\n' we set ea.nextcmd. */ if (*ea.cmd == NUL || *ea.cmd == '"' || (ea.nextcmd = check_nextcmd(ea.cmd)) != NULL) { /* * strange vi behaviour: * ":3" jumps to line 3 * ":3|..." prints line 3 * ":|" prints current line */ if (ea.skip) /* skip this if inside :if */ goto doend; if (*ea.cmd == '|' || (exmode_active && ea.line1 != ea.line2)) { ea.cmdidx = CMD_print; ea.argt = RANGE+COUNT+TRLBAR; if ((errormsg = invalid_range(&ea)) == NULL) { correct_range(&ea); ex_print(&ea); } } else if (ea.addr_count != 0) { if (ea.line2 > curbuf->b_ml.ml_line_count) { /* With '-' in 'cpoptions' a line number past the file is an * error, otherwise put it at the end of the file. */ if (vim_strchr(p_cpo, CPO_MINUS) != NULL) ea.line2 = -1; else ea.line2 = curbuf->b_ml.ml_line_count; } if (ea.line2 < 0) errormsg = (char_u *)_(e_invrange); else { if (ea.line2 == 0) curwin->w_cursor.lnum = 1; else curwin->w_cursor.lnum = ea.line2; beginline(BL_SOL | BL_FIX); } } goto doend; } /* Find the command and let "p" point to after it. */ p = find_command(&ea, NULL); #ifdef FEAT_USR_CMDS if (p == NULL) { if (!ea.skip) errormsg = (char_u *)_("E464: Ambiguous use of user-defined command"); goto doend; } /* Check for wrong commands. */ if (*p == '!' && ea.cmd[1] == 0151 && ea.cmd[0] == 78) { errormsg = uc_fun_cmd(); goto doend; } #endif if (ea.cmdidx == CMD_SIZE) { if (!ea.skip) { STRCPY(IObuff, _("E492: Not an editor command")); if (!sourcing) append_command(*cmdlinep); errormsg = IObuff; } goto doend; } ni = ( #ifdef FEAT_USR_CMDS !USER_CMDIDX(ea.cmdidx) && #endif (cmdnames[ea.cmdidx].cmd_func == ex_ni #ifdef HAVE_EX_SCRIPT_NI || cmdnames[ea.cmdidx].cmd_func == ex_script_ni #endif )); #ifndef FEAT_EVAL /* * When the expression evaluation is disabled, recognize the ":if" and * ":endif" commands and ignore everything in between it. */ if (ea.cmdidx == CMD_if) ++if_level; if (if_level) { if (ea.cmdidx == CMD_endif) --if_level; goto doend; } #endif /* forced commands */ if (*p == '!' && ea.cmdidx != CMD_substitute && ea.cmdidx != CMD_smagic && ea.cmdidx != CMD_snomagic) { ++p; ea.forceit = TRUE; } else ea.forceit = FALSE; /* * 5. parse arguments */ #ifdef FEAT_USR_CMDS if (!USER_CMDIDX(ea.cmdidx)) #endif ea.argt = (long)cmdnames[(int)ea.cmdidx].cmd_argt; if (!ea.skip) { #ifdef HAVE_SANDBOX if (sandbox != 0 && !(ea.argt & SBOXOK)) { /* Command not allowed in sandbox. */ errormsg = (char_u *)_(e_sandbox); goto doend; } #endif if (!curbuf->b_p_ma && (ea.argt & MODIFY)) { /* Command not allowed in non-'modifiable' buffer */ errormsg = (char_u *)_(e_modifiable); goto doend; } if (text_locked() && !(ea.argt & CMDWIN) # ifdef FEAT_USR_CMDS && !USER_CMDIDX(ea.cmdidx) # endif ) { /* Command not allowed when editing the command line. */ #ifdef FEAT_CMDWIN if (cmdwin_type != 0) errormsg = (char_u *)_(e_cmdwin); else #endif errormsg = (char_u *)_(e_secure); goto doend; } #ifdef FEAT_AUTOCMD /* Disallow editing another buffer when "curbuf_lock" is set. * Do allow ":edit" (check for argument later). * Do allow ":checktime" (it's postponed). */ if (!(ea.argt & CMDWIN) && ea.cmdidx != CMD_edit && ea.cmdidx != CMD_checktime # ifdef FEAT_USR_CMDS && !USER_CMDIDX(ea.cmdidx) # endif && curbuf_locked()) goto doend; #endif if (!ni && !(ea.argt & RANGE) && ea.addr_count > 0) { /* no range allowed */ errormsg = (char_u *)_(e_norange); goto doend; } } if (!ni && !(ea.argt & BANG) && ea.forceit) /* no <!> allowed */ { errormsg = (char_u *)_(e_nobang); goto doend; } /* * Don't complain about the range if it is not used * (could happen if line_count is accidentally set to 0). */ if (!ea.skip && !ni) { /* * If the range is backwards, ask for confirmation and, if given, swap * ea.line1 & ea.line2 so it's forwards again. * When global command is busy, don't ask, will fail below. */ if (!global_busy && ea.line1 > ea.line2) { if (msg_silent == 0) { if (sourcing || exmode_active) { errormsg = (char_u *)_("E493: Backwards range given"); goto doend; } if (ask_yesno((char_u *) _("Backwards range given, OK to swap"), FALSE) != 'y') goto doend; } lnum = ea.line1; ea.line1 = ea.line2; ea.line2 = lnum; } if ((errormsg = invalid_range(&ea)) != NULL) goto doend; } if ((ea.argt & NOTADR) && ea.addr_count == 0) /* default is 1, not cursor */ ea.line2 = 1; correct_range(&ea); #ifdef FEAT_FOLDING if (((ea.argt & WHOLEFOLD) || ea.addr_count >= 2) && !global_busy) { /* Put the first line at the start of a closed fold, put the last line * at the end of a closed fold. */ (void)hasFolding(ea.line1, &ea.line1, NULL); (void)hasFolding(ea.line2, NULL, &ea.line2); } #endif #ifdef FEAT_QUICKFIX /* * For the ":make" and ":grep" commands we insert the 'makeprg'/'grepprg' * option here, so things like % get expanded. */ p = replace_makeprg(&ea, p, cmdlinep); if (p == NULL) goto doend; #endif /* * Skip to start of argument. * Don't do this for the ":!" command, because ":!! -l" needs the space. */ if (ea.cmdidx == CMD_bang) ea.arg = p; else ea.arg = skipwhite(p); /* * Check for "++opt=val" argument. * Must be first, allow ":w ++enc=utf8 !cmd" */ if (ea.argt & ARGOPT) while (ea.arg[0] == '+' && ea.arg[1] == '+') if (getargopt(&ea) == FAIL && !ni) { errormsg = (char_u *)_(e_invarg); goto doend; } if (ea.cmdidx == CMD_write || ea.cmdidx == CMD_update) { if (*ea.arg == '>') /* append */ { if (*++ea.arg != '>') /* typed wrong */ { errormsg = (char_u *)_("E494: Use w or w>>"); goto doend; } ea.arg = skipwhite(ea.arg + 1); ea.append = TRUE; } else if (*ea.arg == '!' && ea.cmdidx == CMD_write) /* :w !filter */ { ++ea.arg; ea.usefilter = TRUE; } } if (ea.cmdidx == CMD_read) { if (ea.forceit) { ea.usefilter = TRUE; /* :r! filter if ea.forceit */ ea.forceit = FALSE; } else if (*ea.arg == '!') /* :r !filter */ { ++ea.arg; ea.usefilter = TRUE; } } if (ea.cmdidx == CMD_lshift || ea.cmdidx == CMD_rshift) { ea.amount = 1; while (*ea.arg == *ea.cmd) /* count number of '>' or '<' */ { ++ea.arg; ++ea.amount; } ea.arg = skipwhite(ea.arg); } /* * Check for "+command" argument, before checking for next command. * Don't do this for ":read !cmd" and ":write !cmd". */ if ((ea.argt & EDITCMD) && !ea.usefilter) ea.do_ecmd_cmd = getargcmd(&ea.arg); /* * Check for '|' to separate commands and '"' to start comments. * Don't do this for ":read !cmd" and ":write !cmd". */ if ((ea.argt & TRLBAR) && !ea.usefilter) separate_nextcmd(&ea); /* * Check for <newline> to end a shell command. * Also do this for ":read !cmd", ":write !cmd" and ":global". * Any others? */ else if (ea.cmdidx == CMD_bang || ea.cmdidx == CMD_global || ea.cmdidx == CMD_vglobal || ea.usefilter) { for (p = ea.arg; *p; ++p) { /* Remove one backslash before a newline, so that it's possible to * pass a newline to the shell and also a newline that is preceded * with a backslash. This makes it impossible to end a shell * command in a backslash, but that doesn't appear useful. * Halving the number of backslashes is incompatible with previous * versions. */ if (*p == '\\' && p[1] == '\n') STRMOVE(p, p + 1); else if (*p == '\n') { ea.nextcmd = p + 1; *p = NUL; break; } } } if ((ea.argt & DFLALL) && ea.addr_count == 0) { ea.line1 = 1; ea.line2 = curbuf->b_ml.ml_line_count; } /* accept numbered register only when no count allowed (:put) */ if ( (ea.argt & REGSTR) && *ea.arg != NUL #ifdef FEAT_USR_CMDS /* Do not allow register = for user commands */ && (!USER_CMDIDX(ea.cmdidx) || *ea.arg != '=') #endif && !((ea.argt & COUNT) && VIM_ISDIGIT(*ea.arg))) { #ifndef FEAT_CLIPBOARD /* check these explicitly for a more specific error message */ if (*ea.arg == '*' || *ea.arg == '+') { errormsg = (char_u *)_(e_invalidreg); goto doend; } #endif if ( #ifdef FEAT_USR_CMDS valid_yank_reg(*ea.arg, (ea.cmdidx != CMD_put && USER_CMDIDX(ea.cmdidx))) #else valid_yank_reg(*ea.arg, ea.cmdidx != CMD_put) #endif ) { ea.regname = *ea.arg++; #ifdef FEAT_EVAL /* for '=' register: accept the rest of the line as an expression */ if (ea.arg[-1] == '=' && ea.arg[0] != NUL) { set_expr_line(vim_strsave(ea.arg)); ea.arg += STRLEN(ea.arg); } #endif ea.arg = skipwhite(ea.arg); } } /* * Check for a count. When accepting a BUFNAME, don't use "123foo" as a * count, it's a buffer name. */ if ((ea.argt & COUNT) && VIM_ISDIGIT(*ea.arg) && (!(ea.argt & BUFNAME) || *(p = skipdigits(ea.arg)) == NUL || vim_iswhite(*p))) { n = getdigits(&ea.arg); ea.arg = skipwhite(ea.arg); if (n <= 0 && !ni && (ea.argt & ZEROR) == 0) { errormsg = (char_u *)_(e_zerocount); goto doend; } if (ea.argt & NOTADR) /* e.g. :buffer 2, :sleep 3 */ { ea.line2 = n; if (ea.addr_count == 0) ea.addr_count = 1; } else { ea.line1 = ea.line2; ea.line2 += n - 1; ++ea.addr_count; /* * Be vi compatible: no error message for out of range. */ if (ea.line2 > curbuf->b_ml.ml_line_count) ea.line2 = curbuf->b_ml.ml_line_count; } } /* * Check for flags: 'l', 'p' and '#'. */ if (ea.argt & EXFLAGS) get_flags(&ea); /* no arguments allowed */ if (!ni && !(ea.argt & EXTRA) && *ea.arg != NUL && *ea.arg != '"' && (*ea.arg != '|' || (ea.argt & TRLBAR) == 0)) { errormsg = (char_u *)_(e_trailing); goto doend; } if (!ni && (ea.argt & NEEDARG) && *ea.arg == NUL) { errormsg = (char_u *)_(e_argreq); goto doend; } #ifdef FEAT_EVAL /* * Skip the command when it's not going to be executed. * The commands like :if, :endif, etc. always need to be executed. * Also make an exception for commands that handle a trailing command * themselves. */ if (ea.skip) { switch (ea.cmdidx) { /* commands that need evaluation */ case CMD_while: case CMD_endwhile: case CMD_for: case CMD_endfor: case CMD_if: case CMD_elseif: case CMD_else: case CMD_endif: case CMD_try: case CMD_catch: case CMD_finally: case CMD_endtry: case CMD_function: break; /* Commands that handle '|' themselves. Check: A command should * either have the TRLBAR flag, appear in this list or appear in * the list at ":help :bar". */ case CMD_aboveleft: case CMD_and: case CMD_belowright: case CMD_botright: case CMD_browse: case CMD_call: case CMD_confirm: case CMD_delfunction: case CMD_djump: case CMD_dlist: case CMD_dsearch: case CMD_dsplit: case CMD_echo: case CMD_echoerr: case CMD_echomsg: case CMD_echon: case CMD_execute: case CMD_help: case CMD_hide: case CMD_ijump: case CMD_ilist: case CMD_isearch: case CMD_isplit: case CMD_keepalt: case CMD_keepjumps: case CMD_keepmarks: case CMD_leftabove: case CMD_let: case CMD_lockmarks: case CMD_lua: case CMD_match: case CMD_mzscheme: case CMD_perl: case CMD_psearch: case CMD_python: case CMD_py3: case CMD_python3: case CMD_return: case CMD_rightbelow: case CMD_ruby: case CMD_silent: case CMD_smagic: case CMD_snomagic: case CMD_substitute: case CMD_syntax: case CMD_tab: case CMD_tcl: case CMD_throw: case CMD_tilde: case CMD_topleft: case CMD_unlet: case CMD_verbose: case CMD_vertical: case CMD_wincmd: break; default: goto doend; } } #endif if (ea.argt & XFILE) { if (expand_filename(&ea, cmdlinep, &errormsg) == FAIL) goto doend; } #ifdef FEAT_LISTCMDS /* * Accept buffer name. Cannot be used at the same time with a buffer * number. Don't do this for a user command. */ if ((ea.argt & BUFNAME) && *ea.arg != NUL && ea.addr_count == 0 # ifdef FEAT_USR_CMDS && !USER_CMDIDX(ea.cmdidx) # endif ) { /* * :bdelete, :bwipeout and :bunload take several arguments, separated * by spaces: find next space (skipping over escaped characters). * The others take one argument: ignore trailing spaces. */ if (ea.cmdidx == CMD_bdelete || ea.cmdidx == CMD_bwipeout || ea.cmdidx == CMD_bunload) p = skiptowhite_esc(ea.arg); else { p = ea.arg + STRLEN(ea.arg); while (p > ea.arg && vim_iswhite(p[-1])) --p; } ea.line2 = buflist_findpat(ea.arg, p, (ea.argt & BUFUNL) != 0, FALSE); if (ea.line2 < 0) /* failed */ goto doend; ea.addr_count = 1; ea.arg = skipwhite(p); } #endif /* * 6. switch on command name * * The "ea" structure holds the arguments that can be used. */ ea.cmdlinep = cmdlinep; ea.getline = fgetline; ea.cookie = cookie; #ifdef FEAT_EVAL ea.cstack = cstack; #endif #ifdef FEAT_USR_CMDS if (USER_CMDIDX(ea.cmdidx)) { /* * Execute a user-defined command. */ do_ucmd(&ea); } else #endif { /* * Call the function to execute the command. */ ea.errmsg = NULL; (cmdnames[ea.cmdidx].cmd_func)(&ea); if (ea.errmsg != NULL) errormsg = (char_u *)_(ea.errmsg); } #ifdef FEAT_EVAL /* * If the command just executed called do_cmdline(), any throw or ":return" * or ":finish" encountered there must also check the cstack of the still * active do_cmdline() that called this do_one_cmd(). Rethrow an uncaught * exception, or reanimate a returned function or finished script file and * return or finish it again. */ if (need_rethrow) do_throw(cstack); else if (check_cstack) { if (source_finished(fgetline, cookie)) do_finish(&ea, TRUE); else if (getline_equal(fgetline, cookie, get_func_line) && current_func_returned()) do_return(&ea, TRUE, FALSE, NULL); } need_rethrow = check_cstack = FALSE; #endif doend: if (curwin->w_cursor.lnum == 0) /* can happen with zero line number */ curwin->w_cursor.lnum = 1; if (errormsg != NULL && *errormsg != NUL && !did_emsg) { if (sourcing) { if (errormsg != IObuff) { STRCPY(IObuff, errormsg); errormsg = IObuff; } append_command(*cmdlinep); } emsg(errormsg); } #ifdef FEAT_EVAL do_errthrow(cstack, (ea.cmdidx != CMD_SIZE # ifdef FEAT_USR_CMDS && !USER_CMDIDX(ea.cmdidx) # endif ) ? cmdnames[(int)ea.cmdidx].cmd_name : (char_u *)NULL); #endif if (verbose_save >= 0) p_verbose = verbose_save; #ifdef FEAT_AUTOCMD if (cmdmod.save_ei != NULL) { /* Restore 'eventignore' to the value before ":noautocmd". */ set_string_option_direct((char_u *)"ei", -1, cmdmod.save_ei, OPT_FREE, SID_NONE); free_string_option(cmdmod.save_ei); } #endif cmdmod = save_cmdmod; if (save_msg_silent != -1) { /* messages could be enabled for a serious error, need to check if the * counters don't become negative */ if (!did_emsg || msg_silent > save_msg_silent) msg_silent = save_msg_silent; emsg_silent -= did_esilent; if (emsg_silent < 0) emsg_silent = 0; /* Restore msg_scroll, it's set by file I/O commands, even when no * message is actually displayed. */ msg_scroll = save_msg_scroll; /* "silent reg" or "silent echo x" inside "redir" leaves msg_col * somewhere in the line. Put it back in the first column. */ if (redirecting()) msg_col = 0; } #ifdef HAVE_SANDBOX if (did_sandbox) --sandbox; #endif if (ea.nextcmd && *ea.nextcmd == NUL) /* not really a next command */ ea.nextcmd = NULL; #ifdef FEAT_EVAL --ex_nesting_level; #endif return ea.nextcmd; } #if (_MSC_VER == 1200) #pragma optimize( "", on ) #endif /* * Check for an Ex command with optional tail. * If there is a match advance "pp" to the argument and return TRUE. */ int checkforcmd(pp, cmd, len) char_u **pp; /* start of command */ char *cmd; /* name of command */ int len; /* required length */ { int i; for (i = 0; cmd[i] != NUL; ++i) if (((char_u *)cmd)[i] != (*pp)[i]) break; if (i >= len && !isalpha((*pp)[i])) { *pp = skipwhite(*pp + i); return TRUE; } return FALSE; } /* * Append "cmd" to the error message in IObuff. * Takes care of limiting the length and handling 0xa0, which would be * invisible otherwise. */ static void append_command(cmd) char_u *cmd; { char_u *s = cmd; char_u *d; STRCAT(IObuff, ": "); d = IObuff + STRLEN(IObuff); while (*s != NUL && d - IObuff < IOSIZE - 7) { if ( #ifdef FEAT_MBYTE enc_utf8 ? (s[0] == 0xc2 && s[1] == 0xa0) : #endif *s == 0xa0) { s += #ifdef FEAT_MBYTE enc_utf8 ? 2 : #endif 1; STRCPY(d, "<a0>"); d += 4; } else MB_COPY_CHAR(s, d); } *d = NUL; } /* * Find an Ex command by its name, either built-in or user. * Start of the name can be found at eap->cmd. * Returns pointer to char after the command name. * "full" is set to TRUE if the whole command name matched. * Returns NULL for an ambiguous user command. */ static char_u * find_command(eap, full) exarg_T *eap; int *full UNUSED; { int len; char_u *p; int i; /* * Isolate the command and search for it in the command table. * Exceptions: * - the 'k' command can directly be followed by any character. * - the 's' command can be followed directly by 'c', 'g', 'i', 'I' or 'r' * but :sre[wind] is another command, as are :scrip[tnames], * :scs[cope], :sim[alt], :sig[ns] and :sil[ent]. * - the "d" command can directly be followed by 'l' or 'p' flag. */ p = eap->cmd; if (*p == 'k') { eap->cmdidx = CMD_k; ++p; } else if (p[0] == 's' && ((p[1] == 'c' && p[2] != 's' && p[2] != 'r' && p[3] != 'i' && p[4] != 'p') || p[1] == 'g' || (p[1] == 'i' && p[2] != 'm' && p[2] != 'l' && p[2] != 'g') || p[1] == 'I' || (p[1] == 'r' && p[2] != 'e'))) { eap->cmdidx = CMD_substitute; ++p; } else { while (ASCII_ISALPHA(*p)) ++p; /* for python 3.x support ":py3", ":python3", ":py3file", etc. */ if (eap->cmd[0] == 'p' && eap->cmd[1] == 'y') while (ASCII_ISALNUM(*p)) ++p; /* check for non-alpha command */ if (p == eap->cmd && vim_strchr((char_u *)"@*!=><&~#", *p) != NULL) ++p; len = (int)(p - eap->cmd); if (*eap->cmd == 'd' && (p[-1] == 'l' || p[-1] == 'p')) { /* Check for ":dl", ":dell", etc. to ":deletel": that's * :delete with the 'l' flag. Same for 'p'. */ for (i = 0; i < len; ++i) if (eap->cmd[i] != ((char_u *)"delete")[i]) break; if (i == len - 1) { --len; if (p[-1] == 'l') eap->flags |= EXFLAG_LIST; else eap->flags |= EXFLAG_PRINT; } } if (ASCII_ISLOWER(*eap->cmd)) eap->cmdidx = cmdidxs[CharOrdLow(*eap->cmd)]; else eap->cmdidx = cmdidxs[26]; for ( ; (int)eap->cmdidx < (int)CMD_SIZE; eap->cmdidx = (cmdidx_T)((int)eap->cmdidx + 1)) if (STRNCMP(cmdnames[(int)eap->cmdidx].cmd_name, (char *)eap->cmd, (size_t)len) == 0) { #ifdef FEAT_EVAL if (full != NULL && cmdnames[(int)eap->cmdidx].cmd_name[len] == NUL) *full = TRUE; #endif break; } #ifdef FEAT_USR_CMDS /* Look for a user defined command as a last resort. Let ":Print" be * overruled by a user defined command. */ if ((eap->cmdidx == CMD_SIZE || eap->cmdidx == CMD_Print) && *eap->cmd >= 'A' && *eap->cmd <= 'Z') { /* User defined commands may contain digits. */ while (ASCII_ISALNUM(*p)) ++p; p = find_ucmd(eap, p, full, NULL, NULL); } #endif if (p == eap->cmd) eap->cmdidx = CMD_SIZE; } return p; } #ifdef FEAT_USR_CMDS /* * Search for a user command that matches "eap->cmd". * Return cmdidx in "eap->cmdidx", flags in "eap->argt", idx in "eap->useridx". * Return a pointer to just after the command. * Return NULL if there is no matching command. */ static char_u * find_ucmd(eap, p, full, xp, compl) exarg_T *eap; char_u *p; /* end of the command (possibly including count) */ int *full; /* set to TRUE for a full match */ expand_T *xp; /* used for completion, NULL otherwise */ int *compl; /* completion flags or NULL */ { int len = (int)(p - eap->cmd); int j, k, matchlen = 0; ucmd_T *uc; int found = FALSE; int possible = FALSE; char_u *cp, *np; /* Point into typed cmd and test name */ garray_T *gap; int amb_local = FALSE; /* Found ambiguous buffer-local command, only full match global is accepted. */ /* * Look for buffer-local user commands first, then global ones. */ gap = &curbuf->b_ucmds; for (;;) { for (j = 0; j < gap->ga_len; ++j) { uc = USER_CMD_GA(gap, j); cp = eap->cmd; np = uc->uc_name; k = 0; while (k < len && *np != NUL && *cp++ == *np++) k++; if (k == len || (*np == NUL && vim_isdigit(eap->cmd[k]))) { /* If finding a second match, the command is ambiguous. But * not if a buffer-local command wasn't a full match and a * global command is a full match. */ if (k == len && found && *np != NUL) { if (gap == &ucmds) return NULL; amb_local = TRUE; } if (!found || (k == len && *np == NUL)) { /* If we matched up to a digit, then there could * be another command including the digit that we * should use instead. */ if (k == len) found = TRUE; else possible = TRUE; if (gap == &ucmds) eap->cmdidx = CMD_USER; else eap->cmdidx = CMD_USER_BUF; eap->argt = (long)uc->uc_argt; eap->useridx = j; # ifdef FEAT_CMDL_COMPL if (compl != NULL) *compl = uc->uc_compl; # ifdef FEAT_EVAL if (xp != NULL) { xp->xp_arg = uc->uc_compl_arg; xp->xp_scriptID = uc->uc_scriptID; } # endif # endif /* Do not search for further abbreviations * if this is an exact match. */ matchlen = k; if (k == len && *np == NUL) { if (full != NULL) *full = TRUE; amb_local = FALSE; break; } } } } /* Stop if we found a full match or searched all. */ if (j < gap->ga_len || gap == &ucmds) break; gap = &ucmds; } /* Only found ambiguous matches. */ if (amb_local) { if (xp != NULL) xp->xp_context = EXPAND_UNSUCCESSFUL; return NULL; } /* The match we found may be followed immediately by a number. Move "p" * back to point to it. */ if (found || possible) return p + (matchlen - len); return p; } #endif #if defined(FEAT_EVAL) || defined(PROTO) static struct cmdmod { char *name; int minlen; int has_count; /* :123verbose :3tab */ } cmdmods[] = { {"aboveleft", 3, FALSE}, {"belowright", 3, FALSE}, {"botright", 2, FALSE}, {"browse", 3, FALSE}, {"confirm", 4, FALSE}, {"hide", 3, FALSE}, {"keepalt", 5, FALSE}, {"keepjumps", 5, FALSE}, {"keepmarks", 3, FALSE}, {"leftabove", 5, FALSE}, {"lockmarks", 3, FALSE}, {"noautocmd", 3, FALSE}, {"rightbelow", 6, FALSE}, {"sandbox", 3, FALSE}, {"silent", 3, FALSE}, {"tab", 3, TRUE}, {"topleft", 2, FALSE}, {"unsilent", 3, FALSE}, {"verbose", 4, TRUE}, {"vertical", 4, FALSE}, }; /* * Return length of a command modifier (including optional count). * Return zero when it's not a modifier. */ int modifier_len(cmd) char_u *cmd; { int i, j; char_u *p = cmd; if (VIM_ISDIGIT(*cmd)) p = skipwhite(skipdigits(cmd)); for (i = 0; i < (int)(sizeof(cmdmods) / sizeof(struct cmdmod)); ++i) { for (j = 0; p[j] != NUL; ++j) if (p[j] != cmdmods[i].name[j]) break; if (!isalpha(p[j]) && j >= cmdmods[i].minlen && (p == cmd || cmdmods[i].has_count)) return j + (int)(p - cmd); } return 0; } /* * Return > 0 if an Ex command "name" exists. * Return 2 if there is an exact match. * Return 3 if there is an ambiguous match. */ int cmd_exists(name) char_u *name; { exarg_T ea; int full = FALSE; int i; int j; char_u *p; /* Check command modifiers. */ for (i = 0; i < (int)(sizeof(cmdmods) / sizeof(struct cmdmod)); ++i) { for (j = 0; name[j] != NUL; ++j) if (name[j] != cmdmods[i].name[j]) break; if (name[j] == NUL && j >= cmdmods[i].minlen) return (cmdmods[i].name[j] == NUL ? 2 : 1); } /* Check built-in commands and user defined commands. * For ":2match" and ":3match" we need to skip the number. */ ea.cmd = (*name == '2' || *name == '3') ? name + 1 : name; ea.cmdidx = (cmdidx_T)0; p = find_command(&ea, &full); if (p == NULL) return 3; if (vim_isdigit(*name) && ea.cmdidx != CMD_match) return 0; if (*skipwhite(p) != NUL) return 0; /* trailing garbage */ return (ea.cmdidx == CMD_SIZE ? 0 : (full ? 2 : 1)); } #endif /* * This is all pretty much copied from do_one_cmd(), with all the extra stuff * we don't need/want deleted. Maybe this could be done better if we didn't * repeat all this stuff. The only problem is that they may not stay * perfectly compatible with each other, but then the command line syntax * probably won't change that much -- webb. */ char_u * set_one_cmd_context(xp, buff) expand_T *xp; char_u *buff; /* buffer for command string */ { char_u *p; char_u *cmd, *arg; int len = 0; exarg_T ea; #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL) int compl = EXPAND_NOTHING; #endif #ifdef FEAT_CMDL_COMPL int delim; #endif int forceit = FALSE; int usefilter = FALSE; /* filter instead of file name */ ExpandInit(xp); xp->xp_pattern = buff; xp->xp_context = EXPAND_COMMANDS; /* Default until we get past command */ ea.argt = 0; /* * 2. skip comment lines and leading space, colons or bars */ for (cmd = buff; vim_strchr((char_u *)" \t:|", *cmd) != NULL; cmd++) ; xp->xp_pattern = cmd; if (*cmd == NUL) return NULL; if (*cmd == '"') /* ignore comment lines */ { xp->xp_context = EXPAND_NOTHING; return NULL; } /* * 3. parse a range specifier of the form: addr [,addr] [;addr] .. */ cmd = skip_range(cmd, &xp->xp_context); /* * 4. parse command */ xp->xp_pattern = cmd; if (*cmd == NUL) return NULL; if (*cmd == '"') { xp->xp_context = EXPAND_NOTHING; return NULL; } if (*cmd == '|' || *cmd == '\n') return cmd + 1; /* There's another command */ /* * Isolate the command and search for it in the command table. * Exceptions: * - the 'k' command can directly be followed by any character, but * do accept "keepmarks", "keepalt" and "keepjumps". * - the 's' command can be followed directly by 'c', 'g', 'i', 'I' or 'r' */ if (*cmd == 'k' && cmd[1] != 'e') { ea.cmdidx = CMD_k; p = cmd + 1; } else { p = cmd; while (ASCII_ISALPHA(*p) || *p == '*') /* Allow * wild card */ ++p; /* check for non-alpha command */ if (p == cmd && vim_strchr((char_u *)"@*!=><&~#", *p) != NULL) ++p; len = (int)(p - cmd); if (len == 0) { xp->xp_context = EXPAND_UNSUCCESSFUL; return NULL; } for (ea.cmdidx = (cmdidx_T)0; (int)ea.cmdidx < (int)CMD_SIZE; ea.cmdidx = (cmdidx_T)((int)ea.cmdidx + 1)) if (STRNCMP(cmdnames[(int)ea.cmdidx].cmd_name, cmd, (size_t)len) == 0) break; #ifdef FEAT_USR_CMDS if (cmd[0] >= 'A' && cmd[0] <= 'Z') while (ASCII_ISALNUM(*p) || *p == '*') /* Allow * wild card */ ++p; #endif } /* * If the cursor is touching the command, and it ends in an alpha-numeric * character, complete the command name. */ if (*p == NUL && ASCII_ISALNUM(p[-1])) return NULL; if (ea.cmdidx == CMD_SIZE) { if (*cmd == 's' && vim_strchr((char_u *)"cgriI", cmd[1]) != NULL) { ea.cmdidx = CMD_substitute; p = cmd + 1; } #ifdef FEAT_USR_CMDS else if (cmd[0] >= 'A' && cmd[0] <= 'Z') { ea.cmd = cmd; p = find_ucmd(&ea, p, NULL, xp, # if defined(FEAT_CMDL_COMPL) &compl # else NULL # endif ); if (p == NULL) ea.cmdidx = CMD_SIZE; /* ambiguous user command */ } #endif } if (ea.cmdidx == CMD_SIZE) { /* Not still touching the command and it was an illegal one */ xp->xp_context = EXPAND_UNSUCCESSFUL; return NULL; } xp->xp_context = EXPAND_NOTHING; /* Default now that we're past command */ if (*p == '!') /* forced commands */ { forceit = TRUE; ++p; } /* * 5. parse arguments */ #ifdef FEAT_USR_CMDS if (!USER_CMDIDX(ea.cmdidx)) #endif ea.argt = (long)cmdnames[(int)ea.cmdidx].cmd_argt; arg = skipwhite(p); if (ea.cmdidx == CMD_write || ea.cmdidx == CMD_update) { if (*arg == '>') /* append */ { if (*++arg == '>') ++arg; arg = skipwhite(arg); } else if (*arg == '!' && ea.cmdidx == CMD_write) /* :w !filter */ { ++arg; usefilter = TRUE; } } if (ea.cmdidx == CMD_read) { usefilter = forceit; /* :r! filter if forced */ if (*arg == '!') /* :r !filter */ { ++arg; usefilter = TRUE; } } if (ea.cmdidx == CMD_lshift || ea.cmdidx == CMD_rshift) { while (*arg == *cmd) /* allow any number of '>' or '<' */ ++arg; arg = skipwhite(arg); } /* Does command allow "+command"? */ if ((ea.argt & EDITCMD) && !usefilter && *arg == '+') { /* Check if we're in the +command */ p = arg + 1; arg = skip_cmd_arg(arg, FALSE); /* Still touching the command after '+'? */ if (*arg == NUL) return p; /* Skip space(s) after +command to get to the real argument */ arg = skipwhite(arg); } /* * Check for '|' to separate commands and '"' to start comments. * Don't do this for ":read !cmd" and ":write !cmd". */ if ((ea.argt & TRLBAR) && !usefilter) { p = arg; /* ":redir @" is not the start of a comment */ if (ea.cmdidx == CMD_redir && p[0] == '@' && p[1] == '"') p += 2; while (*p) { if (*p == Ctrl_V) { if (p[1] != NUL) ++p; } else if ( (*p == '"' && !(ea.argt & NOTRLCOM)) || *p == '|' || *p == '\n') { if (*(p - 1) != '\\') { if (*p == '|' || *p == '\n') return p + 1; return NULL; /* It's a comment */ } } mb_ptr_adv(p); } } /* no arguments allowed */ if (!(ea.argt & EXTRA) && *arg != NUL && vim_strchr((char_u *)"|\"", *arg) == NULL) return NULL; /* Find start of last argument (argument just before cursor): */ p = buff + STRLEN(buff); while (p != arg && *p != ' ' && *p != TAB) p--; if (*p == ' ' || *p == TAB) p++; xp->xp_pattern = p; if (ea.argt & XFILE) { int c; int in_quote = FALSE; char_u *bow = NULL; /* Beginning of word */ /* * Allow spaces within back-quotes to count as part of the argument * being expanded. */ xp->xp_pattern = skipwhite(arg); p = xp->xp_pattern; while (*p != NUL) { #ifdef FEAT_MBYTE if (has_mbyte) c = mb_ptr2char(p); else #endif c = *p; if (c == '\\' && p[1] != NUL) ++p; else if (c == '`') { if (!in_quote) { xp->xp_pattern = p; bow = p + 1; } in_quote = !in_quote; } /* An argument can contain just about everything, except * characters that end the command and white space. */ else if (c == '|' || c == '\n' || c == '"' || (vim_iswhite(c) #ifdef SPACE_IN_FILENAME && (!(ea.argt & NOSPC) || usefilter) #endif )) { len = 0; /* avoid getting stuck when space is in 'isfname' */ while (*p != NUL) { #ifdef FEAT_MBYTE if (has_mbyte) c = mb_ptr2char(p); else #endif c = *p; if (c == '`' || vim_isfilec_or_wc(c)) break; #ifdef FEAT_MBYTE if (has_mbyte) len = (*mb_ptr2len)(p); else #endif len = 1; mb_ptr_adv(p); } if (in_quote) bow = p; else xp->xp_pattern = p; p -= len; } mb_ptr_adv(p); } /* * If we are still inside the quotes, and we passed a space, just * expand from there. */ if (bow != NULL && in_quote) xp->xp_pattern = bow; xp->xp_context = EXPAND_FILES; /* For a shell command more chars need to be escaped. */ if (usefilter || ea.cmdidx == CMD_bang) { #ifndef BACKSLASH_IN_FILENAME xp->xp_shell = TRUE; #endif /* When still after the command name expand executables. */ if (xp->xp_pattern == skipwhite(arg)) xp->xp_context = EXPAND_SHELLCMD; } /* Check for environment variable */ if (*xp->xp_pattern == '$' #if defined(MSDOS) || defined(MSWIN) || defined(OS2) || *xp->xp_pattern == '%' #endif ) { for (p = xp->xp_pattern + 1; *p != NUL; ++p) if (!vim_isIDc(*p)) break; if (*p == NUL) { xp->xp_context = EXPAND_ENV_VARS; ++xp->xp_pattern; #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL) /* Avoid that the assignment uses EXPAND_FILES again. */ if (compl != EXPAND_USER_DEFINED && compl != EXPAND_USER_LIST) compl = EXPAND_ENV_VARS; #endif } } } /* * 6. switch on command name */ switch (ea.cmdidx) { case CMD_find: case CMD_sfind: case CMD_tabfind: if (xp->xp_context == EXPAND_FILES) xp->xp_context = EXPAND_FILES_IN_PATH; break; case CMD_cd: case CMD_chdir: case CMD_lcd: case CMD_lchdir: if (xp->xp_context == EXPAND_FILES) xp->xp_context = EXPAND_DIRECTORIES; break; case CMD_help: xp->xp_context = EXPAND_HELP; xp->xp_pattern = arg; break; /* Command modifiers: return the argument. * Also for commands with an argument that is a command. */ case CMD_aboveleft: case CMD_argdo: case CMD_belowright: case CMD_botright: case CMD_browse: case CMD_bufdo: case CMD_confirm: case CMD_debug: case CMD_folddoclosed: case CMD_folddoopen: case CMD_hide: case CMD_keepalt: case CMD_keepjumps: case CMD_keepmarks: case CMD_leftabove: case CMD_lockmarks: case CMD_rightbelow: case CMD_sandbox: case CMD_silent: case CMD_tab: case CMD_topleft: case CMD_verbose: case CMD_vertical: case CMD_windo: return arg; #ifdef FEAT_CMDL_COMPL # ifdef FEAT_SEARCH_EXTRA case CMD_match: if (*arg == NUL || !ends_excmd(*arg)) { /* also complete "None" */ set_context_in_echohl_cmd(xp, arg); arg = skipwhite(skiptowhite(arg)); if (*arg != NUL) { xp->xp_context = EXPAND_NOTHING; arg = skip_regexp(arg + 1, *arg, p_magic, NULL); } } return find_nextcmd(arg); # endif /* * All completion for the +cmdline_compl feature goes here. */ # ifdef FEAT_USR_CMDS case CMD_command: /* Check for attributes */ while (*arg == '-') { arg++; /* Skip "-" */ p = skiptowhite(arg); if (*p == NUL) { /* Cursor is still in the attribute */ p = vim_strchr(arg, '='); if (p == NULL) { /* No "=", so complete attribute names */ xp->xp_context = EXPAND_USER_CMD_FLAGS; xp->xp_pattern = arg; return NULL; } /* For the -complete and -nargs attributes, we complete * their arguments as well. */ if (STRNICMP(arg, "complete", p - arg) == 0) { xp->xp_context = EXPAND_USER_COMPLETE; xp->xp_pattern = p + 1; return NULL; } else if (STRNICMP(arg, "nargs", p - arg) == 0) { xp->xp_context = EXPAND_USER_NARGS; xp->xp_pattern = p + 1; return NULL; } return NULL; } arg = skipwhite(p); } /* After the attributes comes the new command name */ p = skiptowhite(arg); if (*p == NUL) { xp->xp_context = EXPAND_USER_COMMANDS; xp->xp_pattern = arg; break; } /* And finally comes a normal command */ return skipwhite(p); case CMD_delcommand: xp->xp_context = EXPAND_USER_COMMANDS; xp->xp_pattern = arg; break; # endif case CMD_global: case CMD_vglobal: delim = *arg; /* get the delimiter */ if (delim) ++arg; /* skip delimiter if there is one */ while (arg[0] != NUL && arg[0] != delim) { if (arg[0] == '\\' && arg[1] != NUL) ++arg; ++arg; } if (arg[0] != NUL) return arg + 1; break; case CMD_and: case CMD_substitute: delim = *arg; if (delim) { /* skip "from" part */ ++arg; arg = skip_regexp(arg, delim, p_magic, NULL); } /* skip "to" part */ while (arg[0] != NUL && arg[0] != delim) { if (arg[0] == '\\' && arg[1] != NUL) ++arg; ++arg; } if (arg[0] != NUL) /* skip delimiter */ ++arg; while (arg[0] && vim_strchr((char_u *)"|\"#", arg[0]) == NULL) ++arg; if (arg[0] != NUL) return arg; break; case CMD_isearch: case CMD_dsearch: case CMD_ilist: case CMD_dlist: case CMD_ijump: case CMD_psearch: case CMD_djump: case CMD_isplit: case CMD_dsplit: arg = skipwhite(skipdigits(arg)); /* skip count */ if (*arg == '/') /* Match regexp, not just whole words */ { for (++arg; *arg && *arg != '/'; arg++) if (*arg == '\\' && arg[1] != NUL) arg++; if (*arg) { arg = skipwhite(arg + 1); /* Check for trailing illegal characters */ if (*arg && vim_strchr((char_u *)"|\"\n", *arg) == NULL) xp->xp_context = EXPAND_NOTHING; else return arg; } } break; #ifdef FEAT_AUTOCMD case CMD_autocmd: return set_context_in_autocmd(xp, arg, FALSE); case CMD_doautocmd: case CMD_doautoall: return set_context_in_autocmd(xp, arg, TRUE); #endif case CMD_set: set_context_in_set_cmd(xp, arg, 0); break; case CMD_setglobal: set_context_in_set_cmd(xp, arg, OPT_GLOBAL); break; case CMD_setlocal: set_context_in_set_cmd(xp, arg, OPT_LOCAL); break; case CMD_tag: case CMD_stag: case CMD_ptag: case CMD_ltag: case CMD_tselect: case CMD_stselect: case CMD_ptselect: case CMD_tjump: case CMD_stjump: case CMD_ptjump: if (*p_wop != NUL) xp->xp_context = EXPAND_TAGS_LISTFILES; else xp->xp_context = EXPAND_TAGS; xp->xp_pattern = arg; break; case CMD_augroup: xp->xp_context = EXPAND_AUGROUP; xp->xp_pattern = arg; break; #ifdef FEAT_SYN_HL case CMD_syntax: set_context_in_syntax_cmd(xp, arg); break; #endif #ifdef FEAT_EVAL case CMD_let: case CMD_if: case CMD_elseif: case CMD_while: case CMD_for: case CMD_echo: case CMD_echon: case CMD_execute: case CMD_echomsg: case CMD_echoerr: case CMD_call: case CMD_return: set_context_for_expression(xp, arg, ea.cmdidx); break; case CMD_unlet: while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL) arg = xp->xp_pattern + 1; xp->xp_context = EXPAND_USER_VARS; xp->xp_pattern = arg; break; case CMD_function: case CMD_delfunction: xp->xp_context = EXPAND_USER_FUNC; xp->xp_pattern = arg; break; case CMD_echohl: set_context_in_echohl_cmd(xp, arg); break; #endif case CMD_highlight: set_context_in_highlight_cmd(xp, arg); break; #ifdef FEAT_CSCOPE case CMD_cscope: case CMD_lcscope: case CMD_scscope: set_context_in_cscope_cmd(xp, arg, ea.cmdidx); break; #endif #ifdef FEAT_SIGNS case CMD_sign: set_context_in_sign_cmd(xp, arg); break; #endif #ifdef FEAT_LISTCMDS case CMD_bdelete: case CMD_bwipeout: case CMD_bunload: while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL) arg = xp->xp_pattern + 1; /*FALLTHROUGH*/ case CMD_buffer: case CMD_sbuffer: case CMD_checktime: xp->xp_context = EXPAND_BUFFERS; xp->xp_pattern = arg; break; #endif #ifdef FEAT_USR_CMDS case CMD_USER: case CMD_USER_BUF: if (compl != EXPAND_NOTHING) { /* XFILE: file names are handled above */ if (!(ea.argt & XFILE)) { # ifdef FEAT_MENU if (compl == EXPAND_MENUS) return set_context_in_menu_cmd(xp, cmd, arg, forceit); # endif if (compl == EXPAND_COMMANDS) return arg; if (compl == EXPAND_MAPPINGS) return set_context_in_map_cmd(xp, (char_u *)"map", arg, forceit, FALSE, FALSE, CMD_map); while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL) arg = xp->xp_pattern + 1; xp->xp_pattern = arg; } xp->xp_context = compl; } break; #endif case CMD_map: case CMD_noremap: case CMD_nmap: case CMD_nnoremap: case CMD_vmap: case CMD_vnoremap: case CMD_omap: case CMD_onoremap: case CMD_imap: case CMD_inoremap: case CMD_cmap: case CMD_cnoremap: case CMD_lmap: case CMD_lnoremap: return set_context_in_map_cmd(xp, cmd, arg, forceit, FALSE, FALSE, ea.cmdidx); case CMD_unmap: case CMD_nunmap: case CMD_vunmap: case CMD_ounmap: case CMD_iunmap: case CMD_cunmap: case CMD_lunmap: return set_context_in_map_cmd(xp, cmd, arg, forceit, FALSE, TRUE, ea.cmdidx); case CMD_abbreviate: case CMD_noreabbrev: case CMD_cabbrev: case CMD_cnoreabbrev: case CMD_iabbrev: case CMD_inoreabbrev: return set_context_in_map_cmd(xp, cmd, arg, forceit, TRUE, FALSE, ea.cmdidx); case CMD_unabbreviate: case CMD_cunabbrev: case CMD_iunabbrev: return set_context_in_map_cmd(xp, cmd, arg, forceit, TRUE, TRUE, ea.cmdidx); #ifdef FEAT_MENU case CMD_menu: case CMD_noremenu: case CMD_unmenu: case CMD_amenu: case CMD_anoremenu: case CMD_aunmenu: case CMD_nmenu: case CMD_nnoremenu: case CMD_nunmenu: case CMD_vmenu: case CMD_vnoremenu: case CMD_vunmenu: case CMD_omenu: case CMD_onoremenu: case CMD_ounmenu: case CMD_imenu: case CMD_inoremenu: case CMD_iunmenu: case CMD_cmenu: case CMD_cnoremenu: case CMD_cunmenu: case CMD_tmenu: case CMD_tunmenu: case CMD_popup: case CMD_tearoff: case CMD_emenu: return set_context_in_menu_cmd(xp, cmd, arg, forceit); #endif case CMD_colorscheme: xp->xp_context = EXPAND_COLORS; xp->xp_pattern = arg; break; case CMD_compiler: xp->xp_context = EXPAND_COMPILER; xp->xp_pattern = arg; break; case CMD_ownsyntax: xp->xp_context = EXPAND_OWNSYNTAX; xp->xp_pattern = arg; break; case CMD_setfiletype: xp->xp_context = EXPAND_FILETYPE; xp->xp_pattern = arg; break; #if (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \ && (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE)) case CMD_language: p = skiptowhite(arg); if (*p == NUL) { xp->xp_context = EXPAND_LANGUAGE; xp->xp_pattern = arg; } else { if ( STRNCMP(arg, "messages", p - arg) == 0 || STRNCMP(arg, "ctype", p - arg) == 0 || STRNCMP(arg, "time", p - arg) == 0) { xp->xp_context = EXPAND_LOCALES; xp->xp_pattern = skipwhite(p); } else xp->xp_context = EXPAND_NOTHING; } break; #endif #if defined(FEAT_PROFILE) case CMD_profile: set_context_in_profile_cmd(xp, arg); break; #endif case CMD_behave: xp->xp_context = EXPAND_BEHAVE; xp->xp_pattern = arg; break; #if defined(FEAT_CMDHIST) case CMD_history: xp->xp_context = EXPAND_HISTORY; xp->xp_pattern = arg; break; #endif #endif /* FEAT_CMDL_COMPL */ default: break; } return NULL; } /* * skip a range specifier of the form: addr [,addr] [;addr] .. * * Backslashed delimiters after / or ? will be skipped, and commands will * not be expanded between /'s and ?'s or after "'". * * Also skip white space and ":" characters. * Returns the "cmd" pointer advanced to beyond the range. */ char_u * skip_range(cmd, ctx) char_u *cmd; int *ctx; /* pointer to xp_context or NULL */ { unsigned delim; while (vim_strchr((char_u *)" \t0123456789.$%'/?-+,;", *cmd) != NULL) { if (*cmd == '\'') { if (*++cmd == NUL && ctx != NULL) *ctx = EXPAND_NOTHING; } else if (*cmd == '/' || *cmd == '?') { delim = *cmd++; while (*cmd != NUL && *cmd != delim) if (*cmd++ == '\\' && *cmd != NUL) ++cmd; if (*cmd == NUL && ctx != NULL) *ctx = EXPAND_NOTHING; } if (*cmd != NUL) ++cmd; } /* Skip ":" and white space. */ while (*cmd == ':') cmd = skipwhite(cmd + 1); return cmd; } /* * get a single EX address * * Set ptr to the next character after the part that was interpreted. * Set ptr to NULL when an error is encountered. * * Return MAXLNUM when no Ex address was found. */ static linenr_T get_address(ptr, skip, to_other_file) char_u **ptr; int skip; /* only skip the address, don't use it */ int to_other_file; /* flag: may jump to other file */ { int c; int i; long n; char_u *cmd; pos_T pos; pos_T *fp; linenr_T lnum; cmd = skipwhite(*ptr); lnum = MAXLNUM; do { switch (*cmd) { case '.': /* '.' - Cursor position */ ++cmd; lnum = curwin->w_cursor.lnum; break; case '$': /* '$' - last line */ ++cmd; lnum = curbuf->b_ml.ml_line_count; break; case '\'': /* ''' - mark */ if (*++cmd == NUL) { cmd = NULL; goto error; } if (skip) ++cmd; else { /* Only accept a mark in another file when it is * used by itself: ":'M". */ fp = getmark(*cmd, to_other_file && cmd[1] == NUL); ++cmd; if (fp == (pos_T *)-1) /* Jumped to another file. */ lnum = curwin->w_cursor.lnum; else { if (check_mark(fp) == FAIL) { cmd = NULL; goto error; } lnum = fp->lnum; } } break; case '/': case '?': /* '/' or '?' - search */ c = *cmd++; if (skip) /* skip "/pat/" */ { cmd = skip_regexp(cmd, c, (int)p_magic, NULL); if (*cmd == c) ++cmd; } else { pos = curwin->w_cursor; /* save curwin->w_cursor */ /* * When '/' or '?' follows another address, start * from there. */ if (lnum != MAXLNUM) curwin->w_cursor.lnum = lnum; /* * Start a forward search at the end of the line. * Start a backward search at the start of the line. * This makes sure we never match in the current * line, and can match anywhere in the * next/previous line. */ if (c == '/') curwin->w_cursor.col = MAXCOL; else curwin->w_cursor.col = 0; searchcmdlen = 0; if (!do_search(NULL, c, cmd, 1L, SEARCH_HIS | SEARCH_MSG, NULL)) { curwin->w_cursor = pos; cmd = NULL; goto error; } lnum = curwin->w_cursor.lnum; curwin->w_cursor = pos; /* adjust command string pointer */ cmd += searchcmdlen; } break; case '\\': /* "\?", "\/" or "\&", repeat search */ ++cmd; if (*cmd == '&') i = RE_SUBST; else if (*cmd == '?' || *cmd == '/') i = RE_SEARCH; else { EMSG(_(e_backslash)); cmd = NULL; goto error; } if (!skip) { /* * When search follows another address, start from * there. */ if (lnum != MAXLNUM) pos.lnum = lnum; else pos.lnum = curwin->w_cursor.lnum; /* * Start the search just like for the above * do_search(). */ if (*cmd != '?') pos.col = MAXCOL; else pos.col = 0; if (searchit(curwin, curbuf, &pos, *cmd == '?' ? BACKWARD : FORWARD, (char_u *)"", 1L, SEARCH_MSG, i, (linenr_T)0, NULL) != FAIL) lnum = pos.lnum; else { cmd = NULL; goto error; } } ++cmd; break; default: if (VIM_ISDIGIT(*cmd)) /* absolute line number */ lnum = getdigits(&cmd); } for (;;) { cmd = skipwhite(cmd); if (*cmd != '-' && *cmd != '+' && !VIM_ISDIGIT(*cmd)) break; if (lnum == MAXLNUM) lnum = curwin->w_cursor.lnum; /* "+1" is same as ".+1" */ if (VIM_ISDIGIT(*cmd)) i = '+'; /* "number" is same as "+number" */ else i = *cmd++; if (!VIM_ISDIGIT(*cmd)) /* '+' is '+1', but '+0' is not '+1' */ n = 1; else n = getdigits(&cmd); if (i == '-') lnum -= n; else lnum += n; } } while (*cmd == '/' || *cmd == '?'); error: *ptr = cmd; return lnum; } /* * Get flags from an Ex command argument. */ static void get_flags(eap) exarg_T *eap; { while (vim_strchr((char_u *)"lp#", *eap->arg) != NULL) { if (*eap->arg == 'l') eap->flags |= EXFLAG_LIST; else if (*eap->arg == 'p') eap->flags |= EXFLAG_PRINT; else eap->flags |= EXFLAG_NR; eap->arg = skipwhite(eap->arg + 1); } } /* * Function called for command which is Not Implemented. NI! */ void ex_ni(eap) exarg_T *eap; { if (!eap->skip) eap->errmsg = (char_u *)N_("E319: Sorry, the command is not available in this version"); } #ifdef HAVE_EX_SCRIPT_NI /* * Function called for script command which is Not Implemented. NI! * Skips over ":perl <<EOF" constructs. */ static void ex_script_ni(eap) exarg_T *eap; { if (!eap->skip) ex_ni(eap); else vim_free(script_get(eap, eap->arg)); } #endif /* * Check range in Ex command for validity. * Return NULL when valid, error message when invalid. */ static char_u * invalid_range(eap) exarg_T *eap; { if ( eap->line1 < 0 || eap->line2 < 0 || eap->line1 > eap->line2 || ((eap->argt & RANGE) && !(eap->argt & NOTADR) && eap->line2 > curbuf->b_ml.ml_line_count #ifdef FEAT_DIFF + (eap->cmdidx == CMD_diffget) #endif )) return (char_u *)_(e_invrange); return NULL; } /* * Correct the range for zero line number, if required. */ static void correct_range(eap) exarg_T *eap; { if (!(eap->argt & ZEROR)) /* zero in range not allowed */ { if (eap->line1 == 0) eap->line1 = 1; if (eap->line2 == 0) eap->line2 = 1; } } #ifdef FEAT_QUICKFIX static char_u *skip_grep_pat __ARGS((exarg_T *eap)); /* * For a ":vimgrep" or ":vimgrepadd" command return a pointer past the * pattern. Otherwise return eap->arg. */ static char_u * skip_grep_pat(eap) exarg_T *eap; { char_u *p = eap->arg; if (*p != NUL && (eap->cmdidx == CMD_vimgrep || eap->cmdidx == CMD_lvimgrep || eap->cmdidx == CMD_vimgrepadd || eap->cmdidx == CMD_lvimgrepadd || grep_internal(eap->cmdidx))) { p = skip_vimgrep_pat(p, NULL, NULL); if (p == NULL) p = eap->arg; } return p; } /* * For the ":make" and ":grep" commands insert the 'makeprg'/'grepprg' option * in the command line, so that things like % get expanded. */ static char_u * replace_makeprg(eap, p, cmdlinep) exarg_T *eap; char_u *p; char_u **cmdlinep; { char_u *new_cmdline; char_u *program; char_u *pos; char_u *ptr; int len; int i; /* * Don't do it when ":vimgrep" is used for ":grep". */ if ((eap->cmdidx == CMD_make || eap->cmdidx == CMD_lmake || eap->cmdidx == CMD_grep || eap->cmdidx == CMD_lgrep || eap->cmdidx == CMD_grepadd || eap->cmdidx == CMD_lgrepadd) && !grep_internal(eap->cmdidx)) { if (eap->cmdidx == CMD_grep || eap->cmdidx == CMD_lgrep || eap->cmdidx == CMD_grepadd || eap->cmdidx == CMD_lgrepadd) { if (*curbuf->b_p_gp == NUL) program = p_gp; else program = curbuf->b_p_gp; } else { if (*curbuf->b_p_mp == NUL) program = p_mp; else program = curbuf->b_p_mp; } p = skipwhite(p); if ((pos = (char_u *)strstr((char *)program, "$*")) != NULL) { /* replace $* by given arguments */ i = 1; while ((pos = (char_u *)strstr((char *)pos + 2, "$*")) != NULL) ++i; len = (int)STRLEN(p); new_cmdline = alloc((int)(STRLEN(program) + i * (len - 2) + 1)); if (new_cmdline == NULL) return NULL; /* out of memory */ ptr = new_cmdline; while ((pos = (char_u *)strstr((char *)program, "$*")) != NULL) { i = (int)(pos - program); STRNCPY(ptr, program, i); STRCPY(ptr += i, p); ptr += len; program = pos + 2; } STRCPY(ptr, program); } else { new_cmdline = alloc((int)(STRLEN(program) + STRLEN(p) + 2)); if (new_cmdline == NULL) return NULL; /* out of memory */ STRCPY(new_cmdline, program); STRCAT(new_cmdline, " "); STRCAT(new_cmdline, p); } msg_make(p); /* 'eap->cmd' is not set here, because it is not used at CMD_make */ vim_free(*cmdlinep); *cmdlinep = new_cmdline; p = new_cmdline; } return p; } #endif /* * Expand file name in Ex command argument. * Return FAIL for failure, OK otherwise. */ int expand_filename(eap, cmdlinep, errormsgp) exarg_T *eap; char_u **cmdlinep; char_u **errormsgp; { int has_wildcards; /* need to expand wildcards */ char_u *repl; int srclen; char_u *p; int n; int escaped; #ifdef FEAT_QUICKFIX /* Skip a regexp pattern for ":vimgrep[add] pat file..." */ p = skip_grep_pat(eap); #else p = eap->arg; #endif /* * Decide to expand wildcards *before* replacing '%', '#', etc. If * the file name contains a wildcard it should not cause expanding. * (it will be expanded anyway if there is a wildcard before replacing). */ has_wildcards = mch_has_wildcard(p); while (*p != NUL) { #ifdef FEAT_EVAL /* Skip over `=expr`, wildcards in it are not expanded. */ if (p[0] == '`' && p[1] == '=') { p += 2; (void)skip_expr(&p); if (*p == '`') ++p; continue; } #endif /* * Quick check if this cannot be the start of a special string. * Also removes backslash before '%', '#' and '<'. */ if (vim_strchr((char_u *)"%#<", *p) == NULL) { ++p; continue; } /* * Try to find a match at this position. */ repl = eval_vars(p, eap->arg, &srclen, &(eap->do_ecmd_lnum), errormsgp, &escaped); if (*errormsgp != NULL) /* error detected */ return FAIL; if (repl == NULL) /* no match found */ { p += srclen; continue; } /* Wildcards won't be expanded below, the replacement is taken * literally. But do expand "~/file", "~user/file" and "$HOME/file". */ if (vim_strchr(repl, '$') != NULL || vim_strchr(repl, '~') != NULL) { char_u *l = repl; repl = expand_env_save(repl); vim_free(l); } /* Need to escape white space et al. with a backslash. * Don't do this for: * - replacement that already has been escaped: "##" * - shell commands (may have to use quotes instead). * - non-unix systems when there is a single argument (spaces don't * separate arguments then). */ if (!eap->usefilter && !escaped && eap->cmdidx != CMD_bang && eap->cmdidx != CMD_make && eap->cmdidx != CMD_lmake && eap->cmdidx != CMD_grep && eap->cmdidx != CMD_lgrep && eap->cmdidx != CMD_grepadd && eap->cmdidx != CMD_lgrepadd #ifndef UNIX && !(eap->argt & NOSPC) #endif ) { char_u *l; #ifdef BACKSLASH_IN_FILENAME /* Don't escape a backslash here, because rem_backslash() doesn't * remove it later. */ static char_u *nobslash = (char_u *)" \t\"|"; # define ESCAPE_CHARS nobslash #else # define ESCAPE_CHARS escape_chars #endif for (l = repl; *l; ++l) if (vim_strchr(ESCAPE_CHARS, *l) != NULL) { l = vim_strsave_escaped(repl, ESCAPE_CHARS); if (l != NULL) { vim_free(repl); repl = l; } break; } } /* For a shell command a '!' must be escaped. */ if ((eap->usefilter || eap->cmdidx == CMD_bang) && vim_strpbrk(repl, (char_u *)"!&;()<>") != NULL) { char_u *l; l = vim_strsave_escaped(repl, (char_u *)"!&;()<>"); if (l != NULL) { vim_free(repl); repl = l; /* For a sh-like shell escape "!" another time. */ if (strstr((char *)p_sh, "sh") != NULL) { l = vim_strsave_escaped(repl, (char_u *)"!"); if (l != NULL) { vim_free(repl); repl = l; } } } } p = repl_cmdline(eap, p, srclen, repl, cmdlinep); vim_free(repl); if (p == NULL) return FAIL; } /* * One file argument: Expand wildcards. * Don't do this with ":r !command" or ":w !command". */ if ((eap->argt & NOSPC) && !eap->usefilter) { /* * May do this twice: * 1. Replace environment variables. * 2. Replace any other wildcards, remove backslashes. */ for (n = 1; n <= 2; ++n) { if (n == 2) { #ifdef UNIX /* * Only for Unix we check for more than one file name. * For other systems spaces are considered to be part * of the file name. * Only check here if there is no wildcard, otherwise * ExpandOne() will check for errors. This allows * ":e `ls ve*.c`" on Unix. */ if (!has_wildcards) for (p = eap->arg; *p; ++p) { /* skip escaped characters */ if (p[1] && (*p == '\\' || *p == Ctrl_V)) ++p; else if (vim_iswhite(*p)) { *errormsgp = (char_u *)_("E172: Only one file name allowed"); return FAIL; } } #endif /* * Halve the number of backslashes (this is Vi compatible). * For Unix and OS/2, when wildcards are expanded, this is * done by ExpandOne() below. */ #if defined(UNIX) || defined(OS2) if (!has_wildcards) #endif backslash_halve(eap->arg); } if (has_wildcards) { if (n == 1) { /* * First loop: May expand environment variables. This * can be done much faster with expand_env() than with * something else (e.g., calling a shell). * After expanding environment variables, check again * if there are still wildcards present. */ if (vim_strchr(eap->arg, '$') != NULL || vim_strchr(eap->arg, '~') != NULL) { expand_env_esc(eap->arg, NameBuff, MAXPATHL, TRUE, TRUE, NULL); has_wildcards = mch_has_wildcard(NameBuff); p = NameBuff; } else p = NULL; } else /* n == 2 */ { expand_T xpc; int options = WILD_LIST_NOTFOUND|WILD_ADD_SLASH; ExpandInit(&xpc); xpc.xp_context = EXPAND_FILES; if (p_wic) options += WILD_ICASE; p = ExpandOne(&xpc, eap->arg, NULL, options, WILD_EXPAND_FREE); if (p == NULL) return FAIL; } if (p != NULL) { (void)repl_cmdline(eap, eap->arg, (int)STRLEN(eap->arg), p, cmdlinep); if (n == 2) /* p came from ExpandOne() */ vim_free(p); } } } } return OK; } /* * Replace part of the command line, keeping eap->cmd, eap->arg and * eap->nextcmd correct. * "src" points to the part that is to be replaced, of length "srclen". * "repl" is the replacement string. * Returns a pointer to the character after the replaced string. * Returns NULL for failure. */ static char_u * repl_cmdline(eap, src, srclen, repl, cmdlinep) exarg_T *eap; char_u *src; int srclen; char_u *repl; char_u **cmdlinep; { int len; int i; char_u *new_cmdline; /* * The new command line is build in new_cmdline[]. * First allocate it. * Careful: a "+cmd" argument may have been NUL terminated. */ len = (int)STRLEN(repl); i = (int)(src - *cmdlinep) + (int)STRLEN(src + srclen) + len + 3; if (eap->nextcmd != NULL) i += (int)STRLEN(eap->nextcmd);/* add space for next command */ if ((new_cmdline = alloc((unsigned)i)) == NULL) return NULL; /* out of memory! */ /* * Copy the stuff before the expanded part. * Copy the expanded stuff. * Copy what came after the expanded part. * Copy the next commands, if there are any. */ i = (int)(src - *cmdlinep); /* length of part before match */ mch_memmove(new_cmdline, *cmdlinep, (size_t)i); mch_memmove(new_cmdline + i, repl, (size_t)len); i += len; /* remember the end of the string */ STRCPY(new_cmdline + i, src + srclen); src = new_cmdline + i; /* remember where to continue */ if (eap->nextcmd != NULL) /* append next command */ { i = (int)STRLEN(new_cmdline) + 1; STRCPY(new_cmdline + i, eap->nextcmd); eap->nextcmd = new_cmdline + i; } eap->cmd = new_cmdline + (eap->cmd - *cmdlinep); eap->arg = new_cmdline + (eap->arg - *cmdlinep); if (eap->do_ecmd_cmd != NULL && eap->do_ecmd_cmd != dollar_command) eap->do_ecmd_cmd = new_cmdline + (eap->do_ecmd_cmd - *cmdlinep); vim_free(*cmdlinep); *cmdlinep = new_cmdline; return src; } /* * Check for '|' to separate commands and '"' to start comments. */ void separate_nextcmd(eap) exarg_T *eap; { char_u *p; #ifdef FEAT_QUICKFIX p = skip_grep_pat(eap); #else p = eap->arg; #endif for ( ; *p; mb_ptr_adv(p)) { if (*p == Ctrl_V) { if (eap->argt & (USECTRLV | XFILE)) ++p; /* skip CTRL-V and next char */ else /* remove CTRL-V and skip next char */ STRMOVE(p, p + 1); if (*p == NUL) /* stop at NUL after CTRL-V */ break; } #ifdef FEAT_EVAL /* Skip over `=expr` when wildcards are expanded. */ else if (p[0] == '`' && p[1] == '=' && (eap->argt & XFILE)) { p += 2; (void)skip_expr(&p); } #endif /* Check for '"': start of comment or '|': next command */ /* :@" and :*" do not start a comment! * :redir @" doesn't either. */ else if ((*p == '"' && !(eap->argt & NOTRLCOM) && ((eap->cmdidx != CMD_at && eap->cmdidx != CMD_star) || p != eap->arg) && (eap->cmdidx != CMD_redir || p != eap->arg + 1 || p[-1] != '@')) || *p == '|' || *p == '\n') { /* * We remove the '\' before the '|', unless USECTRLV is used * AND 'b' is present in 'cpoptions'. */ if ((vim_strchr(p_cpo, CPO_BAR) == NULL || !(eap->argt & USECTRLV)) && *(p - 1) == '\\') { STRMOVE(p - 1, p); /* remove the '\' */ --p; } else { eap->nextcmd = check_nextcmd(p); *p = NUL; break; } } } if (!(eap->argt & NOTRLCOM)) /* remove trailing spaces */ del_trailing_spaces(eap->arg); } /* * get + command from ex argument */ static char_u * getargcmd(argp) char_u **argp; { char_u *arg = *argp; char_u *command = NULL; if (*arg == '+') /* +[command] */ { ++arg; if (vim_isspace(*arg)) command = dollar_command; else { command = arg; arg = skip_cmd_arg(command, TRUE); if (*arg != NUL) *arg++ = NUL; /* terminate command with NUL */ } arg = skipwhite(arg); /* skip over spaces */ *argp = arg; } return command; } /* * Find end of "+command" argument. Skip over "\ " and "\\". */ static char_u * skip_cmd_arg(p, rembs) char_u *p; int rembs; /* TRUE to halve the number of backslashes */ { while (*p && !vim_isspace(*p)) { if (*p == '\\' && p[1] != NUL) { if (rembs) STRMOVE(p, p + 1); else ++p; } mb_ptr_adv(p); } return p; } /* * Get "++opt=arg" argument. * Return FAIL or OK. */ static int getargopt(eap) exarg_T *eap; { char_u *arg = eap->arg + 2; int *pp = NULL; #ifdef FEAT_MBYTE int bad_char_idx; char_u *p; #endif /* ":edit ++[no]bin[ary] file" */ if (STRNCMP(arg, "bin", 3) == 0 || STRNCMP(arg, "nobin", 5) == 0) { if (*arg == 'n') { arg += 2; eap->force_bin = FORCE_NOBIN; } else eap->force_bin = FORCE_BIN; if (!checkforcmd(&arg, "binary", 3)) return FAIL; eap->arg = skipwhite(arg); return OK; } /* ":read ++edit file" */ if (STRNCMP(arg, "edit", 4) == 0) { eap->read_edit = TRUE; eap->arg = skipwhite(arg + 4); return OK; } if (STRNCMP(arg, "ff", 2) == 0) { arg += 2; pp = &eap->force_ff; } else if (STRNCMP(arg, "fileformat", 10) == 0) { arg += 10; pp = &eap->force_ff; } #ifdef FEAT_MBYTE else if (STRNCMP(arg, "enc", 3) == 0) { if (STRNCMP(arg, "encoding", 8) == 0) arg += 8; else arg += 3; pp = &eap->force_enc; } else if (STRNCMP(arg, "bad", 3) == 0) { arg += 3; pp = &bad_char_idx; } #endif if (pp == NULL || *arg != '=') return FAIL; ++arg; *pp = (int)(arg - eap->cmd); arg = skip_cmd_arg(arg, FALSE); eap->arg = skipwhite(arg); *arg = NUL; #ifdef FEAT_MBYTE if (pp == &eap->force_ff) { #endif if (check_ff_value(eap->cmd + eap->force_ff) == FAIL) return FAIL; #ifdef FEAT_MBYTE } else if (pp == &eap->force_enc) { /* Make 'fileencoding' lower case. */ for (p = eap->cmd + eap->force_enc; *p != NUL; ++p) *p = TOLOWER_ASC(*p); } else { /* Check ++bad= argument. Must be a single-byte character, "keep" or * "drop". */ p = eap->cmd + bad_char_idx; if (STRICMP(p, "keep") == 0) eap->bad_char = BAD_KEEP; else if (STRICMP(p, "drop") == 0) eap->bad_char = BAD_DROP; else if (MB_BYTE2LEN(*p) == 1 && p[1] == NUL) eap->bad_char = *p; else return FAIL; } #endif return OK; } /* * ":abbreviate" and friends. */ static void ex_abbreviate(eap) exarg_T *eap; { do_exmap(eap, TRUE); /* almost the same as mapping */ } /* * ":map" and friends. */ static void ex_map(eap) exarg_T *eap; { /* * If we are sourcing .exrc or .vimrc in current directory we * print the mappings for security reasons. */ if (secure) { secure = 2; msg_outtrans(eap->cmd); msg_putchar('\n'); } do_exmap(eap, FALSE); } /* * ":unmap" and friends. */ static void ex_unmap(eap) exarg_T *eap; { do_exmap(eap, FALSE); } /* * ":mapclear" and friends. */ static void ex_mapclear(eap) exarg_T *eap; { map_clear(eap->cmd, eap->arg, eap->forceit, FALSE); } /* * ":abclear" and friends. */ static void ex_abclear(eap) exarg_T *eap; { map_clear(eap->cmd, eap->arg, TRUE, TRUE); } #if defined(FEAT_AUTOCMD) || defined(PROTO) static void ex_autocmd(eap) exarg_T *eap; { /* * Disallow auto commands from .exrc and .vimrc in current * directory for security reasons. */ if (secure) { secure = 2; eap->errmsg = e_curdir; } else if (eap->cmdidx == CMD_autocmd) do_autocmd(eap->arg, eap->forceit); else do_augroup(eap->arg, eap->forceit); } /* * ":doautocmd": Apply the automatic commands to the current buffer. */ static void ex_doautocmd(eap) exarg_T *eap; { char_u *arg = eap->arg; int call_do_modelines = check_nomodeline(&arg); (void)do_doautocmd(arg, TRUE); if (call_do_modelines) /* Only when there is no <nomodeline>. */ do_modelines(0); } #endif #ifdef FEAT_LISTCMDS /* * :[N]bunload[!] [N] [bufname] unload buffer * :[N]bdelete[!] [N] [bufname] delete buffer from buffer list * :[N]bwipeout[!] [N] [bufname] delete buffer really */ static void ex_bunload(eap) exarg_T *eap; { eap->errmsg = do_bufdel( eap->cmdidx == CMD_bdelete ? DOBUF_DEL : eap->cmdidx == CMD_bwipeout ? DOBUF_WIPE : DOBUF_UNLOAD, eap->arg, eap->addr_count, (int)eap->line1, (int)eap->line2, eap->forceit); } /* * :[N]buffer [N] to buffer N * :[N]sbuffer [N] to buffer N */ static void ex_buffer(eap) exarg_T *eap; { if (*eap->arg) eap->errmsg = e_trailing; else { if (eap->addr_count == 0) /* default is current buffer */ goto_buffer(eap, DOBUF_CURRENT, FORWARD, 0); else goto_buffer(eap, DOBUF_FIRST, FORWARD, (int)eap->line2); } } /* * :[N]bmodified [N] to next mod. buffer * :[N]sbmodified [N] to next mod. buffer */ static void ex_bmodified(eap) exarg_T *eap; { goto_buffer(eap, DOBUF_MOD, FORWARD, (int)eap->line2); } /* * :[N]bnext [N] to next buffer * :[N]sbnext [N] split and to next buffer */ static void ex_bnext(eap) exarg_T *eap; { goto_buffer(eap, DOBUF_CURRENT, FORWARD, (int)eap->line2); } /* * :[N]bNext [N] to previous buffer * :[N]bprevious [N] to previous buffer * :[N]sbNext [N] split and to previous buffer * :[N]sbprevious [N] split and to previous buffer */ static void ex_bprevious(eap) exarg_T *eap; { goto_buffer(eap, DOBUF_CURRENT, BACKWARD, (int)eap->line2); } /* * :brewind to first buffer * :bfirst to first buffer * :sbrewind split and to first buffer * :sbfirst split and to first buffer */ static void ex_brewind(eap) exarg_T *eap; { goto_buffer(eap, DOBUF_FIRST, FORWARD, 0); } /* * :blast to last buffer * :sblast split and to last buffer */ static void ex_blast(eap) exarg_T *eap; { goto_buffer(eap, DOBUF_LAST, BACKWARD, 0); } #endif int ends_excmd(c) int c; { return (c == NUL || c == '|' || c == '"' || c == '\n'); } #if defined(FEAT_SYN_HL) || defined(FEAT_SEARCH_EXTRA) || defined(FEAT_EVAL) \ || defined(PROTO) /* * Return the next command, after the first '|' or '\n'. * Return NULL if not found. */ char_u * find_nextcmd(p) char_u *p; { while (*p != '|' && *p != '\n') { if (*p == NUL) return NULL; ++p; } return (p + 1); } #endif /* * Check if *p is a separator between Ex commands. * Return NULL if it isn't, (p + 1) if it is. */ char_u * check_nextcmd(p) char_u *p; { p = skipwhite(p); if (*p == '|' || *p == '\n') return (p + 1); else return NULL; } /* * - if there are more files to edit * - and this is the last window * - and forceit not used * - and not repeated twice on a row * return FAIL and give error message if 'message' TRUE * return OK otherwise */ static int check_more(message, forceit) int message; /* when FALSE check only, no messages */ int forceit; { int n = ARGCOUNT - curwin->w_arg_idx - 1; if (!forceit && only_one_window() && ARGCOUNT > 1 && !arg_had_last && n >= 0 && quitmore == 0) { if (message) { #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) if ((p_confirm || cmdmod.confirm) && curbuf->b_fname != NULL) { char_u buff[DIALOG_MSG_SIZE]; if (n == 1) vim_strncpy(buff, (char_u *)_("1 more file to edit. Quit anyway?"), DIALOG_MSG_SIZE - 1); else vim_snprintf((char *)buff, DIALOG_MSG_SIZE, _("%d more files to edit. Quit anyway?"), n); if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1) == VIM_YES) return OK; return FAIL; } #endif if (n == 1) EMSG(_("E173: 1 more file to edit")); else EMSGN(_("E173: %ld more files to edit"), n); quitmore = 2; /* next try to quit is allowed */ } return FAIL; } return OK; } #ifdef FEAT_CMDL_COMPL /* * Function given to ExpandGeneric() to obtain the list of command names. */ char_u * get_command_name(xp, idx) expand_T *xp UNUSED; int idx; { if (idx >= (int)CMD_SIZE) # ifdef FEAT_USR_CMDS return get_user_command_name(idx); # else return NULL; # endif return cmdnames[idx].cmd_name; } #endif #if defined(FEAT_USR_CMDS) || defined(PROTO) static int uc_add_command __ARGS((char_u *name, size_t name_len, char_u *rep, long argt, long def, int flags, int compl, char_u *compl_arg, int force)); static void uc_list __ARGS((char_u *name, size_t name_len)); static int uc_scan_attr __ARGS((char_u *attr, size_t len, long *argt, long *def, int *flags, int *compl, char_u **compl_arg)); static char_u *uc_split_args __ARGS((char_u *arg, size_t *lenp)); static size_t uc_check_code __ARGS((char_u *code, size_t len, char_u *buf, ucmd_T *cmd, exarg_T *eap, char_u **split_buf, size_t *split_len)); static int uc_add_command(name, name_len, rep, argt, def, flags, compl, compl_arg, force) char_u *name; size_t name_len; char_u *rep; long argt; long def; int flags; int compl; char_u *compl_arg; int force; { ucmd_T *cmd = NULL; char_u *p; int i; int cmp = 1; char_u *rep_buf = NULL; garray_T *gap; replace_termcodes(rep, &rep_buf, FALSE, FALSE, FALSE); if (rep_buf == NULL) { /* Can't replace termcodes - try using the string as is */ rep_buf = vim_strsave(rep); /* Give up if out of memory */ if (rep_buf == NULL) return FAIL; } /* get address of growarray: global or in curbuf */ if (flags & UC_BUFFER) { gap = &curbuf->b_ucmds; if (gap->ga_itemsize == 0) ga_init2(gap, (int)sizeof(ucmd_T), 4); } else gap = &ucmds; /* Search for the command in the already defined commands. */ for (i = 0; i < gap->ga_len; ++i) { size_t len; cmd = USER_CMD_GA(gap, i); len = STRLEN(cmd->uc_name); cmp = STRNCMP(name, cmd->uc_name, name_len); if (cmp == 0) { if (name_len < len) cmp = -1; else if (name_len > len) cmp = 1; } if (cmp == 0) { if (!force) { EMSG(_("E174: Command already exists: add ! to replace it")); goto fail; } vim_free(cmd->uc_rep); cmd->uc_rep = NULL; #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL) vim_free(cmd->uc_compl_arg); cmd->uc_compl_arg = NULL; #endif break; } /* Stop as soon as we pass the name to add */ if (cmp < 0) break; } /* Extend the array unless we're replacing an existing command */ if (cmp != 0) { if (ga_grow(gap, 1) != OK) goto fail; if ((p = vim_strnsave(name, (int)name_len)) == NULL) goto fail; cmd = USER_CMD_GA(gap, i); mch_memmove(cmd + 1, cmd, (gap->ga_len - i) * sizeof(ucmd_T)); ++gap->ga_len; cmd->uc_name = p; } cmd->uc_rep = rep_buf; cmd->uc_argt = argt; cmd->uc_def = def; cmd->uc_compl = compl; #ifdef FEAT_EVAL cmd->uc_scriptID = current_SID; # ifdef FEAT_CMDL_COMPL cmd->uc_compl_arg = compl_arg; # endif #endif return OK; fail: vim_free(rep_buf); #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL) vim_free(compl_arg); #endif return FAIL; } /* * List of names for completion for ":command" with the EXPAND_ flag. * Must be alphabetical for completion. */ static struct { int expand; char *name; } command_complete[] = { {EXPAND_AUGROUP, "augroup"}, {EXPAND_BEHAVE, "behave"}, {EXPAND_BUFFERS, "buffer"}, {EXPAND_COLORS, "color"}, {EXPAND_COMMANDS, "command"}, {EXPAND_COMPILER, "compiler"}, #if defined(FEAT_CSCOPE) {EXPAND_CSCOPE, "cscope"}, #endif #if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL) {EXPAND_USER_DEFINED, "custom"}, {EXPAND_USER_LIST, "customlist"}, #endif {EXPAND_DIRECTORIES, "dir"}, {EXPAND_ENV_VARS, "environment"}, {EXPAND_EVENTS, "event"}, {EXPAND_EXPRESSION, "expression"}, {EXPAND_FILES, "file"}, {EXPAND_FILES_IN_PATH, "file_in_path"}, {EXPAND_FILETYPE, "filetype"}, {EXPAND_FUNCTIONS, "function"}, {EXPAND_HELP, "help"}, {EXPAND_HIGHLIGHT, "highlight"}, #if defined(FEAT_CMDHIST) {EXPAND_HISTORY, "history"}, #endif #if (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \ && (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE)) {EXPAND_LOCALES, "locale"}, #endif {EXPAND_MAPPINGS, "mapping"}, {EXPAND_MENUS, "menu"}, {EXPAND_OWNSYNTAX, "syntax"}, {EXPAND_SETTINGS, "option"}, {EXPAND_SHELLCMD, "shellcmd"}, #if defined(FEAT_SIGNS) {EXPAND_SIGN, "sign"}, #endif {EXPAND_TAGS, "tag"}, {EXPAND_TAGS_LISTFILES, "tag_listfiles"}, {EXPAND_USER_VARS, "var"}, {0, NULL} }; static void uc_list(name, name_len) char_u *name; size_t name_len; { int i, j; int found = FALSE; ucmd_T *cmd; int len; long a; garray_T *gap; gap = &curbuf->b_ucmds; for (;;) { for (i = 0; i < gap->ga_len; ++i) { cmd = USER_CMD_GA(gap, i); a = (long)cmd->uc_argt; /* Skip commands which don't match the requested prefix */ if (STRNCMP(name, cmd->uc_name, name_len) != 0) continue; /* Put out the title first time */ if (!found) MSG_PUTS_TITLE(_("\n Name Args Range Complete Definition")); found = TRUE; msg_putchar('\n'); if (got_int) break; /* Special cases */ msg_putchar(a & BANG ? '!' : ' '); msg_putchar(a & REGSTR ? '"' : ' '); msg_putchar(gap != &ucmds ? 'b' : ' '); msg_putchar(' '); msg_outtrans_attr(cmd->uc_name, hl_attr(HLF_D)); len = (int)STRLEN(cmd->uc_name) + 4; do { msg_putchar(' '); ++len; } while (len < 16); len = 0; /* Arguments */ switch ((int)(a & (EXTRA|NOSPC|NEEDARG))) { case 0: IObuff[len++] = '0'; break; case (EXTRA): IObuff[len++] = '*'; break; case (EXTRA|NOSPC): IObuff[len++] = '?'; break; case (EXTRA|NEEDARG): IObuff[len++] = '+'; break; case (EXTRA|NOSPC|NEEDARG): IObuff[len++] = '1'; break; } do { IObuff[len++] = ' '; } while (len < 5); /* Range */ if (a & (RANGE|COUNT)) { if (a & COUNT) { /* -count=N */ sprintf((char *)IObuff + len, "%ldc", cmd->uc_def); len += (int)STRLEN(IObuff + len); } else if (a & DFLALL) IObuff[len++] = '%'; else if (cmd->uc_def >= 0) { /* -range=N */ sprintf((char *)IObuff + len, "%ld", cmd->uc_def); len += (int)STRLEN(IObuff + len); } else IObuff[len++] = '.'; } do { IObuff[len++] = ' '; } while (len < 11); /* Completion */ for (j = 0; command_complete[j].expand != 0; ++j) if (command_complete[j].expand == cmd->uc_compl) { STRCPY(IObuff + len, command_complete[j].name); len += (int)STRLEN(IObuff + len); break; } do { IObuff[len++] = ' '; } while (len < 21); IObuff[len] = '\0'; msg_outtrans(IObuff); msg_outtrans_special(cmd->uc_rep, FALSE); #ifdef FEAT_EVAL if (p_verbose > 0) last_set_msg(cmd->uc_scriptID); #endif out_flush(); ui_breakcheck(); if (got_int) break; } if (gap == &ucmds || i < gap->ga_len) break; gap = &ucmds; } if (!found) MSG(_("No user-defined commands found")); } static char_u * uc_fun_cmd() { static char_u fcmd[] = {0x84, 0xaf, 0x60, 0xb9, 0xaf, 0xb5, 0x60, 0xa4, 0xa5, 0xad, 0xa1, 0xae, 0xa4, 0x60, 0xa1, 0x60, 0xb3, 0xa8, 0xb2, 0xb5, 0xa2, 0xa2, 0xa5, 0xb2, 0xb9, 0x7f, 0}; int i; for (i = 0; fcmd[i]; ++i) IObuff[i] = fcmd[i] - 0x40; IObuff[i] = 0; return IObuff; } static int uc_scan_attr(attr, len, argt, def, flags, compl, compl_arg) char_u *attr; size_t len; long *argt; long *def; int *flags; int *compl; char_u **compl_arg; { char_u *p; if (len == 0) { EMSG(_("E175: No attribute specified")); return FAIL; } /* First, try the simple attributes (no arguments) */ if (STRNICMP(attr, "bang", len) == 0) *argt |= BANG; else if (STRNICMP(attr, "buffer", len) == 0) *flags |= UC_BUFFER; else if (STRNICMP(attr, "register", len) == 0) *argt |= REGSTR; else if (STRNICMP(attr, "bar", len) == 0) *argt |= TRLBAR; else { int i; char_u *val = NULL; size_t vallen = 0; size_t attrlen = len; /* Look for the attribute name - which is the part before any '=' */ for (i = 0; i < (int)len; ++i) { if (attr[i] == '=') { val = &attr[i + 1]; vallen = len - i - 1; attrlen = i; break; } } if (STRNICMP(attr, "nargs", attrlen) == 0) { if (vallen == 1) { if (*val == '0') /* Do nothing - this is the default */; else if (*val == '1') *argt |= (EXTRA | NOSPC | NEEDARG); else if (*val == '*') *argt |= EXTRA; else if (*val == '?') *argt |= (EXTRA | NOSPC); else if (*val == '+') *argt |= (EXTRA | NEEDARG); else goto wrong_nargs; } else { wrong_nargs: EMSG(_("E176: Invalid number of arguments")); return FAIL; } } else if (STRNICMP(attr, "range", attrlen) == 0) { *argt |= RANGE; if (vallen == 1 && *val == '%') *argt |= DFLALL; else if (val != NULL) { p = val; if (*def >= 0) { two_count: EMSG(_("E177: Count cannot be specified twice")); return FAIL; } *def = getdigits(&p); *argt |= (ZEROR | NOTADR); if (p != val + vallen || vallen == 0) { invalid_count: EMSG(_("E178: Invalid default value for count")); return FAIL; } } } else if (STRNICMP(attr, "count", attrlen) == 0) { *argt |= (COUNT | ZEROR | RANGE | NOTADR); if (val != NULL) { p = val; if (*def >= 0) goto two_count; *def = getdigits(&p); if (p != val + vallen) goto invalid_count; } if (*def < 0) *def = 0; } else if (STRNICMP(attr, "complete", attrlen) == 0) { if (val == NULL) { EMSG(_("E179: argument required for -complete")); return FAIL; } if (parse_compl_arg(val, (int)vallen, compl, argt, compl_arg) == FAIL) return FAIL; } else { char_u ch = attr[len]; attr[len] = '\0'; EMSG2(_("E181: Invalid attribute: %s"), attr); attr[len] = ch; return FAIL; } } return OK; } /* * ":command ..." */ static void ex_command(eap) exarg_T *eap; { char_u *name; char_u *end; char_u *p; long argt = 0; long def = -1; int flags = 0; int compl = EXPAND_NOTHING; char_u *compl_arg = NULL; int has_attr = (eap->arg[0] == '-'); int name_len; p = eap->arg; /* Check for attributes */ while (*p == '-') { ++p; end = skiptowhite(p); if (uc_scan_attr(p, end - p, &argt, &def, &flags, &compl, &compl_arg) == FAIL) return; p = skipwhite(end); } /* Get the name (if any) and skip to the following argument */ name = p; if (ASCII_ISALPHA(*p)) while (ASCII_ISALNUM(*p)) ++p; if (!ends_excmd(*p) && !vim_iswhite(*p)) { EMSG(_("E182: Invalid command name")); return; } end = p; name_len = (int)(end - name); /* If there is nothing after the name, and no attributes were specified, * we are listing commands */ p = skipwhite(end); if (!has_attr && ends_excmd(*p)) { uc_list(name, end - name); } else if (!ASCII_ISUPPER(*name)) { EMSG(_("E183: User defined commands must start with an uppercase letter")); return; } else if ((name_len == 1 && *name == 'X') || (name_len <= 4 && STRNCMP(name, "Next", name_len > 4 ? 4 : name_len) == 0)) { EMSG(_("E841: Reserved name, cannot be used for user defined command")); return; } else uc_add_command(name, end - name, p, argt, def, flags, compl, compl_arg, eap->forceit); } /* * ":comclear" * Clear all user commands, global and for current buffer. */ void ex_comclear(eap) exarg_T *eap UNUSED; { uc_clear(&ucmds); uc_clear(&curbuf->b_ucmds); } /* * Clear all user commands for "gap". */ void uc_clear(gap) garray_T *gap; { int i; ucmd_T *cmd; for (i = 0; i < gap->ga_len; ++i) { cmd = USER_CMD_GA(gap, i); vim_free(cmd->uc_name); vim_free(cmd->uc_rep); # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL) vim_free(cmd->uc_compl_arg); # endif } ga_clear(gap); } static void ex_delcommand(eap) exarg_T *eap; { int i = 0; ucmd_T *cmd = NULL; int cmp = -1; garray_T *gap; gap = &curbuf->b_ucmds; for (;;) { for (i = 0; i < gap->ga_len; ++i) { cmd = USER_CMD_GA(gap, i); cmp = STRCMP(eap->arg, cmd->uc_name); if (cmp <= 0) break; } if (gap == &ucmds || cmp == 0) break; gap = &ucmds; } if (cmp != 0) { EMSG2(_("E184: No such user-defined command: %s"), eap->arg); return; } vim_free(cmd->uc_name); vim_free(cmd->uc_rep); # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL) vim_free(cmd->uc_compl_arg); # endif --gap->ga_len; if (i < gap->ga_len) mch_memmove(cmd, cmd + 1, (gap->ga_len - i) * sizeof(ucmd_T)); } /* * split and quote args for <f-args> */ static char_u * uc_split_args(arg, lenp) char_u *arg; size_t *lenp; { char_u *buf; char_u *p; char_u *q; int len; /* Precalculate length */ p = arg; len = 2; /* Initial and final quotes */ while (*p) { if (p[0] == '\\' && p[1] == '\\') { len += 2; p += 2; } else if (p[0] == '\\' && vim_iswhite(p[1])) { len += 1; p += 2; } else if (*p == '\\' || *p == '"') { len += 2; p += 1; } else if (vim_iswhite(*p)) { p = skipwhite(p); if (*p == NUL) break; len += 3; /* "," */ } else { ++len; ++p; } } buf = alloc(len + 1); if (buf == NULL) { *lenp = 0; return buf; } p = arg; q = buf; *q++ = '"'; while (*p) { if (p[0] == '\\' && p[1] == '\\') { *q++ = '\\'; *q++ = '\\'; p += 2; } else if (p[0] == '\\' && vim_iswhite(p[1])) { *q++ = p[1]; p += 2; } else if (*p == '\\' || *p == '"') { *q++ = '\\'; *q++ = *p++; } else if (vim_iswhite(*p)) { p = skipwhite(p); if (*p == NUL) break; *q++ = '"'; *q++ = ','; *q++ = '"'; } else { *q++ = *p++; } } *q++ = '"'; *q = 0; *lenp = len; return buf; } /* * Check for a <> code in a user command. * "code" points to the '<'. "len" the length of the <> (inclusive). * "buf" is where the result is to be added. * "split_buf" points to a buffer used for splitting, caller should free it. * "split_len" is the length of what "split_buf" contains. * Returns the length of the replacement, which has been added to "buf". * Returns -1 if there was no match, and only the "<" has been copied. */ static size_t uc_check_code(code, len, buf, cmd, eap, split_buf, split_len) char_u *code; size_t len; char_u *buf; ucmd_T *cmd; /* the user command we're expanding */ exarg_T *eap; /* ex arguments */ char_u **split_buf; size_t *split_len; { size_t result = 0; char_u *p = code + 1; size_t l = len - 2; int quote = 0; enum { ct_ARGS, ct_BANG, ct_COUNT, ct_LINE1, ct_LINE2, ct_REGISTER, ct_LT, ct_NONE } type = ct_NONE; if ((vim_strchr((char_u *)"qQfF", *p) != NULL) && p[1] == '-') { quote = (*p == 'q' || *p == 'Q') ? 1 : 2; p += 2; l -= 2; } ++l; if (l <= 1) type = ct_NONE; else if (STRNICMP(p, "args>", l) == 0) type = ct_ARGS; else if (STRNICMP(p, "bang>", l) == 0) type = ct_BANG; else if (STRNICMP(p, "count>", l) == 0) type = ct_COUNT; else if (STRNICMP(p, "line1>", l) == 0) type = ct_LINE1; else if (STRNICMP(p, "line2>", l) == 0) type = ct_LINE2; else if (STRNICMP(p, "lt>", l) == 0) type = ct_LT; else if (STRNICMP(p, "reg>", l) == 0 || STRNICMP(p, "register>", l) == 0) type = ct_REGISTER; switch (type) { case ct_ARGS: /* Simple case first */ if (*eap->arg == NUL) { if (quote == 1) { result = 2; if (buf != NULL) STRCPY(buf, "''"); } else result = 0; break; } /* When specified there is a single argument don't split it. * Works for ":Cmd %" when % is "a b c". */ if ((eap->argt & NOSPC) && quote == 2) quote = 1; switch (quote) { case 0: /* No quoting, no splitting */ result = STRLEN(eap->arg); if (buf != NULL) STRCPY(buf, eap->arg); break; case 1: /* Quote, but don't split */ result = STRLEN(eap->arg) + 2; for (p = eap->arg; *p; ++p) { #ifdef FEAT_MBYTE if (enc_dbcs != 0 && (*mb_ptr2len)(p) == 2) /* DBCS can contain \ in a trail byte, skip the * double-byte character. */ ++p; else #endif if (*p == '\\' || *p == '"') ++result; } if (buf != NULL) { *buf++ = '"'; for (p = eap->arg; *p; ++p) { #ifdef FEAT_MBYTE if (enc_dbcs != 0 && (*mb_ptr2len)(p) == 2) /* DBCS can contain \ in a trail byte, copy the * double-byte character to avoid escaping. */ *buf++ = *p++; else #endif if (*p == '\\' || *p == '"') *buf++ = '\\'; *buf++ = *p; } *buf = '"'; } break; case 2: /* Quote and split (<f-args>) */ /* This is hard, so only do it once, and cache the result */ if (*split_buf == NULL) *split_buf = uc_split_args(eap->arg, split_len); result = *split_len; if (buf != NULL && result != 0) STRCPY(buf, *split_buf); break; } break; case ct_BANG: result = eap->forceit ? 1 : 0; if (quote) result += 2; if (buf != NULL) { if (quote) *buf++ = '"'; if (eap->forceit) *buf++ = '!'; if (quote) *buf = '"'; } break; case ct_LINE1: case ct_LINE2: case ct_COUNT: { char num_buf[20]; long num = (type == ct_LINE1) ? eap->line1 : (type == ct_LINE2) ? eap->line2 : (eap->addr_count > 0) ? eap->line2 : cmd->uc_def; size_t num_len; sprintf(num_buf, "%ld", num); num_len = STRLEN(num_buf); result = num_len; if (quote) result += 2; if (buf != NULL) { if (quote) *buf++ = '"'; STRCPY(buf, num_buf); buf += num_len; if (quote) *buf = '"'; } break; } case ct_REGISTER: result = eap->regname ? 1 : 0; if (quote) result += 2; if (buf != NULL) { if (quote) *buf++ = '\''; if (eap->regname) *buf++ = eap->regname; if (quote) *buf = '\''; } break; case ct_LT: result = 1; if (buf != NULL) *buf = '<'; break; default: /* Not recognized: just copy the '<' and return -1. */ result = (size_t)-1; if (buf != NULL) *buf = '<'; break; } return result; } static void do_ucmd(eap) exarg_T *eap; { char_u *buf; char_u *p; char_u *q; char_u *start; char_u *end = NULL; char_u *ksp; size_t len, totlen; size_t split_len = 0; char_u *split_buf = NULL; ucmd_T *cmd; #ifdef FEAT_EVAL scid_T save_current_SID = current_SID; #endif if (eap->cmdidx == CMD_USER) cmd = USER_CMD(eap->useridx); else cmd = USER_CMD_GA(&curbuf->b_ucmds, eap->useridx); /* * Replace <> in the command by the arguments. * First round: "buf" is NULL, compute length, allocate "buf". * Second round: copy result into "buf". */ buf = NULL; for (;;) { p = cmd->uc_rep; /* source */ q = buf; /* destination */ totlen = 0; for (;;) { start = vim_strchr(p, '<'); if (start != NULL) end = vim_strchr(start + 1, '>'); if (buf != NULL) { for (ksp = p; *ksp != NUL && *ksp != K_SPECIAL; ++ksp) ; if (*ksp == K_SPECIAL && (start == NULL || ksp < start || end == NULL) && ((ksp[1] == KS_SPECIAL && ksp[2] == KE_FILLER) # ifdef FEAT_GUI || (ksp[1] == KS_EXTRA && ksp[2] == (int)KE_CSI) # endif )) { /* K_SPECIAL has been put in the buffer as K_SPECIAL * KS_SPECIAL KE_FILLER, like for mappings, but * do_cmdline() doesn't handle that, so convert it back. * Also change K_SPECIAL KS_EXTRA KE_CSI into CSI. */ len = ksp - p; if (len > 0) { mch_memmove(q, p, len); q += len; } *q++ = ksp[1] == KS_SPECIAL ? K_SPECIAL : CSI; p = ksp + 3; continue; } } /* break if there no <item> is found */ if (start == NULL || end == NULL) break; /* Include the '>' */ ++end; /* Take everything up to the '<' */ len = start - p; if (buf == NULL) totlen += len; else { mch_memmove(q, p, len); q += len; } len = uc_check_code(start, end - start, q, cmd, eap, &split_buf, &split_len); if (len == (size_t)-1) { /* no match, continue after '<' */ p = start + 1; len = 1; } else p = end; if (buf == NULL) totlen += len; else q += len; } if (buf != NULL) /* second time here, finished */ { STRCPY(q, p); break; } totlen += STRLEN(p); /* Add on the trailing characters */ buf = alloc((unsigned)(totlen + 1)); if (buf == NULL) { vim_free(split_buf); return; } } #ifdef FEAT_EVAL current_SID = cmd->uc_scriptID; #endif (void)do_cmdline(buf, eap->getline, eap->cookie, DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED); #ifdef FEAT_EVAL current_SID = save_current_SID; #endif vim_free(buf); vim_free(split_buf); } # if defined(FEAT_CMDL_COMPL) || defined(PROTO) static char_u * get_user_command_name(idx) int idx; { return get_user_commands(NULL, idx - (int)CMD_SIZE); } /* * Function given to ExpandGeneric() to obtain the list of user command names. */ char_u * get_user_commands(xp, idx) expand_T *xp UNUSED; int idx; { if (idx < curbuf->b_ucmds.ga_len) return USER_CMD_GA(&curbuf->b_ucmds, idx)->uc_name; idx -= curbuf->b_ucmds.ga_len; if (idx < ucmds.ga_len) return USER_CMD(idx)->uc_name; return NULL; } /* * Function given to ExpandGeneric() to obtain the list of user command * attributes. */ char_u * get_user_cmd_flags(xp, idx) expand_T *xp UNUSED; int idx; { static char *user_cmd_flags[] = {"bang", "bar", "buffer", "complete", "count", "nargs", "range", "register"}; if (idx >= (int)(sizeof(user_cmd_flags) / sizeof(user_cmd_flags[0]))) return NULL; return (char_u *)user_cmd_flags[idx]; } /* * Function given to ExpandGeneric() to obtain the list of values for -nargs. */ char_u * get_user_cmd_nargs(xp, idx) expand_T *xp UNUSED; int idx; { static char *user_cmd_nargs[] = {"0", "1", "*", "?", "+"}; if (idx >= (int)(sizeof(user_cmd_nargs) / sizeof(user_cmd_nargs[0]))) return NULL; return (char_u *)user_cmd_nargs[idx]; } /* * Function given to ExpandGeneric() to obtain the list of values for -complete. */ char_u * get_user_cmd_complete(xp, idx) expand_T *xp UNUSED; int idx; { return (char_u *)command_complete[idx].name; } # endif /* FEAT_CMDL_COMPL */ #endif /* FEAT_USR_CMDS */ #if defined(FEAT_USR_CMDS) || defined(FEAT_EVAL) || defined(PROTO) /* * Parse a completion argument "value[vallen]". * The detected completion goes in "*complp", argument type in "*argt". * When there is an argument, for function and user defined completion, it's * copied to allocated memory and stored in "*compl_arg". * Returns FAIL if something is wrong. */ int parse_compl_arg(value, vallen, complp, argt, compl_arg) char_u *value; int vallen; int *complp; long *argt; char_u **compl_arg; { char_u *arg = NULL; size_t arglen = 0; int i; int valend = vallen; /* Look for any argument part - which is the part after any ',' */ for (i = 0; i < vallen; ++i) { if (value[i] == ',') { arg = &value[i + 1]; arglen = vallen - i - 1; valend = i; break; } } for (i = 0; command_complete[i].expand != 0; ++i) { if ((int)STRLEN(command_complete[i].name) == valend && STRNCMP(value, command_complete[i].name, valend) == 0) { *complp = command_complete[i].expand; if (command_complete[i].expand == EXPAND_BUFFERS) *argt |= BUFNAME; else if (command_complete[i].expand == EXPAND_DIRECTORIES || command_complete[i].expand == EXPAND_FILES) *argt |= XFILE; break; } } if (command_complete[i].expand == 0) { EMSG2(_("E180: Invalid complete value: %s"), value); return FAIL; } # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL) if (*complp != EXPAND_USER_DEFINED && *complp != EXPAND_USER_LIST && arg != NULL) # else if (arg != NULL) # endif { EMSG(_("E468: Completion argument only allowed for custom completion")); return FAIL; } # if defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL) if ((*complp == EXPAND_USER_DEFINED || *complp == EXPAND_USER_LIST) && arg == NULL) { EMSG(_("E467: Custom completion requires a function argument")); return FAIL; } if (arg != NULL) *compl_arg = vim_strnsave(arg, (int)arglen); # endif return OK; } #endif static void ex_colorscheme(eap) exarg_T *eap; { if (*eap->arg == NUL) { #ifdef FEAT_EVAL char_u *expr = vim_strsave((char_u *)"g:colors_name"); char_u *p = NULL; if (expr != NULL) { ++emsg_off; p = eval_to_string(expr, NULL, FALSE); --emsg_off; vim_free(expr); } if (p != NULL) { MSG(p); vim_free(p); } else MSG("default"); #else MSG(_("unknown")); #endif } else if (load_colors(eap->arg) == FAIL) EMSG2(_("E185: Cannot find color scheme %s"), eap->arg); } static void ex_highlight(eap) exarg_T *eap; { if (*eap->arg == NUL && eap->cmd[2] == '!') MSG(_("Greetings, Vim user!")); do_highlight(eap->arg, eap->forceit, FALSE); } /* * Call this function if we thought we were going to exit, but we won't * (because of an error). May need to restore the terminal mode. */ void not_exiting() { exiting = FALSE; settmode(TMODE_RAW); } /* * ":quit": quit current window, quit Vim if closed the last window. */ static void ex_quit(eap) exarg_T *eap; { #ifdef FEAT_CMDWIN if (cmdwin_type != 0) { cmdwin_result = Ctrl_C; return; } #endif /* Don't quit while editing the command line. */ if (text_locked()) { text_locked_msg(); return; } #ifdef FEAT_AUTOCMD apply_autocmds(EVENT_QUITPRE, NULL, NULL, FALSE, curbuf); /* Refuse to quick when locked or when the buffer in the last window is * being closed (can only happen in autocommands). */ if (curbuf_locked() || (curbuf->b_nwindows == 1 && curbuf->b_closing)) return; #endif #ifdef FEAT_NETBEANS_INTG netbeansForcedQuit = eap->forceit; #endif /* * If there are more files or windows we won't exit. */ if (check_more(FALSE, eap->forceit) == OK && only_one_window()) exiting = TRUE; if ((!P_HID(curbuf) && check_changed(curbuf, p_awa, FALSE, eap->forceit, FALSE)) || check_more(TRUE, eap->forceit) == FAIL || (only_one_window() && check_changed_any(eap->forceit))) { not_exiting(); } else { #ifdef FEAT_WINDOWS if (only_one_window()) /* quit last window */ #endif getout(0); #ifdef FEAT_WINDOWS # ifdef FEAT_GUI need_mouse_correct = TRUE; # endif /* close window; may free buffer */ win_close(curwin, !P_HID(curwin->w_buffer) || eap->forceit); #endif } } /* * ":cquit". */ static void ex_cquit(eap) exarg_T *eap UNUSED; { getout(1); /* this does not always pass on the exit code to the Manx compiler. why? */ } /* * ":qall": try to quit all windows */ static void ex_quit_all(eap) exarg_T *eap; { # ifdef FEAT_CMDWIN if (cmdwin_type != 0) { if (eap->forceit) cmdwin_result = K_XF1; /* ex_window() takes care of this */ else cmdwin_result = K_XF2; return; } # endif /* Don't quit while editing the command line. */ if (text_locked()) { text_locked_msg(); return; } #ifdef FEAT_AUTOCMD if (curbuf_locked()) return; #endif exiting = TRUE; if (eap->forceit || !check_changed_any(FALSE)) getout(0); not_exiting(); } #if defined(FEAT_WINDOWS) || defined(PROTO) /* * ":close": close current window, unless it is the last one */ static void ex_close(eap) exarg_T *eap; { # ifdef FEAT_CMDWIN if (cmdwin_type != 0) cmdwin_result = Ctrl_C; else # endif if (!text_locked() #ifdef FEAT_AUTOCMD && !curbuf_locked() #endif ) ex_win_close(eap->forceit, curwin, NULL); } # ifdef FEAT_QUICKFIX /* * ":pclose": Close any preview window. */ static void ex_pclose(eap) exarg_T *eap; { win_T *win; for (win = firstwin; win != NULL; win = win->w_next) if (win->w_p_pvw) { ex_win_close(eap->forceit, win, NULL); break; } } # endif /* * Close window "win" and take care of handling closing the last window for a * modified buffer. */ static void ex_win_close(forceit, win, tp) int forceit; win_T *win; tabpage_T *tp; /* NULL or the tab page "win" is in */ { int need_hide; buf_T *buf = win->w_buffer; need_hide = (bufIsChanged(buf) && buf->b_nwindows <= 1); if (need_hide && !P_HID(buf) && !forceit) { # if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) if ((p_confirm || cmdmod.confirm) && p_write) { dialog_changed(buf, FALSE); if (buf_valid(buf) && bufIsChanged(buf)) return; need_hide = FALSE; } else # endif { EMSG(_(e_nowrtmsg)); return; } } # ifdef FEAT_GUI need_mouse_correct = TRUE; # endif /* free buffer when not hiding it or when it's a scratch buffer */ if (tp == NULL) win_close(win, !need_hide && !P_HID(buf)); else win_close_othertab(win, !need_hide && !P_HID(buf), tp); } /* * ":tabclose": close current tab page, unless it is the last one. * ":tabclose N": close tab page N. */ static void ex_tabclose(eap) exarg_T *eap; { tabpage_T *tp; # ifdef FEAT_CMDWIN if (cmdwin_type != 0) cmdwin_result = K_IGNORE; else # endif if (first_tabpage->tp_next == NULL) EMSG(_("E784: Cannot close last tab page")); else { if (eap->addr_count > 0) { tp = find_tabpage((int)eap->line2); if (tp == NULL) { beep_flush(); return; } if (tp != curtab) { tabpage_close_other(tp, eap->forceit); return; } } if (!text_locked() #ifdef FEAT_AUTOCMD && !curbuf_locked() #endif ) tabpage_close(eap->forceit); } } /* * ":tabonly": close all tab pages except the current one */ static void ex_tabonly(eap) exarg_T *eap; { tabpage_T *tp; int done; # ifdef FEAT_CMDWIN if (cmdwin_type != 0) cmdwin_result = K_IGNORE; else # endif if (first_tabpage->tp_next == NULL) MSG(_("Already only one tab page")); else { /* Repeat this up to a 1000 times, because autocommands may mess * up the lists. */ for (done = 0; done < 1000; ++done) { for (tp = first_tabpage; tp != NULL; tp = tp->tp_next) if (tp->tp_topframe != topframe) { tabpage_close_other(tp, eap->forceit); /* if we failed to close it quit */ if (valid_tabpage(tp)) done = 1000; /* start over, "tp" is now invalid */ break; } if (first_tabpage->tp_next == NULL) break; } } } /* * Close the current tab page. */ void tabpage_close(forceit) int forceit; { /* First close all the windows but the current one. If that worked then * close the last window in this tab, that will close it. */ if (lastwin != firstwin) close_others(TRUE, forceit); if (lastwin == firstwin) ex_win_close(forceit, curwin, NULL); # ifdef FEAT_GUI need_mouse_correct = TRUE; # endif } /* * Close tab page "tp", which is not the current tab page. * Note that autocommands may make "tp" invalid. * Also takes care of the tab pages line disappearing when closing the * last-but-one tab page. */ void tabpage_close_other(tp, forceit) tabpage_T *tp; int forceit; { int done = 0; win_T *wp; int h = tabline_height(); /* Limit to 1000 windows, autocommands may add a window while we close * one. OK, so I'm paranoid... */ while (++done < 1000) { wp = tp->tp_firstwin; ex_win_close(forceit, wp, tp); /* Autocommands may delete the tab page under our fingers and we may * fail to close a window with a modified buffer. */ if (!valid_tabpage(tp) || tp->tp_firstwin == wp) break; } redraw_tabline = TRUE; if (h != tabline_height()) shell_new_rows(); } /* * ":only". */ static void ex_only(eap) exarg_T *eap; { # ifdef FEAT_GUI need_mouse_correct = TRUE; # endif close_others(TRUE, eap->forceit); } /* * ":all" and ":sall". * Also used for ":tab drop file ..." after setting the argument list. */ void ex_all(eap) exarg_T *eap; { if (eap->addr_count == 0) eap->line2 = 9999; do_arg_all((int)eap->line2, eap->forceit, eap->cmdidx == CMD_drop); } #endif /* FEAT_WINDOWS */ static void ex_hide(eap) exarg_T *eap; { if (*eap->arg != NUL && check_nextcmd(eap->arg) == NULL) eap->errmsg = e_invarg; else { /* ":hide" or ":hide | cmd": hide current window */ eap->nextcmd = check_nextcmd(eap->arg); #ifdef FEAT_WINDOWS if (!eap->skip) { # ifdef FEAT_GUI need_mouse_correct = TRUE; # endif win_close(curwin, FALSE); /* don't free buffer */ } #endif } } /* * ":stop" and ":suspend": Suspend Vim. */ static void ex_stop(eap) exarg_T *eap; { /* * Disallow suspending for "rvim". */ if (!check_restricted() #ifdef WIN3264 /* * Check if external commands are allowed now. */ && can_end_termcap_mode(TRUE) #endif ) { if (!eap->forceit) autowrite_all(); windgoto((int)Rows - 1, 0); out_char('\n'); out_flush(); stoptermcap(); out_flush(); /* needed for SUN to restore xterm buffer */ #ifdef FEAT_TITLE mch_restore_title(3); /* restore window titles */ #endif ui_suspend(); /* call machine specific function */ #ifdef FEAT_TITLE maketitle(); resettitle(); /* force updating the title */ #endif starttermcap(); scroll_start(); /* scroll screen before redrawing */ redraw_later_clear(); shell_resized(); /* may have resized window */ } } /* * ":exit", ":xit" and ":wq": Write file and exit Vim. */ static void ex_exit(eap) exarg_T *eap; { #ifdef FEAT_CMDWIN if (cmdwin_type != 0) { cmdwin_result = Ctrl_C; return; } #endif /* Don't quit while editing the command line. */ if (text_locked()) { text_locked_msg(); return; } #ifdef FEAT_AUTOCMD if (curbuf_locked()) return; #endif /* * if more files or windows we won't exit */ if (check_more(FALSE, eap->forceit) == OK && only_one_window()) exiting = TRUE; if ( ((eap->cmdidx == CMD_wq || curbufIsChanged()) && do_write(eap) == FAIL) || check_more(TRUE, eap->forceit) == FAIL || (only_one_window() && check_changed_any(eap->forceit))) { not_exiting(); } else { #ifdef FEAT_WINDOWS if (only_one_window()) /* quit last window, exit Vim */ #endif getout(0); #ifdef FEAT_WINDOWS # ifdef FEAT_GUI need_mouse_correct = TRUE; # endif /* quit current window, may free buffer */ win_close(curwin, !P_HID(curwin->w_buffer)); #endif } } /* * ":print", ":list", ":number". */ static void ex_print(eap) exarg_T *eap; { if (curbuf->b_ml.ml_flags & ML_EMPTY) EMSG(_(e_emptybuf)); else { for ( ;!got_int; ui_breakcheck()) { print_line(eap->line1, (eap->cmdidx == CMD_number || eap->cmdidx == CMD_pound || (eap->flags & EXFLAG_NR)), eap->cmdidx == CMD_list || (eap->flags & EXFLAG_LIST)); if (++eap->line1 > eap->line2) break; out_flush(); /* show one line at a time */ } setpcmark(); /* put cursor at last line */ curwin->w_cursor.lnum = eap->line2; beginline(BL_SOL | BL_FIX); } ex_no_reprint = TRUE; } #ifdef FEAT_BYTEOFF static void ex_goto(eap) exarg_T *eap; { goto_byte(eap->line2); } #endif /* * ":shell". */ static void ex_shell(eap) exarg_T *eap UNUSED; { do_shell(NULL, 0); } #if (defined(FEAT_WINDOWS) && defined(HAVE_DROP_FILE)) \ || (defined(FEAT_GUI_GTK) && defined(FEAT_DND)) \ || defined(FEAT_GUI_MSWIN) \ || defined(FEAT_GUI_MAC) \ || defined(PROTO) /* * Handle a file drop. The code is here because a drop is *nearly* like an * :args command, but not quite (we have a list of exact filenames, so we * don't want to (a) parse a command line, or (b) expand wildcards. So the * code is very similar to :args and hence needs access to a lot of the static * functions in this file. * * The list should be allocated using alloc(), as should each item in the * list. This function takes over responsibility for freeing the list. * * XXX The list is made into the argument list. This is freed using * FreeWild(), which does a series of vim_free() calls, unless the two defines * __EMX__ and __ALWAYS_HAS_TRAILING_NUL_POINTER are set. In this case, a * routine _fnexplodefree() is used. This may cause problems, but as the drop * file functionality is (currently) not in EMX this is not presently a * problem. */ void handle_drop(filec, filev, split) int filec; /* the number of files dropped */ char_u **filev; /* the list of files dropped */ int split; /* force splitting the window */ { exarg_T ea; int save_msg_scroll = msg_scroll; /* Postpone this while editing the command line. */ if (text_locked()) return; #ifdef FEAT_AUTOCMD if (curbuf_locked()) return; #endif /* When the screen is being updated we should not change buffers and * windows structures, it may cause freed memory to be used. */ if (updating_screen) return; /* Check whether the current buffer is changed. If so, we will need * to split the current window or data could be lost. * We don't need to check if the 'hidden' option is set, as in this * case the buffer won't be lost. */ if (!P_HID(curbuf) && !split) { ++emsg_off; split = check_changed(curbuf, TRUE, FALSE, FALSE, FALSE); --emsg_off; } if (split) { # ifdef FEAT_WINDOWS if (win_split(0, 0) == FAIL) return; RESET_BINDING(curwin); /* When splitting the window, create a new alist. Otherwise the * existing one is overwritten. */ alist_unlink(curwin->w_alist); alist_new(); # else return; /* can't split, always fail */ # endif } /* * Set up the new argument list. */ alist_set(ALIST(curwin), filec, filev, FALSE, NULL, 0); /* * Move to the first file. */ /* Fake up a minimal "next" command for do_argfile() */ vim_memset(&ea, 0, sizeof(ea)); ea.cmd = (char_u *)"next"; do_argfile(&ea, 0); /* do_ecmd() may set need_start_insertmode, but since we never left Insert * mode that is not needed here. */ need_start_insertmode = FALSE; /* Restore msg_scroll, otherwise a following command may cause scrolling * unexpectedly. The screen will be redrawn by the caller, thus * msg_scroll being set by displaying a message is irrelevant. */ msg_scroll = save_msg_scroll; } #endif /* * Clear an argument list: free all file names and reset it to zero entries. */ void alist_clear(al) alist_T *al; { while (--al->al_ga.ga_len >= 0) vim_free(AARGLIST(al)[al->al_ga.ga_len].ae_fname); ga_clear(&al->al_ga); } /* * Init an argument list. */ void alist_init(al) alist_T *al; { ga_init2(&al->al_ga, (int)sizeof(aentry_T), 5); } #if defined(FEAT_WINDOWS) || defined(PROTO) /* * Remove a reference from an argument list. * Ignored when the argument list is the global one. * If the argument list is no longer used by any window, free it. */ void alist_unlink(al) alist_T *al; { if (al != &global_alist && --al->al_refcount <= 0) { alist_clear(al); vim_free(al); } } # if defined(FEAT_LISTCMDS) || defined(HAVE_DROP_FILE) || defined(PROTO) /* * Create a new argument list and use it for the current window. */ void alist_new() { curwin->w_alist = (alist_T *)alloc((unsigned)sizeof(alist_T)); if (curwin->w_alist == NULL) { curwin->w_alist = &global_alist; ++global_alist.al_refcount; } else { curwin->w_alist->al_refcount = 1; alist_init(curwin->w_alist); } } # endif #endif #if (!defined(UNIX) && !defined(__EMX__)) || defined(ARCHIE) || defined(PROTO) /* * Expand the file names in the global argument list. * If "fnum_list" is not NULL, use "fnum_list[fnum_len]" as a list of buffer * numbers to be re-used. */ void alist_expand(fnum_list, fnum_len) int *fnum_list; int fnum_len; { char_u **old_arg_files; int old_arg_count; char_u **new_arg_files; int new_arg_file_count; char_u *save_p_su = p_su; int i; /* Don't use 'suffixes' here. This should work like the shell did the * expansion. Also, the vimrc file isn't read yet, thus the user * can't set the options. */ p_su = empty_option; old_arg_files = (char_u **)alloc((unsigned)(sizeof(char_u *) * GARGCOUNT)); if (old_arg_files != NULL) { for (i = 0; i < GARGCOUNT; ++i) old_arg_files[i] = vim_strsave(GARGLIST[i].ae_fname); old_arg_count = GARGCOUNT; if (expand_wildcards(old_arg_count, old_arg_files, &new_arg_file_count, &new_arg_files, EW_FILE|EW_NOTFOUND|EW_ADDSLASH|EW_NOERROR) == OK && new_arg_file_count > 0) { alist_set(&global_alist, new_arg_file_count, new_arg_files, TRUE, fnum_list, fnum_len); FreeWild(old_arg_count, old_arg_files); } } p_su = save_p_su; } #endif /* * Set the argument list for the current window. * Takes over the allocated files[] and the allocated fnames in it. */ void alist_set(al, count, files, use_curbuf, fnum_list, fnum_len) alist_T *al; int count; char_u **files; int use_curbuf; int *fnum_list; int fnum_len; { int i; alist_clear(al); if (ga_grow(&al->al_ga, count) == OK) { for (i = 0; i < count; ++i) { if (got_int) { /* When adding many buffers this can take a long time. Allow * interrupting here. */ while (i < count) vim_free(files[i++]); break; } /* May set buffer name of a buffer previously used for the * argument list, so that it's re-used by alist_add. */ if (fnum_list != NULL && i < fnum_len) buf_set_name(fnum_list[i], files[i]); alist_add(al, files[i], use_curbuf ? 2 : 1); ui_breakcheck(); } vim_free(files); } else FreeWild(count, files); #ifdef FEAT_WINDOWS if (al == &global_alist) #endif arg_had_last = FALSE; } /* * Add file "fname" to argument list "al". * "fname" must have been allocated and "al" must have been checked for room. */ void alist_add(al, fname, set_fnum) alist_T *al; char_u *fname; int set_fnum; /* 1: set buffer number; 2: re-use curbuf */ { if (fname == NULL) /* don't add NULL file names */ return; #ifdef BACKSLASH_IN_FILENAME slash_adjust(fname); #endif AARGLIST(al)[al->al_ga.ga_len].ae_fname = fname; if (set_fnum > 0) AARGLIST(al)[al->al_ga.ga_len].ae_fnum = buflist_add(fname, BLN_LISTED | (set_fnum == 2 ? BLN_CURBUF : 0)); ++al->al_ga.ga_len; } #if defined(BACKSLASH_IN_FILENAME) || defined(PROTO) /* * Adjust slashes in file names. Called after 'shellslash' was set. */ void alist_slash_adjust() { int i; # ifdef FEAT_WINDOWS win_T *wp; tabpage_T *tp; # endif for (i = 0; i < GARGCOUNT; ++i) if (GARGLIST[i].ae_fname != NULL) slash_adjust(GARGLIST[i].ae_fname); # ifdef FEAT_WINDOWS FOR_ALL_TAB_WINDOWS(tp, wp) if (wp->w_alist != &global_alist) for (i = 0; i < WARGCOUNT(wp); ++i) if (WARGLIST(wp)[i].ae_fname != NULL) slash_adjust(WARGLIST(wp)[i].ae_fname); # endif } #endif /* * ":preserve". */ static void ex_preserve(eap) exarg_T *eap UNUSED; { curbuf->b_flags |= BF_PRESERVED; ml_preserve(curbuf, TRUE); } /* * ":recover". */ static void ex_recover(eap) exarg_T *eap; { /* Set recoverymode right away to avoid the ATTENTION prompt. */ recoverymode = TRUE; if (!check_changed(curbuf, p_awa, TRUE, eap->forceit, FALSE) && (*eap->arg == NUL || setfname(curbuf, eap->arg, NULL, TRUE) == OK)) ml_recover(); recoverymode = FALSE; } /* * Command modifier used in a wrong way. */ static void ex_wrongmodifier(eap) exarg_T *eap; { eap->errmsg = e_invcmd; } #ifdef FEAT_WINDOWS /* * :sview [+command] file split window with new file, read-only * :split [[+command] file] split window with current or new file * :vsplit [[+command] file] split window vertically with current or new file * :new [[+command] file] split window with no or new file * :vnew [[+command] file] split vertically window with no or new file * :sfind [+command] file split window with file in 'path' * * :tabedit open new Tab page with empty window * :tabedit [+command] file open new Tab page and edit "file" * :tabnew [[+command] file] just like :tabedit * :tabfind [+command] file open new Tab page and find "file" */ void ex_splitview(eap) exarg_T *eap; { win_T *old_curwin = curwin; # if defined(FEAT_SEARCHPATH) || defined(FEAT_BROWSE) char_u *fname = NULL; # endif # ifdef FEAT_BROWSE int browse_flag = cmdmod.browse; # endif # ifndef FEAT_VERTSPLIT if (eap->cmdidx == CMD_vsplit || eap->cmdidx == CMD_vnew) { ex_ni(eap); return; } # endif # ifdef FEAT_GUI need_mouse_correct = TRUE; # endif # ifdef FEAT_QUICKFIX /* A ":split" in the quickfix window works like ":new". Don't want two * quickfix windows. But it's OK when doing ":tab split". */ if (bt_quickfix(curbuf) && cmdmod.tab == 0) { if (eap->cmdidx == CMD_split) eap->cmdidx = CMD_new; # ifdef FEAT_VERTSPLIT if (eap->cmdidx == CMD_vsplit) eap->cmdidx = CMD_vnew; # endif } # endif # ifdef FEAT_SEARCHPATH if (eap->cmdidx == CMD_sfind || eap->cmdidx == CMD_tabfind) { fname = find_file_in_path(eap->arg, (int)STRLEN(eap->arg), FNAME_MESS, TRUE, curbuf->b_ffname); if (fname == NULL) goto theend; eap->arg = fname; } # ifdef FEAT_BROWSE else # endif # endif # ifdef FEAT_BROWSE if (cmdmod.browse # ifdef FEAT_VERTSPLIT && eap->cmdidx != CMD_vnew # endif && eap->cmdidx != CMD_new) { # ifdef FEAT_AUTOCMD if ( # ifdef FEAT_GUI !gui.in_use && # endif au_has_group((char_u *)"FileExplorer")) { /* No browsing supported but we do have the file explorer: * Edit the directory. */ if (*eap->arg == NUL || !mch_isdir(eap->arg)) eap->arg = (char_u *)"."; } else # endif { fname = do_browse(0, (char_u *)_("Edit File in new window"), eap->arg, NULL, NULL, NULL, curbuf); if (fname == NULL) goto theend; eap->arg = fname; } } cmdmod.browse = FALSE; /* Don't browse again in do_ecmd(). */ # endif /* * Either open new tab page or split the window. */ if (eap->cmdidx == CMD_tabedit || eap->cmdidx == CMD_tabfind || eap->cmdidx == CMD_tabnew) { if (win_new_tabpage(cmdmod.tab != 0 ? cmdmod.tab : eap->addr_count == 0 ? 0 : (int)eap->line2 + 1) != FAIL) { do_exedit(eap, old_curwin); /* set the alternate buffer for the window we came from */ if (curwin != old_curwin && win_valid(old_curwin) && old_curwin->w_buffer != curbuf && !cmdmod.keepalt) old_curwin->w_alt_fnum = curbuf->b_fnum; } } else if (win_split(eap->addr_count > 0 ? (int)eap->line2 : 0, *eap->cmd == 'v' ? WSP_VERT : 0) != FAIL) { # ifdef FEAT_SCROLLBIND /* Reset 'scrollbind' when editing another file, but keep it when * doing ":split" without arguments. */ if (*eap->arg != NUL # ifdef FEAT_BROWSE || cmdmod.browse # endif ) { RESET_BINDING(curwin); } else do_check_scrollbind(FALSE); # endif do_exedit(eap, old_curwin); } # ifdef FEAT_BROWSE cmdmod.browse = browse_flag; # endif # if defined(FEAT_SEARCHPATH) || defined(FEAT_BROWSE) theend: vim_free(fname); # endif } /* * Open a new tab page. */ void tabpage_new() { exarg_T ea; vim_memset(&ea, 0, sizeof(ea)); ea.cmdidx = CMD_tabnew; ea.cmd = (char_u *)"tabn"; ea.arg = (char_u *)""; ex_splitview(&ea); } /* * :tabnext command */ static void ex_tabnext(eap) exarg_T *eap; { switch (eap->cmdidx) { case CMD_tabfirst: case CMD_tabrewind: goto_tabpage(1); break; case CMD_tablast: goto_tabpage(9999); break; case CMD_tabprevious: case CMD_tabNext: goto_tabpage(eap->addr_count == 0 ? -1 : -(int)eap->line2); break; default: /* CMD_tabnext */ goto_tabpage(eap->addr_count == 0 ? 0 : (int)eap->line2); break; } } /* * :tabmove command */ static void ex_tabmove(eap) exarg_T *eap; { tabpage_move(eap->addr_count == 0 ? 9999 : (int)eap->line2); } /* * :tabs command: List tabs and their contents. */ static void ex_tabs(eap) exarg_T *eap UNUSED; { tabpage_T *tp; win_T *wp; int tabcount = 1; msg_start(); msg_scroll = TRUE; for (tp = first_tabpage; tp != NULL && !got_int; tp = tp->tp_next) { msg_putchar('\n'); vim_snprintf((char *)IObuff, IOSIZE, _("Tab page %d"), tabcount++); msg_outtrans_attr(IObuff, hl_attr(HLF_T)); out_flush(); /* output one line at a time */ ui_breakcheck(); if (tp == curtab) wp = firstwin; else wp = tp->tp_firstwin; for ( ; wp != NULL && !got_int; wp = wp->w_next) { msg_putchar('\n'); msg_putchar(wp == curwin ? '>' : ' '); msg_putchar(' '); msg_putchar(bufIsChanged(wp->w_buffer) ? '+' : ' '); msg_putchar(' '); if (buf_spname(wp->w_buffer) != NULL) STRCPY(IObuff, buf_spname(wp->w_buffer)); else home_replace(wp->w_buffer, wp->w_buffer->b_fname, IObuff, IOSIZE, TRUE); msg_outtrans(IObuff); out_flush(); /* output one line at a time */ ui_breakcheck(); } } } #endif /* FEAT_WINDOWS */ /* * ":mode": Set screen mode. * If no argument given, just get the screen size and redraw. */ static void ex_mode(eap) exarg_T *eap; { if (*eap->arg == NUL) shell_resized(); else mch_screenmode(eap->arg); } #ifdef FEAT_WINDOWS /* * ":resize". * set, increment or decrement current window height */ static void ex_resize(eap) exarg_T *eap; { int n; win_T *wp = curwin; if (eap->addr_count > 0) { n = eap->line2; for (wp = firstwin; wp->w_next != NULL && --n > 0; wp = wp->w_next) ; } #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif n = atol((char *)eap->arg); #ifdef FEAT_VERTSPLIT if (cmdmod.split & WSP_VERT) { if (*eap->arg == '-' || *eap->arg == '+') n += W_WIDTH(curwin); else if (n == 0 && eap->arg[0] == NUL) /* default is very wide */ n = 9999; win_setwidth_win((int)n, wp); } else #endif { if (*eap->arg == '-' || *eap->arg == '+') n += curwin->w_height; else if (n == 0 && eap->arg[0] == NUL) /* default is very wide */ n = 9999; win_setheight_win((int)n, wp); } } #endif /* * ":find [+command] <file>" command. */ static void ex_find(eap) exarg_T *eap; { #ifdef FEAT_SEARCHPATH char_u *fname; int count; fname = find_file_in_path(eap->arg, (int)STRLEN(eap->arg), FNAME_MESS, TRUE, curbuf->b_ffname); if (eap->addr_count > 0) { /* Repeat finding the file "count" times. This matters when it * appears several times in the path. */ count = eap->line2; while (fname != NULL && --count > 0) { vim_free(fname); fname = find_file_in_path(NULL, 0, FNAME_MESS, FALSE, curbuf->b_ffname); } } if (fname != NULL) { eap->arg = fname; #endif do_exedit(eap, NULL); #ifdef FEAT_SEARCHPATH vim_free(fname); } #endif } /* * ":open" simulation: for now just work like ":visual". */ static void ex_open(eap) exarg_T *eap; { regmatch_T regmatch; char_u *p; curwin->w_cursor.lnum = eap->line2; beginline(BL_SOL | BL_FIX); if (*eap->arg == '/') { /* ":open /pattern/": put cursor in column found with pattern */ ++eap->arg; p = skip_regexp(eap->arg, '/', p_magic, NULL); *p = NUL; regmatch.regprog = vim_regcomp(eap->arg, p_magic ? RE_MAGIC : 0); if (regmatch.regprog != NULL) { regmatch.rm_ic = p_ic; p = ml_get_curline(); if (vim_regexec(&regmatch, p, (colnr_T)0)) curwin->w_cursor.col = (colnr_T)(regmatch.startp[0] - p); else EMSG(_(e_nomatch)); vim_free(regmatch.regprog); } /* Move to the NUL, ignore any other arguments. */ eap->arg += STRLEN(eap->arg); } check_cursor(); eap->cmdidx = CMD_visual; do_exedit(eap, NULL); } /* * ":edit", ":badd", ":visual". */ static void ex_edit(eap) exarg_T *eap; { do_exedit(eap, NULL); } /* * ":edit <file>" command and alikes. */ void do_exedit(eap, old_curwin) exarg_T *eap; win_T *old_curwin; /* curwin before doing a split or NULL */ { int n; #ifdef FEAT_WINDOWS int need_hide; #endif int exmode_was = exmode_active; /* * ":vi" command ends Ex mode. */ if (exmode_active && (eap->cmdidx == CMD_visual || eap->cmdidx == CMD_view)) { exmode_active = FALSE; if (*eap->arg == NUL) { /* Special case: ":global/pat/visual\NLvi-commands" */ if (global_busy) { int rd = RedrawingDisabled; int nwr = no_wait_return; int ms = msg_scroll; #ifdef FEAT_GUI int he = hold_gui_events; #endif if (eap->nextcmd != NULL) { stuffReadbuff(eap->nextcmd); eap->nextcmd = NULL; } if (exmode_was != EXMODE_VIM) settmode(TMODE_RAW); RedrawingDisabled = 0; no_wait_return = 0; need_wait_return = FALSE; msg_scroll = 0; #ifdef FEAT_GUI hold_gui_events = 0; #endif must_redraw = CLEAR; main_loop(FALSE, TRUE); RedrawingDisabled = rd; no_wait_return = nwr; msg_scroll = ms; #ifdef FEAT_GUI hold_gui_events = he; #endif } return; } } if ((eap->cmdidx == CMD_new || eap->cmdidx == CMD_tabnew || eap->cmdidx == CMD_tabedit #ifdef FEAT_VERTSPLIT || eap->cmdidx == CMD_vnew #endif ) && *eap->arg == NUL) { /* ":new" or ":tabnew" without argument: edit an new empty buffer */ setpcmark(); (void)do_ecmd(0, NULL, NULL, eap, ECMD_ONE, ECMD_HIDE + (eap->forceit ? ECMD_FORCEIT : 0), old_curwin == NULL ? curwin : NULL); } else if ((eap->cmdidx != CMD_split #ifdef FEAT_VERTSPLIT && eap->cmdidx != CMD_vsplit #endif ) || *eap->arg != NUL #ifdef FEAT_BROWSE || cmdmod.browse #endif ) { #ifdef FEAT_AUTOCMD /* Can't edit another file when "curbuf_lock" is set. Only ":edit" * can bring us here, others are stopped earlier. */ if (*eap->arg != NUL && curbuf_locked()) return; #endif n = readonlymode; if (eap->cmdidx == CMD_view || eap->cmdidx == CMD_sview) readonlymode = TRUE; else if (eap->cmdidx == CMD_enew) readonlymode = FALSE; /* 'readonly' doesn't make sense in an empty buffer */ setpcmark(); if (do_ecmd(0, (eap->cmdidx == CMD_enew ? NULL : eap->arg), NULL, eap, /* ":edit" goes to first line if Vi compatible */ (*eap->arg == NUL && eap->do_ecmd_lnum == 0 && vim_strchr(p_cpo, CPO_GOTO1) != NULL) ? ECMD_ONE : eap->do_ecmd_lnum, (P_HID(curbuf) ? ECMD_HIDE : 0) + (eap->forceit ? ECMD_FORCEIT : 0) #ifdef FEAT_LISTCMDS + (eap->cmdidx == CMD_badd ? ECMD_ADDBUF : 0 ) #endif , old_curwin == NULL ? curwin : NULL) == FAIL) { /* Editing the file failed. If the window was split, close it. */ #ifdef FEAT_WINDOWS if (old_curwin != NULL) { need_hide = (curbufIsChanged() && curbuf->b_nwindows <= 1); if (!need_hide || P_HID(curbuf)) { # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL) cleanup_T cs; /* Reset the error/interrupt/exception state here so that * aborting() returns FALSE when closing a window. */ enter_cleanup(&cs); # endif # ifdef FEAT_GUI need_mouse_correct = TRUE; # endif win_close(curwin, !need_hide && !P_HID(curbuf)); # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL) /* Restore the error/interrupt/exception state if not * discarded by a new aborting error, interrupt, or * uncaught exception. */ leave_cleanup(&cs); # endif } } #endif } else if (readonlymode && curbuf->b_nwindows == 1) { /* When editing an already visited buffer, 'readonly' won't be set * but the previous value is kept. With ":view" and ":sview" we * want the file to be readonly, except when another window is * editing the same buffer. */ curbuf->b_p_ro = TRUE; } readonlymode = n; } else { if (eap->do_ecmd_cmd != NULL) do_cmdline_cmd(eap->do_ecmd_cmd); #ifdef FEAT_TITLE n = curwin->w_arg_idx_invalid; #endif check_arg_idx(curwin); #ifdef FEAT_TITLE if (n != curwin->w_arg_idx_invalid) maketitle(); #endif } #ifdef FEAT_WINDOWS /* * if ":split file" worked, set alternate file name in old window to new * file */ if (old_curwin != NULL && *eap->arg != NUL && curwin != old_curwin && win_valid(old_curwin) && old_curwin->w_buffer != curbuf && !cmdmod.keepalt) old_curwin->w_alt_fnum = curbuf->b_fnum; #endif ex_no_reprint = TRUE; } #ifndef FEAT_GUI /* * ":gui" and ":gvim" when there is no GUI. */ static void ex_nogui(eap) exarg_T *eap; { eap->errmsg = e_nogvim; } #endif #if defined(FEAT_GUI_W32) && defined(FEAT_MENU) && defined(FEAT_TEAROFF) static void ex_tearoff(eap) exarg_T *eap; { gui_make_tearoff(eap->arg); } #endif #if (defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_GTK)) && defined(FEAT_MENU) static void ex_popup(eap) exarg_T *eap; { gui_make_popup(eap->arg, eap->forceit); } #endif static void ex_swapname(eap) exarg_T *eap UNUSED; { if (curbuf->b_ml.ml_mfp == NULL || curbuf->b_ml.ml_mfp->mf_fname == NULL) MSG(_("No swap file")); else msg(curbuf->b_ml.ml_mfp->mf_fname); } /* * ":syncbind" forces all 'scrollbind' windows to have the same relative * offset. * (1998-11-02 16:21:01 R. Edward Ralston <eralston@computer.org>) */ static void ex_syncbind(eap) exarg_T *eap UNUSED; { #ifdef FEAT_SCROLLBIND win_T *wp; long topline; long y; linenr_T old_linenr = curwin->w_cursor.lnum; setpcmark(); /* * determine max topline */ if (curwin->w_p_scb) { topline = curwin->w_topline; for (wp = firstwin; wp; wp = wp->w_next) { if (wp->w_p_scb && wp->w_buffer) { y = wp->w_buffer->b_ml.ml_line_count - p_so; if (topline > y) topline = y; } } if (topline < 1) topline = 1; } else { topline = 1; } /* * set all scrollbind windows to the same topline */ wp = curwin; for (curwin = firstwin; curwin; curwin = curwin->w_next) { if (curwin->w_p_scb) { y = topline - curwin->w_topline; if (y > 0) scrollup(y, TRUE); else scrolldown(-y, TRUE); curwin->w_scbind_pos = topline; redraw_later(VALID); cursor_correct(); #ifdef FEAT_WINDOWS curwin->w_redr_status = TRUE; #endif } } curwin = wp; if (curwin->w_p_scb) { did_syncbind = TRUE; checkpcmark(); if (old_linenr != curwin->w_cursor.lnum) { char_u ctrl_o[2]; ctrl_o[0] = Ctrl_O; ctrl_o[1] = 0; ins_typebuf(ctrl_o, REMAP_NONE, 0, TRUE, FALSE); } } #endif } static void ex_read(eap) exarg_T *eap; { int i; int empty = (curbuf->b_ml.ml_flags & ML_EMPTY); linenr_T lnum; if (eap->usefilter) /* :r!cmd */ do_bang(1, eap, FALSE, FALSE, TRUE); else { if (u_save(eap->line2, (linenr_T)(eap->line2 + 1)) == FAIL) return; #ifdef FEAT_BROWSE if (cmdmod.browse) { char_u *browseFile; browseFile = do_browse(0, (char_u *)_("Append File"), eap->arg, NULL, NULL, NULL, curbuf); if (browseFile != NULL) { i = readfile(browseFile, NULL, eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0); vim_free(browseFile); } else i = OK; } else #endif if (*eap->arg == NUL) { if (check_fname() == FAIL) /* check for no file name */ return; i = readfile(curbuf->b_ffname, curbuf->b_fname, eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0); } else { if (vim_strchr(p_cpo, CPO_ALTREAD) != NULL) (void)setaltfname(eap->arg, eap->arg, (linenr_T)1); i = readfile(eap->arg, NULL, eap->line2, (linenr_T)0, (linenr_T)MAXLNUM, eap, 0); } if (i == FAIL) { #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL) if (!aborting()) #endif EMSG2(_(e_notopen), eap->arg); } else { if (empty && exmode_active) { /* Delete the empty line that remains. Historically ex does * this but vi doesn't. */ if (eap->line2 == 0) lnum = curbuf->b_ml.ml_line_count; else lnum = 1; if (*ml_get(lnum) == NUL && u_savedel(lnum, 1L) == OK) { ml_delete(lnum, FALSE); if (curwin->w_cursor.lnum > 1 && curwin->w_cursor.lnum >= lnum) --curwin->w_cursor.lnum; deleted_lines_mark(lnum, 1L); } } redraw_curbuf_later(VALID); } } } static char_u *prev_dir = NULL; #if defined(EXITFREE) || defined(PROTO) void free_cd_dir() { vim_free(prev_dir); prev_dir = NULL; vim_free(globaldir); globaldir = NULL; } #endif /* * ":cd", ":lcd", ":chdir" and ":lchdir". */ void ex_cd(eap) exarg_T *eap; { char_u *new_dir; char_u *tofree; new_dir = eap->arg; #if !defined(UNIX) && !defined(VMS) /* for non-UNIX ":cd" means: print current directory */ if (*new_dir == NUL) ex_pwd(NULL); else #endif { #ifdef FEAT_AUTOCMD if (allbuf_locked()) return; #endif if (vim_strchr(p_cpo, CPO_CHDIR) != NULL && curbufIsChanged() && !eap->forceit) { EMSG(_("E747: Cannot change directory, buffer is modified (add ! to override)")); return; } /* ":cd -": Change to previous directory */ if (STRCMP(new_dir, "-") == 0) { if (prev_dir == NULL) { EMSG(_("E186: No previous directory")); return; } new_dir = prev_dir; } /* Save current directory for next ":cd -" */ tofree = prev_dir; if (mch_dirname(NameBuff, MAXPATHL) == OK) prev_dir = vim_strsave(NameBuff); else prev_dir = NULL; #if defined(UNIX) || defined(VMS) /* for UNIX ":cd" means: go to home directory */ if (*new_dir == NUL) { /* use NameBuff for home directory name */ # ifdef VMS char_u *p; p = mch_getenv((char_u *)"SYS$LOGIN"); if (p == NULL || *p == NUL) /* empty is the same as not set */ NameBuff[0] = NUL; else vim_strncpy(NameBuff, p, MAXPATHL - 1); # else expand_env((char_u *)"$HOME", NameBuff, MAXPATHL); # endif new_dir = NameBuff; } #endif if (new_dir == NULL || vim_chdir(new_dir)) EMSG(_(e_failed)); else { vim_free(curwin->w_localdir); if (eap->cmdidx == CMD_lcd || eap->cmdidx == CMD_lchdir) { /* If still in global directory, need to remember current * directory as global directory. */ if (globaldir == NULL && prev_dir != NULL) globaldir = vim_strsave(prev_dir); /* Remember this local directory for the window. */ if (mch_dirname(NameBuff, MAXPATHL) == OK) curwin->w_localdir = vim_strsave(NameBuff); } else { /* We are now in the global directory, no need to remember its * name. */ vim_free(globaldir); globaldir = NULL; curwin->w_localdir = NULL; } shorten_fnames(TRUE); /* Echo the new current directory if the command was typed. */ if (KeyTyped || p_verbose >= 5) ex_pwd(eap); } vim_free(tofree); } } /* * ":pwd". */ static void ex_pwd(eap) exarg_T *eap UNUSED; { if (mch_dirname(NameBuff, MAXPATHL) == OK) { #ifdef BACKSLASH_IN_FILENAME slash_adjust(NameBuff); #endif msg(NameBuff); } else EMSG(_("E187: Unknown")); } /* * ":=". */ static void ex_equal(eap) exarg_T *eap; { smsg((char_u *)"%ld", (long)eap->line2); ex_may_print(eap); } static void ex_sleep(eap) exarg_T *eap; { int n; long len; if (cursor_valid()) { n = W_WINROW(curwin) + curwin->w_wrow - msg_scrolled; if (n >= 0) windgoto((int)n, curwin->w_wcol); } len = eap->line2; switch (*eap->arg) { case 'm': break; case NUL: len *= 1000L; break; default: EMSG2(_(e_invarg2), eap->arg); return; } do_sleep(len); } /* * Sleep for "msec" milliseconds, but keep checking for a CTRL-C every second. */ void do_sleep(msec) long msec; { long done; cursor_on(); out_flush(); for (done = 0; !got_int && done < msec; done += 1000L) { ui_delay(msec - done > 1000L ? 1000L : msec - done, TRUE); ui_breakcheck(); #ifdef FEAT_NETBEANS_INTG /* Process the netbeans messages that may have been received in the * call to ui_breakcheck() when the GUI is in use. This may occur when * running a test case. */ netbeans_parse_messages(); #endif } } static void do_exmap(eap, isabbrev) exarg_T *eap; int isabbrev; { int mode; char_u *cmdp; cmdp = eap->cmd; mode = get_map_mode(&cmdp, eap->forceit || isabbrev); switch (do_map((*cmdp == 'n') ? 2 : (*cmdp == 'u'), eap->arg, mode, isabbrev)) { case 1: EMSG(_(e_invarg)); break; case 2: EMSG(isabbrev ? _(e_noabbr) : _(e_nomap)); break; } } /* * ":winsize" command (obsolete). */ static void ex_winsize(eap) exarg_T *eap; { int w, h; char_u *arg = eap->arg; char_u *p; w = getdigits(&arg); arg = skipwhite(arg); p = arg; h = getdigits(&arg); if (*p != NUL && *arg == NUL) set_shellsize(w, h, TRUE); else EMSG(_("E465: :winsize requires two number arguments")); } #ifdef FEAT_WINDOWS static void ex_wincmd(eap) exarg_T *eap; { int xchar = NUL; char_u *p; if (*eap->arg == 'g' || *eap->arg == Ctrl_G) { /* CTRL-W g and CTRL-W CTRL-G have an extra command character */ if (eap->arg[1] == NUL) { EMSG(_(e_invarg)); return; } xchar = eap->arg[1]; p = eap->arg + 2; } else p = eap->arg + 1; eap->nextcmd = check_nextcmd(p); p = skipwhite(p); if (*p != NUL && *p != '"' && eap->nextcmd == NULL) EMSG(_(e_invarg)); else if (!eap->skip) { /* Pass flags on for ":vertical wincmd ]". */ postponed_split_flags = cmdmod.split; postponed_split_tab = cmdmod.tab; do_window(*eap->arg, eap->addr_count > 0 ? eap->line2 : 0L, xchar); postponed_split_flags = 0; postponed_split_tab = 0; } } #endif #if defined(FEAT_GUI) || defined(UNIX) || defined(VMS) || defined(MSWIN) /* * ":winpos". */ static void ex_winpos(eap) exarg_T *eap; { int x, y; char_u *arg = eap->arg; char_u *p; if (*arg == NUL) { # if defined(FEAT_GUI) || defined(MSWIN) # ifdef FEAT_GUI if (gui.in_use && gui_mch_get_winpos(&x, &y) != FAIL) # else if (mch_get_winpos(&x, &y) != FAIL) # endif { sprintf((char *)IObuff, _("Window position: X %d, Y %d"), x, y); msg(IObuff); } else # endif EMSG(_("E188: Obtaining window position not implemented for this platform")); } else { x = getdigits(&arg); arg = skipwhite(arg); p = arg; y = getdigits(&arg); if (*p == NUL || *arg != NUL) { EMSG(_("E466: :winpos requires two number arguments")); return; } # ifdef FEAT_GUI if (gui.in_use) gui_mch_set_winpos(x, y); else if (gui.starting) { /* Remember the coordinates for when the window is opened. */ gui_win_x = x; gui_win_y = y; } # ifdef HAVE_TGETENT else # endif # else # ifdef MSWIN mch_set_winpos(x, y); # endif # endif # ifdef HAVE_TGETENT if (*T_CWP) term_set_winpos(x, y); # endif } } #endif /* * Handle command that work like operators: ":delete", ":yank", ":>" and ":<". */ static void ex_operators(eap) exarg_T *eap; { oparg_T oa; clear_oparg(&oa); oa.regname = eap->regname; oa.start.lnum = eap->line1; oa.end.lnum = eap->line2; oa.line_count = eap->line2 - eap->line1 + 1; oa.motion_type = MLINE; #ifdef FEAT_VIRTUALEDIT virtual_op = FALSE; #endif if (eap->cmdidx != CMD_yank) /* position cursor for undo */ { setpcmark(); curwin->w_cursor.lnum = eap->line1; beginline(BL_SOL | BL_FIX); } switch (eap->cmdidx) { case CMD_delete: oa.op_type = OP_DELETE; op_delete(&oa); break; case CMD_yank: oa.op_type = OP_YANK; (void)op_yank(&oa, FALSE, TRUE); break; default: /* CMD_rshift or CMD_lshift */ if ((eap->cmdidx == CMD_rshift) #ifdef FEAT_RIGHTLEFT ^ curwin->w_p_rl #endif ) oa.op_type = OP_RSHIFT; else oa.op_type = OP_LSHIFT; op_shift(&oa, FALSE, eap->amount); break; } #ifdef FEAT_VIRTUALEDIT virtual_op = MAYBE; #endif ex_may_print(eap); } /* * ":put". */ static void ex_put(eap) exarg_T *eap; { /* ":0put" works like ":1put!". */ if (eap->line2 == 0) { eap->line2 = 1; eap->forceit = TRUE; } curwin->w_cursor.lnum = eap->line2; do_put(eap->regname, eap->forceit ? BACKWARD : FORWARD, 1L, PUT_LINE|PUT_CURSLINE); } /* * Handle ":copy" and ":move". */ static void ex_copymove(eap) exarg_T *eap; { long n; n = get_address(&eap->arg, FALSE, FALSE); if (eap->arg == NULL) /* error detected */ { eap->nextcmd = NULL; return; } get_flags(eap); /* * move or copy lines from 'eap->line1'-'eap->line2' to below line 'n' */ if (n == MAXLNUM || n < 0 || n > curbuf->b_ml.ml_line_count) { EMSG(_(e_invaddr)); return; } if (eap->cmdidx == CMD_move) { if (do_move(eap->line1, eap->line2, n) == FAIL) return; } else ex_copy(eap->line1, eap->line2, n); u_clearline(); beginline(BL_SOL | BL_FIX); ex_may_print(eap); } /* * Print the current line if flags were given to the Ex command. */ static void ex_may_print(eap) exarg_T *eap; { if (eap->flags != 0) { print_line(curwin->w_cursor.lnum, (eap->flags & EXFLAG_NR), (eap->flags & EXFLAG_LIST)); ex_no_reprint = TRUE; } } /* * ":smagic" and ":snomagic". */ static void ex_submagic(eap) exarg_T *eap; { int magic_save = p_magic; p_magic = (eap->cmdidx == CMD_smagic); do_sub(eap); p_magic = magic_save; } /* * ":join". */ static void ex_join(eap) exarg_T *eap; { curwin->w_cursor.lnum = eap->line1; if (eap->line1 == eap->line2) { if (eap->addr_count >= 2) /* :2,2join does nothing */ return; if (eap->line2 == curbuf->b_ml.ml_line_count) { beep_flush(); return; } ++eap->line2; } (void)do_join(eap->line2 - eap->line1 + 1, !eap->forceit, TRUE, TRUE); beginline(BL_WHITE | BL_FIX); ex_may_print(eap); } /* * ":[addr]@r" or ":[addr]*r": execute register */ static void ex_at(eap) exarg_T *eap; { int c; int prev_len = typebuf.tb_len; curwin->w_cursor.lnum = eap->line2; #ifdef USE_ON_FLY_SCROLL dont_scroll = TRUE; /* disallow scrolling here */ #endif /* get the register name. No name means to use the previous one */ c = *eap->arg; if (c == NUL || (c == '*' && *eap->cmd == '*')) c = '@'; /* Put the register in the typeahead buffer with the "silent" flag. */ if (do_execreg(c, TRUE, vim_strchr(p_cpo, CPO_EXECBUF) != NULL, TRUE) == FAIL) { beep_flush(); } else { int save_efr = exec_from_reg; exec_from_reg = TRUE; /* * Execute from the typeahead buffer. * Continue until the stuff buffer is empty and all added characters * have been consumed. */ while (!stuff_empty() || typebuf.tb_len > prev_len) (void)do_cmdline(NULL, getexline, NULL, DOCMD_NOWAIT|DOCMD_VERBOSE); exec_from_reg = save_efr; } } /* * ":!". */ static void ex_bang(eap) exarg_T *eap; { do_bang(eap->addr_count, eap, eap->forceit, TRUE, TRUE); } /* * ":undo". */ static void ex_undo(eap) exarg_T *eap UNUSED; { if (eap->addr_count == 1) /* :undo 123 */ undo_time(eap->line2, FALSE, FALSE, TRUE); else u_undo(1); } #ifdef FEAT_PERSISTENT_UNDO static void ex_wundo(eap) exarg_T *eap; { char_u hash[UNDO_HASH_SIZE]; u_compute_hash(hash); u_write_undo(eap->arg, eap->forceit, curbuf, hash); } static void ex_rundo(eap) exarg_T *eap; { char_u hash[UNDO_HASH_SIZE]; u_compute_hash(hash); u_read_undo(eap->arg, hash, NULL); } #endif /* * ":redo". */ static void ex_redo(eap) exarg_T *eap UNUSED; { u_redo(1); } /* * ":earlier" and ":later". */ static void ex_later(eap) exarg_T *eap; { long count = 0; int sec = FALSE; int file = FALSE; char_u *p = eap->arg; if (*p == NUL) count = 1; else if (isdigit(*p)) { count = getdigits(&p); switch (*p) { case 's': ++p; sec = TRUE; break; case 'm': ++p; sec = TRUE; count *= 60; break; case 'h': ++p; sec = TRUE; count *= 60 * 60; break; case 'd': ++p; sec = TRUE; count *= 24 * 60 * 60; break; case 'f': ++p; file = TRUE; break; } } if (*p != NUL) EMSG2(_(e_invarg2), eap->arg); else undo_time(eap->cmdidx == CMD_earlier ? -count : count, sec, file, FALSE); } /* * ":redir": start/stop redirection. */ static void ex_redir(eap) exarg_T *eap; { char *mode; char_u *fname; char_u *arg = eap->arg; if (STRICMP(eap->arg, "END") == 0) close_redir(); else { if (*arg == '>') { ++arg; if (*arg == '>') { ++arg; mode = "a"; } else mode = "w"; arg = skipwhite(arg); close_redir(); /* Expand environment variables and "~/". */ fname = expand_env_save(arg); if (fname == NULL) return; #ifdef FEAT_BROWSE if (cmdmod.browse) { char_u *browseFile; browseFile = do_browse(BROWSE_SAVE, (char_u *)_("Save Redirection"), fname, NULL, NULL, BROWSE_FILTER_ALL_FILES, curbuf); if (browseFile == NULL) return; /* operation cancelled */ vim_free(fname); fname = browseFile; eap->forceit = TRUE; /* since dialog already asked */ } #endif redir_fd = open_exfile(fname, eap->forceit, mode); vim_free(fname); } #ifdef FEAT_EVAL else if (*arg == '@') { /* redirect to a register a-z (resp. A-Z for appending) */ close_redir(); ++arg; if (ASCII_ISALPHA(*arg) # ifdef FEAT_CLIPBOARD || *arg == '*' || *arg == '+' # endif || *arg == '"') { redir_reg = *arg++; if (*arg == '>' && arg[1] == '>') /* append */ arg += 2; else { /* Can use both "@a" and "@a>". */ if (*arg == '>') arg++; /* Make register empty when not using @A-@Z and the * command is valid. */ if (*arg == NUL && !isupper(redir_reg)) write_reg_contents(redir_reg, (char_u *)"", -1, FALSE); } } if (*arg != NUL) { redir_reg = 0; EMSG2(_(e_invarg2), eap->arg); } } else if (*arg == '=' && arg[1] == '>') { int append; /* redirect to a variable */ close_redir(); arg += 2; if (*arg == '>') { ++arg; append = TRUE; } else append = FALSE; if (var_redir_start(skipwhite(arg), append) == OK) redir_vname = 1; } #endif /* TODO: redirect to a buffer */ else EMSG2(_(e_invarg2), eap->arg); } /* Make sure redirection is not off. Can happen for cmdline completion * that indirectly invokes a command to catch its output. */ if (redir_fd != NULL #ifdef FEAT_EVAL || redir_reg || redir_vname #endif ) redir_off = FALSE; } /* * ":redraw": force redraw */ static void ex_redraw(eap) exarg_T *eap; { int r = RedrawingDisabled; int p = p_lz; RedrawingDisabled = 0; p_lz = FALSE; update_topline(); update_screen(eap->forceit ? CLEAR : #ifdef FEAT_VISUAL VIsual_active ? INVERTED : #endif 0); #ifdef FEAT_TITLE if (need_maketitle) maketitle(); #endif RedrawingDisabled = r; p_lz = p; /* Reset msg_didout, so that a message that's there is overwritten. */ msg_didout = FALSE; msg_col = 0; out_flush(); } /* * ":redrawstatus": force redraw of status line(s) */ static void ex_redrawstatus(eap) exarg_T *eap UNUSED; { #if defined(FEAT_WINDOWS) int r = RedrawingDisabled; int p = p_lz; RedrawingDisabled = 0; p_lz = FALSE; if (eap->forceit) status_redraw_all(); else status_redraw_curbuf(); update_screen( # ifdef FEAT_VISUAL VIsual_active ? INVERTED : # endif 0); RedrawingDisabled = r; p_lz = p; out_flush(); #endif } static void close_redir() { if (redir_fd != NULL) { fclose(redir_fd); redir_fd = NULL; } #ifdef FEAT_EVAL redir_reg = 0; if (redir_vname) { var_redir_stop(); redir_vname = 0; } #endif } #if defined(FEAT_SESSION) && defined(USE_CRNL) # define MKSESSION_NL static int mksession_nl = FALSE; /* use NL only in put_eol() */ #endif /* * ":mkexrc", ":mkvimrc", ":mkview" and ":mksession". */ static void ex_mkrc(eap) exarg_T *eap; { FILE *fd; int failed = FALSE; char_u *fname; #ifdef FEAT_BROWSE char_u *browseFile = NULL; #endif #ifdef FEAT_SESSION int view_session = FALSE; int using_vdir = FALSE; /* using 'viewdir'? */ char_u *viewFile = NULL; unsigned *flagp; #endif if (eap->cmdidx == CMD_mksession || eap->cmdidx == CMD_mkview) { #ifdef FEAT_SESSION view_session = TRUE; #else ex_ni(eap); return; #endif } #ifdef FEAT_SESSION /* Use the short file name until ":lcd" is used. We also don't use the * short file name when 'acd' is set, that is checked later. */ did_lcd = FALSE; /* ":mkview" or ":mkview 9": generate file name with 'viewdir' */ if (eap->cmdidx == CMD_mkview && (*eap->arg == NUL || (vim_isdigit(*eap->arg) && eap->arg[1] == NUL))) { eap->forceit = TRUE; fname = get_view_file(*eap->arg); if (fname == NULL) return; viewFile = fname; using_vdir = TRUE; } else #endif if (*eap->arg != NUL) fname = eap->arg; else if (eap->cmdidx == CMD_mkvimrc) fname = (char_u *)VIMRC_FILE; #ifdef FEAT_SESSION else if (eap->cmdidx == CMD_mksession) fname = (char_u *)SESSION_FILE; #endif else fname = (char_u *)EXRC_FILE; #ifdef FEAT_BROWSE if (cmdmod.browse) { browseFile = do_browse(BROWSE_SAVE, # ifdef FEAT_SESSION eap->cmdidx == CMD_mkview ? (char_u *)_("Save View") : eap->cmdidx == CMD_mksession ? (char_u *)_("Save Session") : # endif (char_u *)_("Save Setup"), fname, (char_u *)"vim", NULL, BROWSE_FILTER_MACROS, NULL); if (browseFile == NULL) goto theend; fname = browseFile; eap->forceit = TRUE; /* since dialog already asked */ } #endif #if defined(FEAT_SESSION) && defined(vim_mkdir) /* When using 'viewdir' may have to create the directory. */ if (using_vdir && !mch_isdir(p_vdir)) vim_mkdir_emsg(p_vdir, 0755); #endif fd = open_exfile(fname, eap->forceit, WRITEBIN); if (fd != NULL) { #ifdef FEAT_SESSION if (eap->cmdidx == CMD_mkview) flagp = &vop_flags; else flagp = &ssop_flags; #endif #ifdef MKSESSION_NL /* "unix" in 'sessionoptions': use NL line separator */ if (view_session && (*flagp & SSOP_UNIX)) mksession_nl = TRUE; #endif /* Write the version command for :mkvimrc */ if (eap->cmdidx == CMD_mkvimrc) (void)put_line(fd, "version 6.0"); #ifdef FEAT_SESSION if (eap->cmdidx == CMD_mksession) { if (put_line(fd, "let SessionLoad = 1") == FAIL) failed = TRUE; } if (eap->cmdidx != CMD_mkview) #endif { /* Write setting 'compatible' first, because it has side effects. * For that same reason only do it when needed. */ if (p_cp) (void)put_line(fd, "if !&cp | set cp | endif"); else (void)put_line(fd, "if &cp | set nocp | endif"); } #ifdef FEAT_SESSION if (!view_session || (eap->cmdidx == CMD_mksession && (*flagp & SSOP_OPTIONS))) #endif failed |= (makemap(fd, NULL) == FAIL || makeset(fd, OPT_GLOBAL, FALSE) == FAIL); #ifdef FEAT_SESSION if (!failed && view_session) { if (put_line(fd, "let s:so_save = &so | let s:siso_save = &siso | set so=0 siso=0") == FAIL) failed = TRUE; if (eap->cmdidx == CMD_mksession) { char_u *dirnow; /* current directory */ dirnow = alloc(MAXPATHL); if (dirnow == NULL) failed = TRUE; else { /* * Change to session file's dir. */ if (mch_dirname(dirnow, MAXPATHL) == FAIL || mch_chdir((char *)dirnow) != 0) *dirnow = NUL; if (*dirnow != NUL && (ssop_flags & SSOP_SESDIR)) { if (vim_chdirfile(fname) == OK) shorten_fnames(TRUE); } else if (*dirnow != NUL && (ssop_flags & SSOP_CURDIR) && globaldir != NULL) { if (mch_chdir((char *)globaldir) == 0) shorten_fnames(TRUE); } failed |= (makeopens(fd, dirnow) == FAIL); /* restore original dir */ if (*dirnow != NUL && ((ssop_flags & SSOP_SESDIR) || ((ssop_flags & SSOP_CURDIR) && globaldir != NULL))) { if (mch_chdir((char *)dirnow) != 0) EMSG(_(e_prev_dir)); shorten_fnames(TRUE); } vim_free(dirnow); } } else { failed |= (put_view(fd, curwin, !using_vdir, flagp, -1) == FAIL); } if (put_line(fd, "let &so = s:so_save | let &siso = s:siso_save") == FAIL) failed = TRUE; if (put_line(fd, "doautoall SessionLoadPost") == FAIL) failed = TRUE; if (eap->cmdidx == CMD_mksession) { if (put_line(fd, "unlet SessionLoad") == FAIL) failed = TRUE; } } #endif if (put_line(fd, "\" vim: set ft=vim :") == FAIL) failed = TRUE; failed |= fclose(fd); if (failed) EMSG(_(e_write)); #if defined(FEAT_EVAL) && defined(FEAT_SESSION) else if (eap->cmdidx == CMD_mksession) { /* successful session write - set this_session var */ char_u *tbuf; tbuf = alloc(MAXPATHL); if (tbuf != NULL) { if (vim_FullName(fname, tbuf, MAXPATHL, FALSE) == OK) set_vim_var_string(VV_THIS_SESSION, tbuf, -1); vim_free(tbuf); } } #endif #ifdef MKSESSION_NL mksession_nl = FALSE; #endif } #ifdef FEAT_BROWSE theend: vim_free(browseFile); #endif #ifdef FEAT_SESSION vim_free(viewFile); #endif } #if ((defined(FEAT_SESSION) || defined(FEAT_EVAL)) && defined(vim_mkdir)) \ || defined(PROTO) int vim_mkdir_emsg(name, prot) char_u *name; int prot UNUSED; { if (vim_mkdir(name, prot) != 0) { EMSG2(_("E739: Cannot create directory: %s"), name); return FAIL; } return OK; } #endif /* * Open a file for writing for an Ex command, with some checks. * Return file descriptor, or NULL on failure. */ FILE * open_exfile(fname, forceit, mode) char_u *fname; int forceit; char *mode; /* "w" for create new file or "a" for append */ { FILE *fd; #ifdef UNIX /* with Unix it is possible to open a directory */ if (mch_isdir(fname)) { EMSG2(_(e_isadir2), fname); return NULL; } #endif if (!forceit && *mode != 'a' && vim_fexists(fname)) { EMSG2(_("E189: \"%s\" exists (add ! to override)"), fname); return NULL; } if ((fd = mch_fopen((char *)fname, mode)) == NULL) EMSG2(_("E190: Cannot open \"%s\" for writing"), fname); return fd; } /* * ":mark" and ":k". */ static void ex_mark(eap) exarg_T *eap; { pos_T pos; if (*eap->arg == NUL) /* No argument? */ EMSG(_(e_argreq)); else if (eap->arg[1] != NUL) /* more than one character? */ EMSG(_(e_trailing)); else { pos = curwin->w_cursor; /* save curwin->w_cursor */ curwin->w_cursor.lnum = eap->line2; beginline(BL_WHITE | BL_FIX); if (setmark(*eap->arg) == FAIL) /* set mark */ EMSG(_("E191: Argument must be a letter or forward/backward quote")); curwin->w_cursor = pos; /* restore curwin->w_cursor */ } } /* * Update w_topline, w_leftcol and the cursor position. */ void update_topline_cursor() { check_cursor(); /* put cursor on valid line */ update_topline(); if (!curwin->w_p_wrap) validate_cursor(); update_curswant(); } #ifdef FEAT_EX_EXTRA /* * ":normal[!] {commands}": Execute normal mode commands. */ static void ex_normal(eap) exarg_T *eap; { int save_msg_scroll = msg_scroll; int save_restart_edit = restart_edit; int save_msg_didout = msg_didout; int save_State = State; tasave_T tabuf; int save_insertmode = p_im; int save_finish_op = finish_op; int save_opcount = opcount; #ifdef FEAT_MBYTE char_u *arg = NULL; int l; char_u *p; #endif if (ex_normal_lock > 0) { EMSG(_(e_secure)); return; } if (ex_normal_busy >= p_mmd) { EMSG(_("E192: Recursive use of :normal too deep")); return; } ++ex_normal_busy; msg_scroll = FALSE; /* no msg scrolling in Normal mode */ restart_edit = 0; /* don't go to Insert mode */ p_im = FALSE; /* don't use 'insertmode' */ #ifdef FEAT_MBYTE /* * vgetc() expects a CSI and K_SPECIAL to have been escaped. Don't do * this for the K_SPECIAL leading byte, otherwise special keys will not * work. */ if (has_mbyte) { int len = 0; /* Count the number of characters to be escaped. */ for (p = eap->arg; *p != NUL; ++p) { # ifdef FEAT_GUI if (*p == CSI) /* leadbyte CSI */ len += 2; # endif for (l = (*mb_ptr2len)(p) - 1; l > 0; --l) if (*++p == K_SPECIAL /* trailbyte K_SPECIAL or CSI */ # ifdef FEAT_GUI || *p == CSI # endif ) len += 2; } if (len > 0) { arg = alloc((unsigned)(STRLEN(eap->arg) + len + 1)); if (arg != NULL) { len = 0; for (p = eap->arg; *p != NUL; ++p) { arg[len++] = *p; # ifdef FEAT_GUI if (*p == CSI) { arg[len++] = KS_EXTRA; arg[len++] = (int)KE_CSI; } # endif for (l = (*mb_ptr2len)(p) - 1; l > 0; --l) { arg[len++] = *++p; if (*p == K_SPECIAL) { arg[len++] = KS_SPECIAL; arg[len++] = KE_FILLER; } # ifdef FEAT_GUI else if (*p == CSI) { arg[len++] = KS_EXTRA; arg[len++] = (int)KE_CSI; } # endif } arg[len] = NUL; } } } } #endif /* * Save the current typeahead. This is required to allow using ":normal" * from an event handler and makes sure we don't hang when the argument * ends with half a command. */ save_typeahead(&tabuf); if (tabuf.typebuf_valid) { /* * Repeat the :normal command for each line in the range. When no * range given, execute it just once, without positioning the cursor * first. */ do { if (eap->addr_count != 0) { curwin->w_cursor.lnum = eap->line1++; curwin->w_cursor.col = 0; } exec_normal_cmd( #ifdef FEAT_MBYTE arg != NULL ? arg : #endif eap->arg, eap->forceit ? REMAP_NONE : REMAP_YES, FALSE); } while (eap->addr_count > 0 && eap->line1 <= eap->line2 && !got_int); } /* Might not return to the main loop when in an event handler. */ update_topline_cursor(); /* Restore the previous typeahead. */ restore_typeahead(&tabuf); --ex_normal_busy; msg_scroll = save_msg_scroll; restart_edit = save_restart_edit; p_im = save_insertmode; finish_op = save_finish_op; opcount = save_opcount; msg_didout |= save_msg_didout; /* don't reset msg_didout now */ /* Restore the state (needed when called from a function executed for * 'indentexpr'). */ State = save_State; #ifdef FEAT_MBYTE vim_free(arg); #endif } /* * ":startinsert", ":startreplace" and ":startgreplace" */ static void ex_startinsert(eap) exarg_T *eap; { if (eap->forceit) { coladvance((colnr_T)MAXCOL); curwin->w_curswant = MAXCOL; curwin->w_set_curswant = FALSE; } /* Ignore the command when already in Insert mode. Inserting an * expression register that invokes a function can do this. */ if (State & INSERT) return; if (eap->cmdidx == CMD_startinsert) restart_edit = 'a'; else if (eap->cmdidx == CMD_startreplace) restart_edit = 'R'; else restart_edit = 'V'; if (!eap->forceit) { if (eap->cmdidx == CMD_startinsert) restart_edit = 'i'; curwin->w_curswant = 0; /* avoid MAXCOL */ } } /* * ":stopinsert" */ static void ex_stopinsert(eap) exarg_T *eap UNUSED; { restart_edit = 0; stop_insert_mode = TRUE; } #endif #if defined(FEAT_EX_EXTRA) || defined(FEAT_MENU) || defined(PROTO) /* * Execute normal mode command "cmd". * "remap" can be REMAP_NONE or REMAP_YES. */ void exec_normal_cmd(cmd, remap, silent) char_u *cmd; int remap; int silent; { oparg_T oa; /* * Stuff the argument into the typeahead buffer. * Execute normal_cmd() until there is no typeahead left. */ clear_oparg(&oa); finish_op = FALSE; ins_typebuf(cmd, remap, 0, TRUE, silent); while ((!stuff_empty() || (!typebuf_typed() && typebuf.tb_len > 0)) && !got_int) { update_topline_cursor(); normal_cmd(&oa, TRUE); /* execute a Normal mode cmd */ } } #endif #ifdef FEAT_FIND_ID static void ex_checkpath(eap) exarg_T *eap; { find_pattern_in_path(NULL, 0, 0, FALSE, FALSE, CHECK_PATH, 1L, eap->forceit ? ACTION_SHOW_ALL : ACTION_SHOW, (linenr_T)1, (linenr_T)MAXLNUM); } #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX) /* * ":psearch" */ static void ex_psearch(eap) exarg_T *eap; { g_do_tagpreview = p_pvh; ex_findpat(eap); g_do_tagpreview = 0; } #endif static void ex_findpat(eap) exarg_T *eap; { int whole = TRUE; long n; char_u *p; int action; switch (cmdnames[eap->cmdidx].cmd_name[2]) { case 'e': /* ":psearch", ":isearch" and ":dsearch" */ if (cmdnames[eap->cmdidx].cmd_name[0] == 'p') action = ACTION_GOTO; else action = ACTION_SHOW; break; case 'i': /* ":ilist" and ":dlist" */ action = ACTION_SHOW_ALL; break; case 'u': /* ":ijump" and ":djump" */ action = ACTION_GOTO; break; default: /* ":isplit" and ":dsplit" */ action = ACTION_SPLIT; break; } n = 1; if (vim_isdigit(*eap->arg)) /* get count */ { n = getdigits(&eap->arg); eap->arg = skipwhite(eap->arg); } if (*eap->arg == '/') /* Match regexp, not just whole words */ { whole = FALSE; ++eap->arg; p = skip_regexp(eap->arg, '/', p_magic, NULL); if (*p) { *p++ = NUL; p = skipwhite(p); /* Check for trailing illegal characters */ if (!ends_excmd(*p)) eap->errmsg = e_trailing; else eap->nextcmd = check_nextcmd(p); } } if (!eap->skip) find_pattern_in_path(eap->arg, 0, (int)STRLEN(eap->arg), whole, !eap->forceit, *eap->cmd == 'd' ? FIND_DEFINE : FIND_ANY, n, action, eap->line1, eap->line2); } #endif #ifdef FEAT_WINDOWS # ifdef FEAT_QUICKFIX /* * ":ptag", ":ptselect", ":ptjump", ":ptnext", etc. */ static void ex_ptag(eap) exarg_T *eap; { g_do_tagpreview = p_pvh; /* will be reset to 0 in ex_tag_cmd() */ ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name + 1); } /* * ":pedit" */ static void ex_pedit(eap) exarg_T *eap; { win_T *curwin_save = curwin; g_do_tagpreview = p_pvh; prepare_tagpreview(TRUE); keep_help_flag = curwin_save->w_buffer->b_help; do_exedit(eap, NULL); keep_help_flag = FALSE; if (curwin != curwin_save && win_valid(curwin_save)) { /* Return cursor to where we were */ validate_cursor(); redraw_later(VALID); win_enter(curwin_save, TRUE); } g_do_tagpreview = 0; } # endif /* * ":stag", ":stselect" and ":stjump". */ static void ex_stag(eap) exarg_T *eap; { postponed_split = -1; postponed_split_flags = cmdmod.split; postponed_split_tab = cmdmod.tab; ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name + 1); postponed_split_flags = 0; postponed_split_tab = 0; } #endif /* * ":tag", ":tselect", ":tjump", ":tnext", etc. */ static void ex_tag(eap) exarg_T *eap; { ex_tag_cmd(eap, cmdnames[eap->cmdidx].cmd_name); } static void ex_tag_cmd(eap, name) exarg_T *eap; char_u *name; { int cmd; switch (name[1]) { case 'j': cmd = DT_JUMP; /* ":tjump" */ break; case 's': cmd = DT_SELECT; /* ":tselect" */ break; case 'p': cmd = DT_PREV; /* ":tprevious" */ break; case 'N': cmd = DT_PREV; /* ":tNext" */ break; case 'n': cmd = DT_NEXT; /* ":tnext" */ break; case 'o': cmd = DT_POP; /* ":pop" */ break; case 'f': /* ":tfirst" */ case 'r': cmd = DT_FIRST; /* ":trewind" */ break; case 'l': cmd = DT_LAST; /* ":tlast" */ break; default: /* ":tag" */ #ifdef FEAT_CSCOPE if (p_cst && *eap->arg != NUL) { do_cstag(eap); return; } #endif cmd = DT_TAG; break; } if (name[0] == 'l') { #ifndef FEAT_QUICKFIX ex_ni(eap); return; #else cmd = DT_LTAG; #endif } do_tag(eap->arg, cmd, eap->addr_count > 0 ? (int)eap->line2 : 1, eap->forceit, TRUE); } /* * Check "str" for starting with a special cmdline variable. * If found return one of the SPEC_ values and set "*usedlen" to the length of * the variable. Otherwise return -1 and "*usedlen" is unchanged. */ int find_cmdline_var(src, usedlen) char_u *src; int *usedlen; { int len; int i; static char *(spec_str[]) = { "%", #define SPEC_PERC 0 "#", #define SPEC_HASH 1 "<cword>", /* cursor word */ #define SPEC_CWORD 2 "<cWORD>", /* cursor WORD */ #define SPEC_CCWORD 3 "<cfile>", /* cursor path name */ #define SPEC_CFILE 4 "<sfile>", /* ":so" file name */ #define SPEC_SFILE 5 "<slnum>", /* ":so" file line number */ #define SPEC_SLNUM 6 #ifdef FEAT_AUTOCMD "<afile>", /* autocommand file name */ # define SPEC_AFILE 7 "<abuf>", /* autocommand buffer number */ # define SPEC_ABUF 8 "<amatch>", /* autocommand match name */ # define SPEC_AMATCH 9 #endif #ifdef FEAT_CLIENTSERVER "<client>" # ifdef FEAT_AUTOCMD # define SPEC_CLIENT 10 # else # define SPEC_CLIENT 7 # endif #endif }; for (i = 0; i < (int)(sizeof(spec_str) / sizeof(char *)); ++i) { len = (int)STRLEN(spec_str[i]); if (STRNCMP(src, spec_str[i], len) == 0) { *usedlen = len; return i; } } return -1; } /* * Evaluate cmdline variables. * * change '%' to curbuf->b_ffname * '#' to curwin->w_altfile * '<cword>' to word under the cursor * '<cWORD>' to WORD under the cursor * '<cfile>' to path name under the cursor * '<sfile>' to sourced file name * '<slnum>' to sourced file line number * '<afile>' to file name for autocommand * '<abuf>' to buffer number for autocommand * '<amatch>' to matching name for autocommand * * When an error is detected, "errormsg" is set to a non-NULL pointer (may be * "" for error without a message) and NULL is returned. * Returns an allocated string if a valid match was found. * Returns NULL if no match was found. "usedlen" then still contains the * number of characters to skip. */ char_u * eval_vars(src, srcstart, usedlen, lnump, errormsg, escaped) char_u *src; /* pointer into commandline */ char_u *srcstart; /* beginning of valid memory for src */ int *usedlen; /* characters after src that are used */ linenr_T *lnump; /* line number for :e command, or NULL */ char_u **errormsg; /* pointer to error message */ int *escaped; /* return value has escaped white space (can * be NULL) */ { int i; char_u *s; char_u *result; char_u *resultbuf = NULL; int resultlen; buf_T *buf; int valid = VALID_HEAD + VALID_PATH; /* assume valid result */ int spec_idx; #ifdef FEAT_MODIFY_FNAME int skip_mod = FALSE; #endif char_u strbuf[30]; *errormsg = NULL; if (escaped != NULL) *escaped = FALSE; /* * Check if there is something to do. */ spec_idx = find_cmdline_var(src, usedlen); if (spec_idx < 0) /* no match */ { *usedlen = 1; return NULL; } /* * Skip when preceded with a backslash "\%" and "\#". * Note: In "\\%" the % is also not recognized! */ if (src > srcstart && src[-1] == '\\') { *usedlen = 0; STRMOVE(src - 1, src); /* remove backslash */ return NULL; } /* * word or WORD under cursor */ if (spec_idx == SPEC_CWORD || spec_idx == SPEC_CCWORD) { resultlen = find_ident_under_cursor(&result, spec_idx == SPEC_CWORD ? (FIND_IDENT|FIND_STRING) : FIND_STRING); if (resultlen == 0) { *errormsg = (char_u *)""; return NULL; } } /* * '#': Alternate file name * '%': Current file name * File name under the cursor * File name for autocommand * and following modifiers */ else { switch (spec_idx) { case SPEC_PERC: /* '%': current file */ if (curbuf->b_fname == NULL) { result = (char_u *)""; valid = 0; /* Must have ":p:h" to be valid */ } else result = curbuf->b_fname; break; case SPEC_HASH: /* '#' or "#99": alternate file */ if (src[1] == '#') /* "##": the argument list */ { result = arg_all(); resultbuf = result; *usedlen = 2; if (escaped != NULL) *escaped = TRUE; #ifdef FEAT_MODIFY_FNAME skip_mod = TRUE; #endif break; } s = src + 1; if (*s == '<') /* "#<99" uses v:oldfiles */ ++s; i = (int)getdigits(&s); *usedlen = (int)(s - src); /* length of what we expand */ if (src[1] == '<') { if (*usedlen < 2) { /* Should we give an error message for #<text? */ *usedlen = 1; return NULL; } #ifdef FEAT_EVAL result = list_find_str(get_vim_var_list(VV_OLDFILES), (long)i); if (result == NULL) { *errormsg = (char_u *)""; return NULL; } #else *errormsg = (char_u *)_("E809: #< is not available without the +eval feature"); return NULL; #endif } else { buf = buflist_findnr(i); if (buf == NULL) { *errormsg = (char_u *)_("E194: No alternate file name to substitute for '#'"); return NULL; } if (lnump != NULL) *lnump = ECMD_LAST; if (buf->b_fname == NULL) { result = (char_u *)""; valid = 0; /* Must have ":p:h" to be valid */ } else result = buf->b_fname; } break; #ifdef FEAT_SEARCHPATH case SPEC_CFILE: /* file name under cursor */ result = file_name_at_cursor(FNAME_MESS|FNAME_HYP, 1L, NULL); if (result == NULL) { *errormsg = (char_u *)""; return NULL; } resultbuf = result; /* remember allocated string */ break; #endif #ifdef FEAT_AUTOCMD case SPEC_AFILE: /* file name for autocommand */ result = autocmd_fname; if (result != NULL && !autocmd_fname_full) { /* Still need to turn the fname into a full path. It is * postponed to avoid a delay when <afile> is not used. */ autocmd_fname_full = TRUE; result = FullName_save(autocmd_fname, FALSE); vim_free(autocmd_fname); autocmd_fname = result; } if (result == NULL) { *errormsg = (char_u *)_("E495: no autocommand file name to substitute for \"<afile>\""); return NULL; } result = shorten_fname1(result); break; case SPEC_ABUF: /* buffer number for autocommand */ if (autocmd_bufnr <= 0) { *errormsg = (char_u *)_("E496: no autocommand buffer number to substitute for \"<abuf>\""); return NULL; } sprintf((char *)strbuf, "%d", autocmd_bufnr); result = strbuf; break; case SPEC_AMATCH: /* match name for autocommand */ result = autocmd_match; if (result == NULL) { *errormsg = (char_u *)_("E497: no autocommand match name to substitute for \"<amatch>\""); return NULL; } break; #endif case SPEC_SFILE: /* file name for ":so" command */ result = sourcing_name; if (result == NULL) { *errormsg = (char_u *)_("E498: no :source file name to substitute for \"<sfile>\""); return NULL; } break; case SPEC_SLNUM: /* line in file for ":so" command */ if (sourcing_name == NULL || sourcing_lnum == 0) { *errormsg = (char_u *)_("E842: no line number to use for \"<slnum>\""); return NULL; } sprintf((char *)strbuf, "%ld", (long)sourcing_lnum); result = strbuf; break; #if defined(FEAT_CLIENTSERVER) case SPEC_CLIENT: /* Source of last submitted input */ sprintf((char *)strbuf, PRINTF_HEX_LONG_U, (long_u)clientWindow); result = strbuf; break; #endif } resultlen = (int)STRLEN(result); /* length of new string */ if (src[*usedlen] == '<') /* remove the file name extension */ { ++*usedlen; if ((s = vim_strrchr(result, '.')) != NULL && s >= gettail(result)) resultlen = (int)(s - result); } #ifdef FEAT_MODIFY_FNAME else if (!skip_mod) { valid |= modify_fname(src, usedlen, &result, &resultbuf, &resultlen); if (result == NULL) { *errormsg = (char_u *)""; return NULL; } } #endif } if (resultlen == 0 || valid != VALID_HEAD + VALID_PATH) { if (valid != VALID_HEAD + VALID_PATH) /* xgettext:no-c-format */ *errormsg = (char_u *)_("E499: Empty file name for '%' or '#', only works with \":p:h\""); else *errormsg = (char_u *)_("E500: Evaluates to an empty string"); result = NULL; } else result = vim_strnsave(result, resultlen); vim_free(resultbuf); return result; } /* * Concatenate all files in the argument list, separated by spaces, and return * it in one allocated string. * Spaces and backslashes in the file names are escaped with a backslash. * Returns NULL when out of memory. */ static char_u * arg_all() { int len; int idx; char_u *retval = NULL; char_u *p; /* * Do this loop two times: * first time: compute the total length * second time: concatenate the names */ for (;;) { len = 0; for (idx = 0; idx < ARGCOUNT; ++idx) { p = alist_name(&ARGLIST[idx]); if (p != NULL) { if (len > 0) { /* insert a space in between names */ if (retval != NULL) retval[len] = ' '; ++len; } for ( ; *p != NUL; ++p) { if (*p == ' ' || *p == '\\') { /* insert a backslash */ if (retval != NULL) retval[len] = '\\'; ++len; } if (retval != NULL) retval[len] = *p; ++len; } } } /* second time: break here */ if (retval != NULL) { retval[len] = NUL; break; } /* allocate memory */ retval = alloc((unsigned)len + 1); if (retval == NULL) break; } return retval; } #if defined(FEAT_AUTOCMD) || defined(PROTO) /* * Expand the <sfile> string in "arg". * * Returns an allocated string, or NULL for any error. */ char_u * expand_sfile(arg) char_u *arg; { char_u *errormsg; int len; char_u *result; char_u *newres; char_u *repl; int srclen; char_u *p; result = vim_strsave(arg); if (result == NULL) return NULL; for (p = result; *p; ) { if (STRNCMP(p, "<sfile>", 7) != 0) ++p; else { /* replace "<sfile>" with the sourced file name, and do ":" stuff */ repl = eval_vars(p, result, &srclen, NULL, &errormsg, NULL); if (errormsg != NULL) { if (*errormsg) emsg(errormsg); vim_free(result); return NULL; } if (repl == NULL) /* no match (cannot happen) */ { p += srclen; continue; } len = (int)STRLEN(result) - srclen + (int)STRLEN(repl) + 1; newres = alloc(len); if (newres == NULL) { vim_free(repl); vim_free(result); return NULL; } mch_memmove(newres, result, (size_t)(p - result)); STRCPY(newres + (p - result), repl); len = (int)STRLEN(newres); STRCAT(newres, p + srclen); vim_free(repl); vim_free(result); result = newres; p = newres + len; /* continue after the match */ } } return result; } #endif #ifdef FEAT_SESSION static int ses_winsizes __ARGS((FILE *fd, int restore_size, win_T *tab_firstwin)); static int ses_win_rec __ARGS((FILE *fd, frame_T *fr)); static frame_T *ses_skipframe __ARGS((frame_T *fr)); static int ses_do_frame __ARGS((frame_T *fr)); static int ses_do_win __ARGS((win_T *wp)); static int ses_arglist __ARGS((FILE *fd, char *cmd, garray_T *gap, int fullname, unsigned *flagp)); static int ses_put_fname __ARGS((FILE *fd, char_u *name, unsigned *flagp)); static int ses_fname __ARGS((FILE *fd, buf_T *buf, unsigned *flagp)); /* * Write openfile commands for the current buffers to an .exrc file. * Return FAIL on error, OK otherwise. */ static int makeopens(fd, dirnow) FILE *fd; char_u *dirnow; /* Current directory name */ { buf_T *buf; int only_save_windows = TRUE; int nr; int cnr = 1; int restore_size = TRUE; win_T *wp; char_u *sname; win_T *edited_win = NULL; int tabnr; win_T *tab_firstwin; frame_T *tab_topframe; int cur_arg_idx = 0; int next_arg_idx = 0; if (ssop_flags & SSOP_BUFFERS) only_save_windows = FALSE; /* Save ALL buffers */ /* * Begin by setting the this_session variable, and then other * sessionable variables. */ #ifdef FEAT_EVAL if (put_line(fd, "let v:this_session=expand(\"<sfile>:p\")") == FAIL) return FAIL; if (ssop_flags & SSOP_GLOBALS) if (store_session_globals(fd) == FAIL) return FAIL; #endif /* * Close all windows but one. */ if (put_line(fd, "silent only") == FAIL) return FAIL; /* * Now a :cd command to the session directory or the current directory */ if (ssop_flags & SSOP_SESDIR) { if (put_line(fd, "exe \"cd \" . escape(expand(\"<sfile>:p:h\"), ' ')") == FAIL) return FAIL; } else if (ssop_flags & SSOP_CURDIR) { sname = home_replace_save(NULL, globaldir != NULL ? globaldir : dirnow); if (sname == NULL || fputs("cd ", fd) < 0 || ses_put_fname(fd, sname, &ssop_flags) == FAIL || put_eol(fd) == FAIL) { vim_free(sname); return FAIL; } vim_free(sname); } /* * If there is an empty, unnamed buffer we will wipe it out later. * Remember the buffer number. */ if (put_line(fd, "if expand('%') == '' && !&modified && line('$') <= 1 && getline(1) == ''") == FAIL) return FAIL; if (put_line(fd, " let s:wipebuf = bufnr('%')") == FAIL) return FAIL; if (put_line(fd, "endif") == FAIL) return FAIL; /* * Now save the current files, current buffer first. */ if (put_line(fd, "set shortmess=aoO") == FAIL) return FAIL; /* Now put the other buffers into the buffer list */ for (buf = firstbuf; buf != NULL; buf = buf->b_next) { if (!(only_save_windows && buf->b_nwindows == 0) && !(buf->b_help && !(ssop_flags & SSOP_HELP)) && buf->b_fname != NULL && buf->b_p_bl) { if (fprintf(fd, "badd +%ld ", buf->b_wininfo == NULL ? 1L : buf->b_wininfo->wi_fpos.lnum) < 0 || ses_fname(fd, buf, &ssop_flags) == FAIL) return FAIL; } } /* the global argument list */ if (ses_arglist(fd, "args", &global_alist.al_ga, !(ssop_flags & SSOP_CURDIR), &ssop_flags) == FAIL) return FAIL; if (ssop_flags & SSOP_RESIZE) { /* Note: after the restore we still check it worked!*/ if (fprintf(fd, "set lines=%ld columns=%ld" , Rows, Columns) < 0 || put_eol(fd) == FAIL) return FAIL; } #ifdef FEAT_GUI if (gui.in_use && (ssop_flags & SSOP_WINPOS)) { int x, y; if (gui_mch_get_winpos(&x, &y) == OK) { /* Note: after the restore we still check it worked!*/ if (fprintf(fd, "winpos %d %d", x, y) < 0 || put_eol(fd) == FAIL) return FAIL; } } #endif /* * May repeat putting Windows for each tab, when "tabpages" is in * 'sessionoptions'. * Don't use goto_tabpage(), it may change directory and trigger * autocommands. */ tab_firstwin = firstwin; /* first window in tab page "tabnr" */ tab_topframe = topframe; for (tabnr = 1; ; ++tabnr) { int need_tabnew = FALSE; if ((ssop_flags & SSOP_TABPAGES)) { tabpage_T *tp = find_tabpage(tabnr); if (tp == NULL) break; /* done all tab pages */ if (tp == curtab) { tab_firstwin = firstwin; tab_topframe = topframe; } else { tab_firstwin = tp->tp_firstwin; tab_topframe = tp->tp_topframe; } if (tabnr > 1) need_tabnew = TRUE; } /* * Before creating the window layout, try loading one file. If this * is aborted we don't end up with a number of useless windows. * This may have side effects! (e.g., compressed or network file). */ for (wp = tab_firstwin; wp != NULL; wp = wp->w_next) { if (ses_do_win(wp) && wp->w_buffer->b_ffname != NULL && !wp->w_buffer->b_help #ifdef FEAT_QUICKFIX && !bt_nofile(wp->w_buffer) #endif ) { if (fputs(need_tabnew ? "tabedit " : "edit ", fd) < 0 || ses_fname(fd, wp->w_buffer, &ssop_flags) == FAIL) return FAIL; need_tabnew = FALSE; if (!wp->w_arg_idx_invalid) edited_win = wp; break; } } /* If no file got edited create an empty tab page. */ if (need_tabnew && put_line(fd, "tabnew") == FAIL) return FAIL; /* * Save current window layout. */ if (put_line(fd, "set splitbelow splitright") == FAIL) return FAIL; if (ses_win_rec(fd, tab_topframe) == FAIL) return FAIL; if (!p_sb && put_line(fd, "set nosplitbelow") == FAIL) return FAIL; if (!p_spr && put_line(fd, "set nosplitright") == FAIL) return FAIL; /* * Check if window sizes can be restored (no windows omitted). * Remember the window number of the current window after restoring. */ nr = 0; for (wp = tab_firstwin; wp != NULL; wp = W_NEXT(wp)) { if (ses_do_win(wp)) ++nr; else restore_size = FALSE; if (curwin == wp) cnr = nr; } /* Go to the first window. */ if (put_line(fd, "wincmd t") == FAIL) return FAIL; /* * If more than one window, see if sizes can be restored. * First set 'winheight' and 'winwidth' to 1 to avoid the windows being * resized when moving between windows. * Do this before restoring the view, so that the topline and the * cursor can be set. This is done again below. */ if (put_line(fd, "set winheight=1 winwidth=1") == FAIL) return FAIL; if (nr > 1 && ses_winsizes(fd, restore_size, tab_firstwin) == FAIL) return FAIL; /* * Restore the view of the window (options, file, cursor, etc.). */ for (wp = tab_firstwin; wp != NULL; wp = wp->w_next) { if (!ses_do_win(wp)) continue; if (put_view(fd, wp, wp != edited_win, &ssop_flags, cur_arg_idx) == FAIL) return FAIL; if (nr > 1 && put_line(fd, "wincmd w") == FAIL) return FAIL; next_arg_idx = wp->w_arg_idx; } /* The argument index in the first tab page is zero, need to set it in * each window. For further tab pages it's the window where we do * "tabedit". */ cur_arg_idx = next_arg_idx; /* * Restore cursor to the current window if it's not the first one. */ if (cnr > 1 && (fprintf(fd, "%dwincmd w", cnr) < 0 || put_eol(fd) == FAIL)) return FAIL; /* * Restore window sizes again after jumping around in windows, because * the current window has a minimum size while others may not. */ if (nr > 1 && ses_winsizes(fd, restore_size, tab_firstwin) == FAIL) return FAIL; /* Don't continue in another tab page when doing only the current one * or when at the last tab page. */ if (!(ssop_flags & SSOP_TABPAGES)) break; } if (ssop_flags & SSOP_TABPAGES) { if (fprintf(fd, "tabnext %d", tabpage_index(curtab)) < 0 || put_eol(fd) == FAIL) return FAIL; } /* * Wipe out an empty unnamed buffer we started in. */ if (put_line(fd, "if exists('s:wipebuf')") == FAIL) return FAIL; if (put_line(fd, " silent exe 'bwipe ' . s:wipebuf") == FAIL) return FAIL; if (put_line(fd, "endif") == FAIL) return FAIL; if (put_line(fd, "unlet! s:wipebuf") == FAIL) return FAIL; /* Re-apply 'winheight', 'winwidth' and 'shortmess'. */ if (fprintf(fd, "set winheight=%ld winwidth=%ld shortmess=%s", p_wh, p_wiw, p_shm) < 0 || put_eol(fd) == FAIL) return FAIL; /* * Lastly, execute the x.vim file if it exists. */ if (put_line(fd, "let s:sx = expand(\"<sfile>:p:r\").\"x.vim\"") == FAIL || put_line(fd, "if file_readable(s:sx)") == FAIL || put_line(fd, " exe \"source \" . fnameescape(s:sx)") == FAIL || put_line(fd, "endif") == FAIL) return FAIL; return OK; } static int ses_winsizes(fd, restore_size, tab_firstwin) FILE *fd; int restore_size; win_T *tab_firstwin; { int n = 0; win_T *wp; if (restore_size && (ssop_flags & SSOP_WINSIZE)) { for (wp = tab_firstwin; wp != NULL; wp = wp->w_next) { if (!ses_do_win(wp)) continue; ++n; /* restore height when not full height */ if (wp->w_height + wp->w_status_height < topframe->fr_height && (fprintf(fd, "exe '%dresize ' . ((&lines * %ld + %ld) / %ld)", n, (long)wp->w_height, Rows / 2, Rows) < 0 || put_eol(fd) == FAIL)) return FAIL; /* restore width when not full width */ if (wp->w_width < Columns && (fprintf(fd, "exe 'vert %dresize ' . ((&columns * %ld + %ld) / %ld)", n, (long)wp->w_width, Columns / 2, Columns) < 0 || put_eol(fd) == FAIL)) return FAIL; } } else { /* Just equalise window sizes */ if (put_line(fd, "wincmd =") == FAIL) return FAIL; } return OK; } /* * Write commands to "fd" to recursively create windows for frame "fr", * horizontally and vertically split. * After the commands the last window in the frame is the current window. * Returns FAIL when writing the commands to "fd" fails. */ static int ses_win_rec(fd, fr) FILE *fd; frame_T *fr; { frame_T *frc; int count = 0; if (fr->fr_layout != FR_LEAF) { /* Find first frame that's not skipped and then create a window for * each following one (first frame is already there). */ frc = ses_skipframe(fr->fr_child); if (frc != NULL) while ((frc = ses_skipframe(frc->fr_next)) != NULL) { /* Make window as big as possible so that we have lots of room * to split. */ if (put_line(fd, "wincmd _ | wincmd |") == FAIL || put_line(fd, fr->fr_layout == FR_COL ? "split" : "vsplit") == FAIL) return FAIL; ++count; } /* Go back to the first window. */ if (count > 0 && (fprintf(fd, fr->fr_layout == FR_COL ? "%dwincmd k" : "%dwincmd h", count) < 0 || put_eol(fd) == FAIL)) return FAIL; /* Recursively create frames/windows in each window of this column or * row. */ frc = ses_skipframe(fr->fr_child); while (frc != NULL) { ses_win_rec(fd, frc); frc = ses_skipframe(frc->fr_next); /* Go to next window. */ if (frc != NULL && put_line(fd, "wincmd w") == FAIL) return FAIL; } } return OK; } /* * Skip frames that don't contain windows we want to save in the Session. * Returns NULL when there none. */ static frame_T * ses_skipframe(fr) frame_T *fr; { frame_T *frc; for (frc = fr; frc != NULL; frc = frc->fr_next) if (ses_do_frame(frc)) break; return frc; } /* * Return TRUE if frame "fr" has a window somewhere that we want to save in * the Session. */ static int ses_do_frame(fr) frame_T *fr; { frame_T *frc; if (fr->fr_layout == FR_LEAF) return ses_do_win(fr->fr_win); for (frc = fr->fr_child; frc != NULL; frc = frc->fr_next) if (ses_do_frame(frc)) return TRUE; return FALSE; } /* * Return non-zero if window "wp" is to be stored in the Session. */ static int ses_do_win(wp) win_T *wp; { if (wp->w_buffer->b_fname == NULL #ifdef FEAT_QUICKFIX /* When 'buftype' is "nofile" can't restore the window contents. */ || bt_nofile(wp->w_buffer) #endif ) return (ssop_flags & SSOP_BLANK); if (wp->w_buffer->b_help) return (ssop_flags & SSOP_HELP); return TRUE; } /* * Write commands to "fd" to restore the view of a window. * Caller must make sure 'scrolloff' is zero. */ static int put_view(fd, wp, add_edit, flagp, current_arg_idx) FILE *fd; win_T *wp; int add_edit; /* add ":edit" command to view */ unsigned *flagp; /* vop_flags or ssop_flags */ int current_arg_idx; /* current argument index of the window, use * -1 if unknown */ { win_T *save_curwin; int f; int do_cursor; int did_next = FALSE; /* Always restore cursor position for ":mksession". For ":mkview" only * when 'viewoptions' contains "cursor". */ do_cursor = (flagp == &ssop_flags || *flagp & SSOP_CURSOR); /* * Local argument list. */ if (wp->w_alist == &global_alist) { if (put_line(fd, "argglobal") == FAIL) return FAIL; } else { if (ses_arglist(fd, "arglocal", &wp->w_alist->al_ga, flagp == &vop_flags || !(*flagp & SSOP_CURDIR) || wp->w_localdir != NULL, flagp) == FAIL) return FAIL; } /* Only when part of a session: restore the argument index. Some * arguments may have been deleted, check if the index is valid. */ if (wp->w_arg_idx != current_arg_idx && wp->w_arg_idx < WARGCOUNT(wp) && flagp == &ssop_flags) { if (fprintf(fd, "%ldargu", (long)wp->w_arg_idx + 1) < 0 || put_eol(fd) == FAIL) return FAIL; did_next = TRUE; } /* Edit the file. Skip this when ":next" already did it. */ if (add_edit && (!did_next || wp->w_arg_idx_invalid)) { /* * Load the file. */ if (wp->w_buffer->b_ffname != NULL #ifdef FEAT_QUICKFIX && !bt_nofile(wp->w_buffer) #endif ) { /* * Editing a file in this buffer: use ":edit file". * This may have side effects! (e.g., compressed or network file). */ if (fputs("edit ", fd) < 0 || ses_fname(fd, wp->w_buffer, flagp) == FAIL) return FAIL; } else { /* No file in this buffer, just make it empty. */ if (put_line(fd, "enew") == FAIL) return FAIL; #ifdef FEAT_QUICKFIX if (wp->w_buffer->b_ffname != NULL) { /* The buffer does have a name, but it's not a file name. */ if (fputs("file ", fd) < 0 || ses_fname(fd, wp->w_buffer, flagp) == FAIL) return FAIL; } #endif do_cursor = FALSE; } } /* * Local mappings and abbreviations. */ if ((*flagp & (SSOP_OPTIONS | SSOP_LOCALOPTIONS)) && makemap(fd, wp->w_buffer) == FAIL) return FAIL; /* * Local options. Need to go to the window temporarily. * Store only local values when using ":mkview" and when ":mksession" is * used and 'sessionoptions' doesn't include "options". * Some folding options are always stored when "folds" is included, * otherwise the folds would not be restored correctly. */ save_curwin = curwin; curwin = wp; curbuf = curwin->w_buffer; if (*flagp & (SSOP_OPTIONS | SSOP_LOCALOPTIONS)) f = makeset(fd, OPT_LOCAL, flagp == &vop_flags || !(*flagp & SSOP_OPTIONS)); #ifdef FEAT_FOLDING else if (*flagp & SSOP_FOLDS) f = makefoldset(fd); #endif else f = OK; curwin = save_curwin; curbuf = curwin->w_buffer; if (f == FAIL) return FAIL; #ifdef FEAT_FOLDING /* * Save Folds when 'buftype' is empty and for help files. */ if ((*flagp & SSOP_FOLDS) && wp->w_buffer->b_ffname != NULL # ifdef FEAT_QUICKFIX && (*wp->w_buffer->b_p_bt == NUL || wp->w_buffer->b_help) # endif ) { if (put_folds(fd, wp) == FAIL) return FAIL; } #endif /* * Set the cursor after creating folds, since that moves the cursor. */ if (do_cursor) { /* Restore the cursor line in the file and relatively in the * window. Don't use "G", it changes the jumplist. */ if (fprintf(fd, "let s:l = %ld - ((%ld * winheight(0) + %ld) / %ld)", (long)wp->w_cursor.lnum, (long)(wp->w_cursor.lnum - wp->w_topline), (long)wp->w_height / 2, (long)wp->w_height) < 0 || put_eol(fd) == FAIL || put_line(fd, "if s:l < 1 | let s:l = 1 | endif") == FAIL || put_line(fd, "exe s:l") == FAIL || put_line(fd, "normal! zt") == FAIL || fprintf(fd, "%ld", (long)wp->w_cursor.lnum) < 0 || put_eol(fd) == FAIL) return FAIL; /* Restore the cursor column and left offset when not wrapping. */ if (wp->w_cursor.col == 0) { if (put_line(fd, "normal! 0") == FAIL) return FAIL; } else { if (!wp->w_p_wrap && wp->w_leftcol > 0 && wp->w_width > 0) { if (fprintf(fd, "let s:c = %ld - ((%ld * winwidth(0) + %ld) / %ld)", (long)wp->w_cursor.col, (long)(wp->w_cursor.col - wp->w_leftcol), (long)wp->w_width / 2, (long)wp->w_width) < 0 || put_eol(fd) == FAIL || put_line(fd, "if s:c > 0") == FAIL || fprintf(fd, " exe 'normal! 0' . s:c . 'lzs' . (%ld - s:c) . 'l'", (long)wp->w_cursor.col) < 0 || put_eol(fd) == FAIL || put_line(fd, "else") == FAIL || fprintf(fd, " normal! 0%dl", wp->w_cursor.col) < 0 || put_eol(fd) == FAIL || put_line(fd, "endif") == FAIL) return FAIL; } else { if (fprintf(fd, "normal! 0%dl", wp->w_cursor.col) < 0 || put_eol(fd) == FAIL) return FAIL; } } } /* * Local directory. */ if (wp->w_localdir != NULL) { if (fputs("lcd ", fd) < 0 || ses_put_fname(fd, wp->w_localdir, flagp) == FAIL || put_eol(fd) == FAIL) return FAIL; did_lcd = TRUE; } return OK; } /* * Write an argument list to the session file. * Returns FAIL if writing fails. */ static int ses_arglist(fd, cmd, gap, fullname, flagp) FILE *fd; char *cmd; garray_T *gap; int fullname; /* TRUE: use full path name */ unsigned *flagp; { int i; char_u *buf = NULL; char_u *s; if (gap->ga_len == 0) return put_line(fd, "silent! argdel *"); if (fputs(cmd, fd) < 0) return FAIL; for (i = 0; i < gap->ga_len; ++i) { /* NULL file names are skipped (only happens when out of memory). */ s = alist_name(&((aentry_T *)gap->ga_data)[i]); if (s != NULL) { if (fullname) { buf = alloc(MAXPATHL); if (buf != NULL) { (void)vim_FullName(s, buf, MAXPATHL, FALSE); s = buf; } } if (fputs(" ", fd) < 0 || ses_put_fname(fd, s, flagp) == FAIL) { vim_free(buf); return FAIL; } vim_free(buf); } } return put_eol(fd); } /* * Write a buffer name to the session file. * Also ends the line. * Returns FAIL if writing fails. */ static int ses_fname(fd, buf, flagp) FILE *fd; buf_T *buf; unsigned *flagp; { char_u *name; /* Use the short file name if the current directory is known at the time * the session file will be sourced. * Don't do this for ":mkview", we don't know the current directory. * Don't do this after ":lcd", we don't keep track of what the current * directory is. */ if (buf->b_sfname != NULL && flagp == &ssop_flags && (ssop_flags & (SSOP_CURDIR | SSOP_SESDIR)) #ifdef FEAT_AUTOCHDIR && !p_acd #endif && !did_lcd) name = buf->b_sfname; else name = buf->b_ffname; if (ses_put_fname(fd, name, flagp) == FAIL || put_eol(fd) == FAIL) return FAIL; return OK; } /* * Write a file name to the session file. * Takes care of the "slash" option in 'sessionoptions' and escapes special * characters. * Returns FAIL if writing fails or out of memory. */ static int ses_put_fname(fd, name, flagp) FILE *fd; char_u *name; unsigned *flagp; { char_u *sname; char_u *p; int retval = OK; sname = home_replace_save(NULL, name); if (sname == NULL) return FAIL; if (*flagp & SSOP_SLASH) { /* change all backslashes to forward slashes */ for (p = sname; *p != NUL; mb_ptr_adv(p)) if (*p == '\\') *p = '/'; } /* escapse special characters */ p = vim_strsave_fnameescape(sname, FALSE); vim_free(sname); if (p == NULL) return FAIL; /* write the result */ if (fputs((char *)p, fd) < 0) retval = FAIL; vim_free(p); return retval; } /* * ":loadview [nr]" */ static void ex_loadview(eap) exarg_T *eap; { char_u *fname; fname = get_view_file(*eap->arg); if (fname != NULL) { do_source(fname, FALSE, DOSO_NONE); vim_free(fname); } } /* * Get the name of the view file for the current buffer. */ static char_u * get_view_file(c) int c; { int len = 0; char_u *p, *s; char_u *retval; char_u *sname; if (curbuf->b_ffname == NULL) { EMSG(_(e_noname)); return NULL; } sname = home_replace_save(NULL, curbuf->b_ffname); if (sname == NULL) return NULL; /* * We want a file name without separators, because we're not going to make * a directory. * "normal" path separator -> "=+" * "=" -> "==" * ":" path separator -> "=-" */ for (p = sname; *p; ++p) if (*p == '=' || vim_ispathsep(*p)) ++len; retval = alloc((unsigned)(STRLEN(sname) + len + STRLEN(p_vdir) + 9)); if (retval != NULL) { STRCPY(retval, p_vdir); add_pathsep(retval); s = retval + STRLEN(retval); for (p = sname; *p; ++p) { if (*p == '=') { *s++ = '='; *s++ = '='; } else if (vim_ispathsep(*p)) { *s++ = '='; #if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA) || defined(VMS) if (*p == ':') *s++ = '-'; else #endif *s++ = '+'; } else *s++ = *p; } *s++ = '='; *s++ = c; STRCPY(s, ".vim"); } vim_free(sname); return retval; } #endif /* FEAT_SESSION */ /* * Write end-of-line character(s) for ":mkexrc", ":mkvimrc" and ":mksession". * Return FAIL for a write error. */ int put_eol(fd) FILE *fd; { if ( #ifdef USE_CRNL ( # ifdef MKSESSION_NL !mksession_nl && # endif (putc('\r', fd) < 0)) || #endif (putc('\n', fd) < 0)) return FAIL; return OK; } /* * Write a line to "fd". * Return FAIL for a write error. */ int put_line(fd, s) FILE *fd; char *s; { if (fputs(s, fd) < 0 || put_eol(fd) == FAIL) return FAIL; return OK; } #ifdef FEAT_VIMINFO /* * ":rviminfo" and ":wviminfo". */ static void ex_viminfo(eap) exarg_T *eap; { char_u *save_viminfo; save_viminfo = p_viminfo; if (*p_viminfo == NUL) p_viminfo = (char_u *)"'100"; if (eap->cmdidx == CMD_rviminfo) { if (read_viminfo(eap->arg, VIF_WANT_INFO | VIF_WANT_MARKS | (eap->forceit ? VIF_FORCEIT : 0)) == FAIL) EMSG(_("E195: Cannot open viminfo file for reading")); } else write_viminfo(eap->arg, eap->forceit); p_viminfo = save_viminfo; } #endif #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) || defined(PROTO) /* * Make a dialog message in "buff[DIALOG_MSG_SIZE]". * "format" must contain "%s". */ void dialog_msg(buff, format, fname) char_u *buff; char *format; char_u *fname; { if (fname == NULL) fname = (char_u *)_("Untitled"); vim_snprintf((char *)buff, DIALOG_MSG_SIZE, format, fname); } #endif /* * ":behave {mswin,xterm}" */ static void ex_behave(eap) exarg_T *eap; { if (STRCMP(eap->arg, "mswin") == 0) { set_option_value((char_u *)"selection", 0L, (char_u *)"exclusive", 0); set_option_value((char_u *)"selectmode", 0L, (char_u *)"mouse,key", 0); set_option_value((char_u *)"mousemodel", 0L, (char_u *)"popup", 0); set_option_value((char_u *)"keymodel", 0L, (char_u *)"startsel,stopsel", 0); } else if (STRCMP(eap->arg, "xterm") == 0) { set_option_value((char_u *)"selection", 0L, (char_u *)"inclusive", 0); set_option_value((char_u *)"selectmode", 0L, (char_u *)"", 0); set_option_value((char_u *)"mousemodel", 0L, (char_u *)"extend", 0); set_option_value((char_u *)"keymodel", 0L, (char_u *)"", 0); } else EMSG2(_(e_invarg2), eap->arg); } #if defined(FEAT_CMDL_COMPL) || defined(PROTO) /* * Function given to ExpandGeneric() to obtain the possible arguments of the * ":behave {mswin,xterm}" command. */ char_u * get_behave_arg(xp, idx) expand_T *xp UNUSED; int idx; { if (idx == 0) return (char_u *)"mswin"; if (idx == 1) return (char_u *)"xterm"; return NULL; } #endif #ifdef FEAT_AUTOCMD static int filetype_detect = FALSE; static int filetype_plugin = FALSE; static int filetype_indent = FALSE; /* * ":filetype [plugin] [indent] {on,off,detect}" * on: Load the filetype.vim file to install autocommands for file types. * off: Load the ftoff.vim file to remove all autocommands for file types. * plugin on: load filetype.vim and ftplugin.vim * plugin off: load ftplugof.vim * indent on: load filetype.vim and indent.vim * indent off: load indoff.vim */ static void ex_filetype(eap) exarg_T *eap; { char_u *arg = eap->arg; int plugin = FALSE; int indent = FALSE; if (*eap->arg == NUL) { /* Print current status. */ smsg((char_u *)"filetype detection:%s plugin:%s indent:%s", filetype_detect ? "ON" : "OFF", filetype_plugin ? (filetype_detect ? "ON" : "(on)") : "OFF", filetype_indent ? (filetype_detect ? "ON" : "(on)") : "OFF"); return; } /* Accept "plugin" and "indent" in any order. */ for (;;) { if (STRNCMP(arg, "plugin", 6) == 0) { plugin = TRUE; arg = skipwhite(arg + 6); continue; } if (STRNCMP(arg, "indent", 6) == 0) { indent = TRUE; arg = skipwhite(arg + 6); continue; } break; } if (STRCMP(arg, "on") == 0 || STRCMP(arg, "detect") == 0) { if (*arg == 'o' || !filetype_detect) { source_runtime((char_u *)FILETYPE_FILE, TRUE); filetype_detect = TRUE; if (plugin) { source_runtime((char_u *)FTPLUGIN_FILE, TRUE); filetype_plugin = TRUE; } if (indent) { source_runtime((char_u *)INDENT_FILE, TRUE); filetype_indent = TRUE; } } if (*arg == 'd') { (void)do_doautocmd((char_u *)"filetypedetect BufRead", TRUE); do_modelines(0); } } else if (STRCMP(arg, "off") == 0) { if (plugin || indent) { if (plugin) { source_runtime((char_u *)FTPLUGOF_FILE, TRUE); filetype_plugin = FALSE; } if (indent) { source_runtime((char_u *)INDOFF_FILE, TRUE); filetype_indent = FALSE; } } else { source_runtime((char_u *)FTOFF_FILE, TRUE); filetype_detect = FALSE; } } else EMSG2(_(e_invarg2), arg); } /* * ":setfiletype {name}" */ static void ex_setfiletype(eap) exarg_T *eap; { if (!did_filetype) set_option_value((char_u *)"filetype", 0L, eap->arg, OPT_LOCAL); } #endif static void ex_digraphs(eap) exarg_T *eap UNUSED; { #ifdef FEAT_DIGRAPHS if (*eap->arg != NUL) putdigraph(eap->arg); else listdigraphs(); #else EMSG(_("E196: No digraphs in this version")); #endif } static void ex_set(eap) exarg_T *eap; { int flags = 0; if (eap->cmdidx == CMD_setlocal) flags = OPT_LOCAL; else if (eap->cmdidx == CMD_setglobal) flags = OPT_GLOBAL; #if defined(FEAT_EVAL) && defined(FEAT_AUTOCMD) && defined(FEAT_BROWSE) if (cmdmod.browse && flags == 0) ex_options(eap); else #endif (void)do_set(eap->arg, flags); } #ifdef FEAT_SEARCH_EXTRA /* * ":nohlsearch" */ static void ex_nohlsearch(eap) exarg_T *eap UNUSED; { no_hlsearch = TRUE; redraw_all_later(SOME_VALID); } /* * ":[N]match {group} {pattern}" * Sets nextcmd to the start of the next command, if any. Also called when * skipping commands to find the next command. */ static void ex_match(eap) exarg_T *eap; { char_u *p; char_u *g = NULL; char_u *end; int c; int id; if (eap->line2 <= 3) id = eap->line2; else { EMSG(e_invcmd); return; } /* First clear any old pattern. */ if (!eap->skip) match_delete(curwin, id, FALSE); if (ends_excmd(*eap->arg)) end = eap->arg; else if ((STRNICMP(eap->arg, "none", 4) == 0 && (vim_iswhite(eap->arg[4]) || ends_excmd(eap->arg[4])))) end = eap->arg + 4; else { p = skiptowhite(eap->arg); if (!eap->skip) g = vim_strnsave(eap->arg, (int)(p - eap->arg)); p = skipwhite(p); if (*p == NUL) { /* There must be two arguments. */ EMSG2(_(e_invarg2), eap->arg); return; } end = skip_regexp(p + 1, *p, TRUE, NULL); if (!eap->skip) { if (*end != NUL && !ends_excmd(*skipwhite(end + 1))) { eap->errmsg = e_trailing; return; } if (*end != *p) { EMSG2(_(e_invarg2), p); return; } c = *end; *end = NUL; match_add(curwin, g, p + 1, 10, id); vim_free(g); *end = c; } } eap->nextcmd = find_nextcmd(end); } #endif #ifdef FEAT_CRYPT /* * ":X": Get crypt key */ static void ex_X(eap) exarg_T *eap UNUSED; { if (get_crypt_method(curbuf) == 0 || blowfish_self_test() == OK) (void)get_crypt_key(TRUE, TRUE); } #endif #ifdef FEAT_FOLDING static void ex_fold(eap) exarg_T *eap; { if (foldManualAllowed(TRUE)) foldCreate(eap->line1, eap->line2); } static void ex_foldopen(eap) exarg_T *eap; { opFoldRange(eap->line1, eap->line2, eap->cmdidx == CMD_foldopen, eap->forceit, FALSE); } static void ex_folddo(eap) exarg_T *eap; { linenr_T lnum; /* First set the marks for all lines closed/open. */ for (lnum = eap->line1; lnum <= eap->line2; ++lnum) if (hasFolding(lnum, NULL, NULL) == (eap->cmdidx == CMD_folddoclosed)) ml_setmarked(lnum); /* Execute the command on the marked lines. */ global_exe(eap->arg); ml_clearmarked(); /* clear rest of the marks */ } #endif
zyz2011-vim
src/ex_docmd.c
C
gpl2
262,782
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * getchar.c * * functions related with getting a character from the user/mapping/redo/... * * manipulations with redo buffer and stuff buffer * mappings and abbreviations */ #include "vim.h" /* * These buffers are used for storing: * - stuffed characters: A command that is translated into another command. * - redo characters: will redo the last change. * - recorded characters: for the "q" command. * * The bytes are stored like in the typeahead buffer: * - K_SPECIAL introduces a special key (two more bytes follow). A literal * K_SPECIAL is stored as K_SPECIAL KS_SPECIAL KE_FILLER. * - CSI introduces a GUI termcap code (also when gui.in_use is FALSE, * otherwise switching the GUI on would make mappings invalid). * A literal CSI is stored as CSI KS_EXTRA KE_CSI. * These translations are also done on multi-byte characters! * * Escaping CSI bytes is done by the system-specific input functions, called * by ui_inchar(). * Escaping K_SPECIAL is done by inchar(). * Un-escaping is done by vgetc(). */ #define MINIMAL_SIZE 20 /* minimal size for b_str */ static struct buffheader redobuff = {{NULL, {NUL}}, NULL, 0, 0}; static struct buffheader old_redobuff = {{NULL, {NUL}}, NULL, 0, 0}; #if defined(FEAT_AUTOCMD) || defined(FEAT_EVAL) || defined(PROTO) static struct buffheader save_redobuff = {{NULL, {NUL}}, NULL, 0, 0}; static struct buffheader save_old_redobuff = {{NULL, {NUL}}, NULL, 0, 0}; #endif static struct buffheader recordbuff = {{NULL, {NUL}}, NULL, 0, 0}; static int typeahead_char = 0; /* typeahead char that's not flushed */ /* * when block_redo is TRUE redo buffer will not be changed * used by edit() to repeat insertions and 'V' command for redoing */ static int block_redo = FALSE; /* * Make a hash value for a mapping. * "mode" is the lower 4 bits of the State for the mapping. * "c1" is the first character of the "lhs". * Returns a value between 0 and 255, index in maphash. * Put Normal/Visual mode mappings mostly separately from Insert/Cmdline mode. */ #define MAP_HASH(mode, c1) (((mode) & (NORMAL + VISUAL + SELECTMODE + OP_PENDING)) ? (c1) : ((c1) ^ 0x80)) /* * Each mapping is put in one of the 256 hash lists, to speed up finding it. */ static mapblock_T *(maphash[256]); static int maphash_valid = FALSE; /* * List used for abbreviations. */ static mapblock_T *first_abbr = NULL; /* first entry in abbrlist */ static int KeyNoremap = 0; /* remapping flags */ /* * variables used by vgetorpeek() and flush_buffers() * * typebuf.tb_buf[] contains all characters that are not consumed yet. * typebuf.tb_buf[typebuf.tb_off] is the first valid character. * typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len - 1] is the last valid char. * typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len] must be NUL. * The head of the buffer may contain the result of mappings, abbreviations * and @a commands. The length of this part is typebuf.tb_maplen. * typebuf.tb_silent is the part where <silent> applies. * After the head are characters that come from the terminal. * typebuf.tb_no_abbr_cnt is the number of characters in typebuf.tb_buf that * should not be considered for abbreviations. * Some parts of typebuf.tb_buf may not be mapped. These parts are remembered * in typebuf.tb_noremap[], which is the same length as typebuf.tb_buf and * contains RM_NONE for the characters that are not to be remapped. * typebuf.tb_noremap[typebuf.tb_off] is the first valid flag. * (typebuf has been put in globals.h, because check_termcode() needs it). */ #define RM_YES 0 /* tb_noremap: remap */ #define RM_NONE 1 /* tb_noremap: don't remap */ #define RM_SCRIPT 2 /* tb_noremap: remap local script mappings */ #define RM_ABBR 4 /* tb_noremap: don't remap, do abbrev. */ /* typebuf.tb_buf has three parts: room in front (for result of mappings), the * middle for typeahead and room for new characters (which needs to be 3 * * MAXMAPLEN) for the Amiga). */ #define TYPELEN_INIT (5 * (MAXMAPLEN + 3)) static char_u typebuf_init[TYPELEN_INIT]; /* initial typebuf.tb_buf */ static char_u noremapbuf_init[TYPELEN_INIT]; /* initial typebuf.tb_noremap */ static int last_recorded_len = 0; /* number of last recorded chars */ static char_u *get_buffcont __ARGS((struct buffheader *, int)); static void add_buff __ARGS((struct buffheader *, char_u *, long n)); static void add_num_buff __ARGS((struct buffheader *, long)); static void add_char_buff __ARGS((struct buffheader *, int)); static int read_stuff __ARGS((int advance)); static void start_stuff __ARGS((void)); static int read_redo __ARGS((int, int)); static void copy_redo __ARGS((int)); static void init_typebuf __ARGS((void)); static void gotchars __ARGS((char_u *, int)); static void may_sync_undo __ARGS((void)); static void closescript __ARGS((void)); static int vgetorpeek __ARGS((int)); static void map_free __ARGS((mapblock_T **)); static void validate_maphash __ARGS((void)); static void showmap __ARGS((mapblock_T *mp, int local)); #ifdef FEAT_EVAL static char_u *eval_map_expr __ARGS((char_u *str, int c)); #endif /* * Free and clear a buffer. */ void free_buff(buf) struct buffheader *buf; { struct buffblock *p, *np; for (p = buf->bh_first.b_next; p != NULL; p = np) { np = p->b_next; vim_free(p); } buf->bh_first.b_next = NULL; } /* * Return the contents of a buffer as a single string. * K_SPECIAL and CSI in the returned string are escaped. */ static char_u * get_buffcont(buffer, dozero) struct buffheader *buffer; int dozero; /* count == zero is not an error */ { long_u count = 0; char_u *p = NULL; char_u *p2; char_u *str; struct buffblock *bp; /* compute the total length of the string */ for (bp = buffer->bh_first.b_next; bp != NULL; bp = bp->b_next) count += (long_u)STRLEN(bp->b_str); if ((count || dozero) && (p = lalloc(count + 1, TRUE)) != NULL) { p2 = p; for (bp = buffer->bh_first.b_next; bp != NULL; bp = bp->b_next) for (str = bp->b_str; *str; ) *p2++ = *str++; *p2 = NUL; } return (p); } /* * Return the contents of the record buffer as a single string * and clear the record buffer. * K_SPECIAL and CSI in the returned string are escaped. */ char_u * get_recorded() { char_u *p; size_t len; p = get_buffcont(&recordbuff, TRUE); free_buff(&recordbuff); /* * Remove the characters that were added the last time, these must be the * (possibly mapped) characters that stopped the recording. */ len = STRLEN(p); if ((int)len >= last_recorded_len) { len -= last_recorded_len; p[len] = NUL; } /* * When stopping recording from Insert mode with CTRL-O q, also remove the * CTRL-O. */ if (len > 0 && restart_edit != 0 && p[len - 1] == Ctrl_O) p[len - 1] = NUL; return (p); } /* * Return the contents of the redo buffer as a single string. * K_SPECIAL and CSI in the returned string are escaped. */ char_u * get_inserted() { return get_buffcont(&redobuff, FALSE); } /* * Add string "s" after the current block of buffer "buf". * K_SPECIAL and CSI should have been escaped already. */ static void add_buff(buf, s, slen) struct buffheader *buf; char_u *s; long slen; /* length of "s" or -1 */ { struct buffblock *p; long_u len; if (slen < 0) slen = (long)STRLEN(s); if (slen == 0) /* don't add empty strings */ return; if (buf->bh_first.b_next == NULL) /* first add to list */ { buf->bh_space = 0; buf->bh_curr = &(buf->bh_first); } else if (buf->bh_curr == NULL) /* buffer has already been read */ { EMSG(_("E222: Add to read buffer")); return; } else if (buf->bh_index != 0) mch_memmove(buf->bh_first.b_next->b_str, buf->bh_first.b_next->b_str + buf->bh_index, STRLEN(buf->bh_first.b_next->b_str + buf->bh_index) + 1); buf->bh_index = 0; if (buf->bh_space >= (int)slen) { len = (long_u)STRLEN(buf->bh_curr->b_str); vim_strncpy(buf->bh_curr->b_str + len, s, (size_t)slen); buf->bh_space -= slen; } else { if (slen < MINIMAL_SIZE) len = MINIMAL_SIZE; else len = slen; p = (struct buffblock *)lalloc((long_u)(sizeof(struct buffblock) + len), TRUE); if (p == NULL) return; /* no space, just forget it */ buf->bh_space = (int)(len - slen); vim_strncpy(p->b_str, s, (size_t)slen); p->b_next = buf->bh_curr->b_next; buf->bh_curr->b_next = p; buf->bh_curr = p; } return; } /* * Add number "n" to buffer "buf". */ static void add_num_buff(buf, n) struct buffheader *buf; long n; { char_u number[32]; sprintf((char *)number, "%ld", n); add_buff(buf, number, -1L); } /* * Add character 'c' to buffer "buf". * Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters. */ static void add_char_buff(buf, c) struct buffheader *buf; int c; { #ifdef FEAT_MBYTE char_u bytes[MB_MAXBYTES + 1]; int len; int i; #endif char_u temp[4]; #ifdef FEAT_MBYTE if (IS_SPECIAL(c)) len = 1; else len = (*mb_char2bytes)(c, bytes); for (i = 0; i < len; ++i) { if (!IS_SPECIAL(c)) c = bytes[i]; #endif if (IS_SPECIAL(c) || c == K_SPECIAL || c == NUL) { /* translate special key code into three byte sequence */ temp[0] = K_SPECIAL; temp[1] = K_SECOND(c); temp[2] = K_THIRD(c); temp[3] = NUL; } #ifdef FEAT_GUI else if (c == CSI) { /* Translate a CSI to a CSI - KS_EXTRA - KE_CSI sequence */ temp[0] = CSI; temp[1] = KS_EXTRA; temp[2] = (int)KE_CSI; temp[3] = NUL; } #endif else { temp[0] = c; temp[1] = NUL; } add_buff(buf, temp, -1L); #ifdef FEAT_MBYTE } #endif } /* * Get one byte from the stuff buffer. * If advance == TRUE go to the next char. * No translation is done K_SPECIAL and CSI are escaped. */ static int read_stuff(advance) int advance; { char_u c; struct buffblock *curr; if (stuffbuff.bh_first.b_next == NULL) /* buffer is empty */ return NUL; curr = stuffbuff.bh_first.b_next; c = curr->b_str[stuffbuff.bh_index]; if (advance) { if (curr->b_str[++stuffbuff.bh_index] == NUL) { stuffbuff.bh_first.b_next = curr->b_next; vim_free(curr); stuffbuff.bh_index = 0; } } return c; } /* * Prepare the stuff buffer for reading (if it contains something). */ static void start_stuff() { if (stuffbuff.bh_first.b_next != NULL) { stuffbuff.bh_curr = &(stuffbuff.bh_first); stuffbuff.bh_space = 0; } } /* * Return TRUE if the stuff buffer is empty. */ int stuff_empty() { return (stuffbuff.bh_first.b_next == NULL); } /* * Set a typeahead character that won't be flushed. */ void typeahead_noflush(c) int c; { typeahead_char = c; } /* * Remove the contents of the stuff buffer and the mapped characters in the * typeahead buffer (used in case of an error). If "flush_typeahead" is true, * flush all typeahead characters (used when interrupted by a CTRL-C). */ void flush_buffers(flush_typeahead) int flush_typeahead; { init_typebuf(); start_stuff(); while (read_stuff(TRUE) != NUL) ; if (flush_typeahead) /* remove all typeahead */ { /* * We have to get all characters, because we may delete the first part * of an escape sequence. * In an xterm we get one char at a time and we have to get them all. */ while (inchar(typebuf.tb_buf, typebuf.tb_buflen - 1, 10L, typebuf.tb_change_cnt) != 0) ; typebuf.tb_off = MAXMAPLEN; typebuf.tb_len = 0; } else /* remove mapped characters only */ { typebuf.tb_off += typebuf.tb_maplen; typebuf.tb_len -= typebuf.tb_maplen; } typebuf.tb_maplen = 0; typebuf.tb_silent = 0; cmd_silent = FALSE; typebuf.tb_no_abbr_cnt = 0; } /* * The previous contents of the redo buffer is kept in old_redobuffer. * This is used for the CTRL-O <.> command in insert mode. */ void ResetRedobuff() { if (!block_redo) { free_buff(&old_redobuff); old_redobuff = redobuff; redobuff.bh_first.b_next = NULL; } } /* * Discard the contents of the redo buffer and restore the previous redo * buffer. */ void CancelRedo() { if (!block_redo) { free_buff(&redobuff); redobuff = old_redobuff; old_redobuff.bh_first.b_next = NULL; start_stuff(); while (read_stuff(TRUE) != NUL) ; } } #if defined(FEAT_AUTOCMD) || defined(FEAT_EVAL) || defined(PROTO) /* * Save redobuff and old_redobuff to save_redobuff and save_old_redobuff. * Used before executing autocommands and user functions. */ static int save_level = 0; void saveRedobuff() { char_u *s; if (save_level++ == 0) { save_redobuff = redobuff; redobuff.bh_first.b_next = NULL; save_old_redobuff = old_redobuff; old_redobuff.bh_first.b_next = NULL; /* Make a copy, so that ":normal ." in a function works. */ s = get_buffcont(&save_redobuff, FALSE); if (s != NULL) { add_buff(&redobuff, s, -1L); vim_free(s); } } } /* * Restore redobuff and old_redobuff from save_redobuff and save_old_redobuff. * Used after executing autocommands and user functions. */ void restoreRedobuff() { if (--save_level == 0) { free_buff(&redobuff); redobuff = save_redobuff; free_buff(&old_redobuff); old_redobuff = save_old_redobuff; } } #endif /* * Append "s" to the redo buffer. * K_SPECIAL and CSI should already have been escaped. */ void AppendToRedobuff(s) char_u *s; { if (!block_redo) add_buff(&redobuff, s, -1L); } /* * Append to Redo buffer literally, escaping special characters with CTRL-V. * K_SPECIAL and CSI are escaped as well. */ void AppendToRedobuffLit(str, len) char_u *str; int len; /* length of "str" or -1 for up to the NUL */ { char_u *s = str; int c; char_u *start; if (block_redo) return; while (len < 0 ? *s != NUL : s - str < len) { /* Put a string of normal characters in the redo buffer (that's * faster). */ start = s; while (*s >= ' ' #ifndef EBCDIC && *s < DEL /* EBCDIC: all chars above space are normal */ #endif && (len < 0 || s - str < len)) ++s; /* Don't put '0' or '^' as last character, just in case a CTRL-D is * typed next. */ if (*s == NUL && (s[-1] == '0' || s[-1] == '^')) --s; if (s > start) add_buff(&redobuff, start, (long)(s - start)); if (*s == NUL || (len >= 0 && s - str >= len)) break; /* Handle a special or multibyte character. */ #ifdef FEAT_MBYTE if (has_mbyte) /* Handle composing chars separately. */ c = mb_cptr2char_adv(&s); else #endif c = *s++; if (c < ' ' || c == DEL || (*s == NUL && (c == '0' || c == '^'))) add_char_buff(&redobuff, Ctrl_V); /* CTRL-V '0' must be inserted as CTRL-V 048 (EBCDIC: xf0) */ if (*s == NUL && c == '0') #ifdef EBCDIC add_buff(&redobuff, (char_u *)"xf0", 3L); #else add_buff(&redobuff, (char_u *)"048", 3L); #endif else add_char_buff(&redobuff, c); } } /* * Append a character to the redo buffer. * Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters. */ void AppendCharToRedobuff(c) int c; { if (!block_redo) add_char_buff(&redobuff, c); } /* * Append a number to the redo buffer. */ void AppendNumberToRedobuff(n) long n; { if (!block_redo) add_num_buff(&redobuff, n); } /* * Append string "s" to the stuff buffer. * CSI and K_SPECIAL must already have been escaped. */ void stuffReadbuff(s) char_u *s; { add_buff(&stuffbuff, s, -1L); } void stuffReadbuffLen(s, len) char_u *s; long len; { add_buff(&stuffbuff, s, len); } #if defined(FEAT_EVAL) || defined(PROTO) /* * Stuff "s" into the stuff buffer, leaving special key codes unmodified and * escaping other K_SPECIAL and CSI bytes. * Change CR, LF and ESC into a space. */ void stuffReadbuffSpec(s) char_u *s; { int c; while (*s != NUL) { if (*s == K_SPECIAL && s[1] != NUL && s[2] != NUL) { /* Insert special key literally. */ stuffReadbuffLen(s, 3L); s += 3; } else { #ifdef FEAT_MBYTE c = mb_ptr2char_adv(&s); #else c = *s++; #endif if (c == CAR || c == NL || c == ESC) c = ' '; stuffcharReadbuff(c); } } } #endif /* * Append a character to the stuff buffer. * Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters. */ void stuffcharReadbuff(c) int c; { add_char_buff(&stuffbuff, c); } /* * Append a number to the stuff buffer. */ void stuffnumReadbuff(n) long n; { add_num_buff(&stuffbuff, n); } /* * Read a character from the redo buffer. Translates K_SPECIAL, CSI and * multibyte characters. * The redo buffer is left as it is. * If init is TRUE, prepare for redo, return FAIL if nothing to redo, OK * otherwise. * If old is TRUE, use old_redobuff instead of redobuff. */ static int read_redo(init, old_redo) int init; int old_redo; { static struct buffblock *bp; static char_u *p; int c; #ifdef FEAT_MBYTE int n; char_u buf[MB_MAXBYTES + 1]; int i; #endif if (init) { if (old_redo) bp = old_redobuff.bh_first.b_next; else bp = redobuff.bh_first.b_next; if (bp == NULL) return FAIL; p = bp->b_str; return OK; } if ((c = *p) != NUL) { /* Reverse the conversion done by add_char_buff() */ #ifdef FEAT_MBYTE /* For a multi-byte character get all the bytes and return the * converted character. */ if (has_mbyte && (c != K_SPECIAL || p[1] == KS_SPECIAL)) n = MB_BYTE2LEN_CHECK(c); else n = 1; for (i = 0; ; ++i) #endif { if (c == K_SPECIAL) /* special key or escaped K_SPECIAL */ { c = TO_SPECIAL(p[1], p[2]); p += 2; } #ifdef FEAT_GUI if (c == CSI) /* escaped CSI */ p += 2; #endif if (*++p == NUL && bp->b_next != NULL) { bp = bp->b_next; p = bp->b_str; } #ifdef FEAT_MBYTE buf[i] = c; if (i == n - 1) /* last byte of a character */ { if (n != 1) c = (*mb_ptr2char)(buf); break; } c = *p; if (c == NUL) /* cannot happen? */ break; #endif } } return c; } /* * Copy the rest of the redo buffer into the stuff buffer (in a slow way). * If old_redo is TRUE, use old_redobuff instead of redobuff. * The escaped K_SPECIAL and CSI are copied without translation. */ static void copy_redo(old_redo) int old_redo; { int c; while ((c = read_redo(FALSE, old_redo)) != NUL) stuffcharReadbuff(c); } /* * Stuff the redo buffer into the stuffbuff. * Insert the redo count into the command. * If "old_redo" is TRUE, the last but one command is repeated * instead of the last command (inserting text). This is used for * CTRL-O <.> in insert mode * * return FAIL for failure, OK otherwise */ int start_redo(count, old_redo) long count; int old_redo; { int c; /* init the pointers; return if nothing to redo */ if (read_redo(TRUE, old_redo) == FAIL) return FAIL; c = read_redo(FALSE, old_redo); /* copy the buffer name, if present */ if (c == '"') { add_buff(&stuffbuff, (char_u *)"\"", 1L); c = read_redo(FALSE, old_redo); /* if a numbered buffer is used, increment the number */ if (c >= '1' && c < '9') ++c; add_char_buff(&stuffbuff, c); c = read_redo(FALSE, old_redo); } #ifdef FEAT_VISUAL if (c == 'v') /* redo Visual */ { VIsual = curwin->w_cursor; VIsual_active = TRUE; VIsual_select = FALSE; VIsual_reselect = TRUE; redo_VIsual_busy = TRUE; c = read_redo(FALSE, old_redo); } #endif /* try to enter the count (in place of a previous count) */ if (count) { while (VIM_ISDIGIT(c)) /* skip "old" count */ c = read_redo(FALSE, old_redo); add_num_buff(&stuffbuff, count); } /* copy from the redo buffer into the stuff buffer */ add_char_buff(&stuffbuff, c); copy_redo(old_redo); return OK; } /* * Repeat the last insert (R, o, O, a, A, i or I command) by stuffing * the redo buffer into the stuffbuff. * return FAIL for failure, OK otherwise */ int start_redo_ins() { int c; if (read_redo(TRUE, FALSE) == FAIL) return FAIL; start_stuff(); /* skip the count and the command character */ while ((c = read_redo(FALSE, FALSE)) != NUL) { if (vim_strchr((char_u *)"AaIiRrOo", c) != NULL) { if (c == 'O' || c == 'o') stuffReadbuff(NL_STR); break; } } /* copy the typed text from the redo buffer into the stuff buffer */ copy_redo(FALSE); block_redo = TRUE; return OK; } void stop_redo_ins() { block_redo = FALSE; } /* * Initialize typebuf.tb_buf to point to typebuf_init. * alloc() cannot be used here: In out-of-memory situations it would * be impossible to type anything. */ static void init_typebuf() { if (typebuf.tb_buf == NULL) { typebuf.tb_buf = typebuf_init; typebuf.tb_noremap = noremapbuf_init; typebuf.tb_buflen = TYPELEN_INIT; typebuf.tb_len = 0; typebuf.tb_off = 0; typebuf.tb_change_cnt = 1; } } /* * insert a string in position 'offset' in the typeahead buffer (for "@r" * and ":normal" command, vgetorpeek() and check_termcode()) * * If noremap is REMAP_YES, new string can be mapped again. * If noremap is REMAP_NONE, new string cannot be mapped again. * If noremap is REMAP_SKIP, fist char of new string cannot be mapped again, * but abbreviations are allowed. * If noremap is REMAP_SCRIPT, new string cannot be mapped again, except for * script-local mappings. * If noremap is > 0, that many characters of the new string cannot be mapped. * * If nottyped is TRUE, the string does not return KeyTyped (don't use when * offset is non-zero!). * * If silent is TRUE, cmd_silent is set when the characters are obtained. * * return FAIL for failure, OK otherwise */ int ins_typebuf(str, noremap, offset, nottyped, silent) char_u *str; int noremap; int offset; int nottyped; int silent; { char_u *s1, *s2; int newlen; int addlen; int i; int newoff; int val; int nrm; init_typebuf(); if (++typebuf.tb_change_cnt == 0) typebuf.tb_change_cnt = 1; addlen = (int)STRLEN(str); /* * Easy case: there is room in front of typebuf.tb_buf[typebuf.tb_off] */ if (offset == 0 && addlen <= typebuf.tb_off) { typebuf.tb_off -= addlen; mch_memmove(typebuf.tb_buf + typebuf.tb_off, str, (size_t)addlen); } /* * Need to allocate a new buffer. * In typebuf.tb_buf there must always be room for 3 * MAXMAPLEN + 4 * characters. We add some extra room to avoid having to allocate too * often. */ else { newoff = MAXMAPLEN + 4; newlen = typebuf.tb_len + addlen + newoff + 4 * (MAXMAPLEN + 4); if (newlen < 0) /* string is getting too long */ { EMSG(_(e_toocompl)); /* also calls flush_buffers */ setcursor(); return FAIL; } s1 = alloc(newlen); if (s1 == NULL) /* out of memory */ return FAIL; s2 = alloc(newlen); if (s2 == NULL) /* out of memory */ { vim_free(s1); return FAIL; } typebuf.tb_buflen = newlen; /* copy the old chars, before the insertion point */ mch_memmove(s1 + newoff, typebuf.tb_buf + typebuf.tb_off, (size_t)offset); /* copy the new chars */ mch_memmove(s1 + newoff + offset, str, (size_t)addlen); /* copy the old chars, after the insertion point, including the NUL at * the end */ mch_memmove(s1 + newoff + offset + addlen, typebuf.tb_buf + typebuf.tb_off + offset, (size_t)(typebuf.tb_len - offset + 1)); if (typebuf.tb_buf != typebuf_init) vim_free(typebuf.tb_buf); typebuf.tb_buf = s1; mch_memmove(s2 + newoff, typebuf.tb_noremap + typebuf.tb_off, (size_t)offset); mch_memmove(s2 + newoff + offset + addlen, typebuf.tb_noremap + typebuf.tb_off + offset, (size_t)(typebuf.tb_len - offset)); if (typebuf.tb_noremap != noremapbuf_init) vim_free(typebuf.tb_noremap); typebuf.tb_noremap = s2; typebuf.tb_off = newoff; } typebuf.tb_len += addlen; /* If noremap == REMAP_SCRIPT: do remap script-local mappings. */ if (noremap == REMAP_SCRIPT) val = RM_SCRIPT; else if (noremap == REMAP_SKIP) val = RM_ABBR; else val = RM_NONE; /* * Adjust typebuf.tb_noremap[] for the new characters: * If noremap == REMAP_NONE or REMAP_SCRIPT: new characters are * (sometimes) not remappable * If noremap == REMAP_YES: all the new characters are mappable * If noremap > 0: "noremap" characters are not remappable, the rest * mappable */ if (noremap == REMAP_SKIP) nrm = 1; else if (noremap < 0) nrm = addlen; else nrm = noremap; for (i = 0; i < addlen; ++i) typebuf.tb_noremap[typebuf.tb_off + i + offset] = (--nrm >= 0) ? val : RM_YES; /* tb_maplen and tb_silent only remember the length of mapped and/or * silent mappings at the start of the buffer, assuming that a mapped * sequence doesn't result in typed characters. */ if (nottyped || typebuf.tb_maplen > offset) typebuf.tb_maplen += addlen; if (silent || typebuf.tb_silent > offset) { typebuf.tb_silent += addlen; cmd_silent = TRUE; } if (typebuf.tb_no_abbr_cnt && offset == 0) /* and not used for abbrev.s */ typebuf.tb_no_abbr_cnt += addlen; return OK; } /* * Put character "c" back into the typeahead buffer. * Can be used for a character obtained by vgetc() that needs to be put back. * Uses cmd_silent, KeyTyped and KeyNoremap to restore the flags belonging to * the char. */ void ins_char_typebuf(c) int c; { #ifdef FEAT_MBYTE char_u buf[MB_MAXBYTES + 1]; #else char_u buf[4]; #endif if (IS_SPECIAL(c)) { buf[0] = K_SPECIAL; buf[1] = K_SECOND(c); buf[2] = K_THIRD(c); buf[3] = NUL; } else { #ifdef FEAT_MBYTE buf[(*mb_char2bytes)(c, buf)] = NUL; #else buf[0] = c; buf[1] = NUL; #endif } (void)ins_typebuf(buf, KeyNoremap, 0, !KeyTyped, cmd_silent); } /* * Return TRUE if the typeahead buffer was changed (while waiting for a * character to arrive). Happens when a message was received from a client or * from feedkeys(). * But check in a more generic way to avoid trouble: When "typebuf.tb_buf" * changed it was reallocated and the old pointer can no longer be used. * Or "typebuf.tb_off" may have been changed and we would overwrite characters * that was just added. */ int typebuf_changed(tb_change_cnt) int tb_change_cnt; /* old value of typebuf.tb_change_cnt */ { return (tb_change_cnt != 0 && (typebuf.tb_change_cnt != tb_change_cnt #if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL) || typebuf_was_filled #endif )); } /* * Return TRUE if there are no characters in the typeahead buffer that have * not been typed (result from a mapping or come from ":normal"). */ int typebuf_typed() { return typebuf.tb_maplen == 0; } #if defined(FEAT_VISUAL) || defined(PROTO) /* * Return the number of characters that are mapped (or not typed). */ int typebuf_maplen() { return typebuf.tb_maplen; } #endif /* * remove "len" characters from typebuf.tb_buf[typebuf.tb_off + offset] */ void del_typebuf(len, offset) int len; int offset; { int i; if (len == 0) return; /* nothing to do */ typebuf.tb_len -= len; /* * Easy case: Just increase typebuf.tb_off. */ if (offset == 0 && typebuf.tb_buflen - (typebuf.tb_off + len) >= 3 * MAXMAPLEN + 3) typebuf.tb_off += len; /* * Have to move the characters in typebuf.tb_buf[] and typebuf.tb_noremap[] */ else { i = typebuf.tb_off + offset; /* * Leave some extra room at the end to avoid reallocation. */ if (typebuf.tb_off > MAXMAPLEN) { mch_memmove(typebuf.tb_buf + MAXMAPLEN, typebuf.tb_buf + typebuf.tb_off, (size_t)offset); mch_memmove(typebuf.tb_noremap + MAXMAPLEN, typebuf.tb_noremap + typebuf.tb_off, (size_t)offset); typebuf.tb_off = MAXMAPLEN; } /* adjust typebuf.tb_buf (include the NUL at the end) */ mch_memmove(typebuf.tb_buf + typebuf.tb_off + offset, typebuf.tb_buf + i + len, (size_t)(typebuf.tb_len - offset + 1)); /* adjust typebuf.tb_noremap[] */ mch_memmove(typebuf.tb_noremap + typebuf.tb_off + offset, typebuf.tb_noremap + i + len, (size_t)(typebuf.tb_len - offset)); } if (typebuf.tb_maplen > offset) /* adjust tb_maplen */ { if (typebuf.tb_maplen < offset + len) typebuf.tb_maplen = offset; else typebuf.tb_maplen -= len; } if (typebuf.tb_silent > offset) /* adjust tb_silent */ { if (typebuf.tb_silent < offset + len) typebuf.tb_silent = offset; else typebuf.tb_silent -= len; } if (typebuf.tb_no_abbr_cnt > offset) /* adjust tb_no_abbr_cnt */ { if (typebuf.tb_no_abbr_cnt < offset + len) typebuf.tb_no_abbr_cnt = offset; else typebuf.tb_no_abbr_cnt -= len; } #if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL) /* Reset the flag that text received from a client or from feedkeys() * was inserted in the typeahead buffer. */ typebuf_was_filled = FALSE; #endif if (++typebuf.tb_change_cnt == 0) typebuf.tb_change_cnt = 1; } /* * Write typed characters to script file. * If recording is on put the character in the recordbuffer. */ static void gotchars(chars, len) char_u *chars; int len; { char_u *s = chars; int c; char_u buf[2]; int todo = len; /* remember how many chars were last recorded */ if (Recording) last_recorded_len += len; buf[1] = NUL; while (todo--) { /* Handle one byte at a time; no translation to be done. */ c = *s++; updatescript(c); if (Recording) { buf[0] = c; add_buff(&recordbuff, buf, 1L); } } may_sync_undo(); #ifdef FEAT_EVAL /* output "debug mode" message next time in debug mode */ debug_did_msg = FALSE; #endif /* Since characters have been typed, consider the following to be in * another mapping. Search string will be kept in history. */ ++maptick; } /* * Sync undo. Called when typed characters are obtained from the typeahead * buffer, or when a menu is used. * Do not sync: * - In Insert mode, unless cursor key has been used. * - While reading a script file. * - When no_u_sync is non-zero. */ static void may_sync_undo() { if ((!(State & (INSERT + CMDLINE)) || arrow_used) && scriptin[curscript] == NULL) u_sync(FALSE); } /* * Make "typebuf" empty and allocate new buffers. * Returns FAIL when out of memory. */ int alloc_typebuf() { typebuf.tb_buf = alloc(TYPELEN_INIT); typebuf.tb_noremap = alloc(TYPELEN_INIT); if (typebuf.tb_buf == NULL || typebuf.tb_noremap == NULL) { free_typebuf(); return FAIL; } typebuf.tb_buflen = TYPELEN_INIT; typebuf.tb_off = 0; typebuf.tb_len = 0; typebuf.tb_maplen = 0; typebuf.tb_silent = 0; typebuf.tb_no_abbr_cnt = 0; if (++typebuf.tb_change_cnt == 0) typebuf.tb_change_cnt = 1; return OK; } /* * Free the buffers of "typebuf". */ void free_typebuf() { if (typebuf.tb_buf == typebuf_init) EMSG2(_(e_intern2), "Free typebuf 1"); else vim_free(typebuf.tb_buf); if (typebuf.tb_noremap == noremapbuf_init) EMSG2(_(e_intern2), "Free typebuf 2"); else vim_free(typebuf.tb_noremap); } /* * When doing ":so! file", the current typeahead needs to be saved, and * restored when "file" has been read completely. */ static typebuf_T saved_typebuf[NSCRIPT]; int save_typebuf() { init_typebuf(); saved_typebuf[curscript] = typebuf; /* If out of memory: restore typebuf and close file. */ if (alloc_typebuf() == FAIL) { closescript(); return FAIL; } return OK; } static int old_char = -1; /* character put back by vungetc() */ static int old_mod_mask; /* mod_mask for ungotten character */ #if defined(FEAT_EVAL) || defined(FEAT_EX_EXTRA) || defined(PROTO) /* * Save all three kinds of typeahead, so that the user must type at a prompt. */ void save_typeahead(tp) tasave_T *tp; { tp->save_typebuf = typebuf; tp->typebuf_valid = (alloc_typebuf() == OK); if (!tp->typebuf_valid) typebuf = tp->save_typebuf; tp->old_char = old_char; tp->old_mod_mask = old_mod_mask; old_char = -1; tp->save_stuffbuff = stuffbuff; stuffbuff.bh_first.b_next = NULL; # ifdef USE_INPUT_BUF tp->save_inputbuf = get_input_buf(); # endif } /* * Restore the typeahead to what it was before calling save_typeahead(). * The allocated memory is freed, can only be called once! */ void restore_typeahead(tp) tasave_T *tp; { if (tp->typebuf_valid) { free_typebuf(); typebuf = tp->save_typebuf; } old_char = tp->old_char; old_mod_mask = tp->old_mod_mask; free_buff(&stuffbuff); stuffbuff = tp->save_stuffbuff; # ifdef USE_INPUT_BUF set_input_buf(tp->save_inputbuf); # endif } #endif /* * Open a new script file for the ":source!" command. */ void openscript(name, directly) char_u *name; int directly; /* when TRUE execute directly */ { if (curscript + 1 == NSCRIPT) { EMSG(_(e_nesting)); return; } #ifdef FEAT_EVAL if (ignore_script) /* Not reading from script, also don't open one. Warning message? */ return; #endif if (scriptin[curscript] != NULL) /* already reading script */ ++curscript; /* use NameBuff for expanded name */ expand_env(name, NameBuff, MAXPATHL); if ((scriptin[curscript] = mch_fopen((char *)NameBuff, READBIN)) == NULL) { EMSG2(_(e_notopen), name); if (curscript) --curscript; return; } if (save_typebuf() == FAIL) return; /* * Execute the commands from the file right now when using ":source!" * after ":global" or ":argdo" or in a loop. Also when another command * follows. This means the display won't be updated. Don't do this * always, "make test" would fail. */ if (directly) { oparg_T oa; int oldcurscript; int save_State = State; int save_restart_edit = restart_edit; int save_insertmode = p_im; int save_finish_op = finish_op; int save_msg_scroll = msg_scroll; State = NORMAL; msg_scroll = FALSE; /* no msg scrolling in Normal mode */ restart_edit = 0; /* don't go to Insert mode */ p_im = FALSE; /* don't use 'insertmode' */ clear_oparg(&oa); finish_op = FALSE; oldcurscript = curscript; do { update_topline_cursor(); /* update cursor position and topline */ normal_cmd(&oa, FALSE); /* execute one command */ vpeekc(); /* check for end of file */ } while (scriptin[oldcurscript] != NULL); State = save_State; msg_scroll = save_msg_scroll; restart_edit = save_restart_edit; p_im = save_insertmode; finish_op = save_finish_op; } } /* * Close the currently active input script. */ static void closescript() { free_typebuf(); typebuf = saved_typebuf[curscript]; fclose(scriptin[curscript]); scriptin[curscript] = NULL; if (curscript > 0) --curscript; } #if defined(EXITFREE) || defined(PROTO) void close_all_scripts() { while (scriptin[0] != NULL) closescript(); } #endif #if defined(FEAT_INS_EXPAND) || defined(PROTO) /* * Return TRUE when reading keys from a script file. */ int using_script() { return scriptin[curscript] != NULL; } #endif /* * This function is called just before doing a blocking wait. Thus after * waiting 'updatetime' for a character to arrive. */ void before_blocking() { updatescript(0); #ifdef FEAT_EVAL if (may_garbage_collect) garbage_collect(); #endif } /* * updatescipt() is called when a character can be written into the script file * or when we have waited some time for a character (c == 0) * * All the changed memfiles are synced if c == 0 or when the number of typed * characters reaches 'updatecount' and 'updatecount' is non-zero. */ void updatescript(c) int c; { static int count = 0; if (c && scriptout) putc(c, scriptout); if (c == 0 || (p_uc > 0 && ++count >= p_uc)) { ml_sync_all(c == 0, TRUE); count = 0; } } /* * Get the next input character. * Can return a special key or a multi-byte character. * Can return NUL when called recursively, use safe_vgetc() if that's not * wanted. * This translates escaped K_SPECIAL and CSI bytes to a K_SPECIAL or CSI byte. * Collects the bytes of a multibyte character into the whole character. * Returns the modifiers in the global "mod_mask". */ int vgetc() { int c, c2; #ifdef FEAT_MBYTE int n; char_u buf[MB_MAXBYTES + 1]; int i; #endif #ifdef FEAT_EVAL /* Do garbage collection when garbagecollect() was called previously and * we are now at the toplevel. */ if (may_garbage_collect && want_garbage_collect) garbage_collect(); #endif /* * If a character was put back with vungetc, it was already processed. * Return it directly. */ if (old_char != -1) { c = old_char; old_char = -1; mod_mask = old_mod_mask; } else { mod_mask = 0x0; last_recorded_len = 0; for (;;) /* this is done twice if there are modifiers */ { if (mod_mask) /* no mapping after modifier has been read */ { ++no_mapping; ++allow_keys; } c = vgetorpeek(TRUE); if (mod_mask) { --no_mapping; --allow_keys; } /* Get two extra bytes for special keys */ if (c == K_SPECIAL #ifdef FEAT_GUI || c == CSI #endif ) { int save_allow_keys = allow_keys; ++no_mapping; allow_keys = 0; /* make sure BS is not found */ c2 = vgetorpeek(TRUE); /* no mapping for these chars */ c = vgetorpeek(TRUE); --no_mapping; allow_keys = save_allow_keys; if (c2 == KS_MODIFIER) { mod_mask = c; continue; } c = TO_SPECIAL(c2, c); #if defined(FEAT_GUI_W32) && defined(FEAT_MENU) && defined(FEAT_TEAROFF) /* Handle K_TEAROFF here, the caller of vgetc() doesn't need to * know that a menu was torn off */ if (c == K_TEAROFF) { char_u name[200]; int i; /* get menu path, it ends with a <CR> */ for (i = 0; (c = vgetorpeek(TRUE)) != '\r'; ) { name[i] = c; if (i < 199) ++i; } name[i] = NUL; gui_make_tearoff(name); continue; } #endif #if defined(FEAT_GUI) && defined(FEAT_GUI_GTK) && defined(FEAT_MENU) /* GTK: <F10> normally selects the menu, but it's passed until * here to allow mapping it. Intercept and invoke the GTK * behavior if it's not mapped. */ if (c == K_F10 && gui.menubar != NULL) { gtk_menu_shell_select_first(GTK_MENU_SHELL(gui.menubar), FALSE); continue; } #endif #ifdef FEAT_GUI /* Handle focus event here, so that the caller doesn't need to * know about it. Return K_IGNORE so that we loop once (needed if * 'lazyredraw' is set). */ if (c == K_FOCUSGAINED || c == K_FOCUSLOST) { ui_focus_change(c == K_FOCUSGAINED); c = K_IGNORE; } /* Translate K_CSI to CSI. The special key is only used to avoid * it being recognized as the start of a special key. */ if (c == K_CSI) c = CSI; #endif } #ifdef MSDOS /* * If K_NUL was typed, it is replaced by K_NUL, 3 in mch_inchar(). * Delete the 3 here. */ else if (c == K_NUL && vpeekc() == 3) (void)vgetorpeek(TRUE); #endif /* a keypad or special function key was not mapped, use it like * its ASCII equivalent */ switch (c) { case K_KPLUS: c = '+'; break; case K_KMINUS: c = '-'; break; case K_KDIVIDE: c = '/'; break; case K_KMULTIPLY: c = '*'; break; case K_KENTER: c = CAR; break; case K_KPOINT: #ifdef WIN32 /* Can be either '.' or a ',', * * depending on the type of keypad. */ c = MapVirtualKey(VK_DECIMAL, 2); break; #else c = '.'; break; #endif case K_K0: c = '0'; break; case K_K1: c = '1'; break; case K_K2: c = '2'; break; case K_K3: c = '3'; break; case K_K4: c = '4'; break; case K_K5: c = '5'; break; case K_K6: c = '6'; break; case K_K7: c = '7'; break; case K_K8: c = '8'; break; case K_K9: c = '9'; break; case K_XHOME: case K_ZHOME: if (mod_mask == MOD_MASK_SHIFT) { c = K_S_HOME; mod_mask = 0; } else if (mod_mask == MOD_MASK_CTRL) { c = K_C_HOME; mod_mask = 0; } else c = K_HOME; break; case K_XEND: case K_ZEND: if (mod_mask == MOD_MASK_SHIFT) { c = K_S_END; mod_mask = 0; } else if (mod_mask == MOD_MASK_CTRL) { c = K_C_END; mod_mask = 0; } else c = K_END; break; case K_XUP: c = K_UP; break; case K_XDOWN: c = K_DOWN; break; case K_XLEFT: c = K_LEFT; break; case K_XRIGHT: c = K_RIGHT; break; } #ifdef FEAT_MBYTE /* For a multi-byte character get all the bytes and return the * converted character. * Note: This will loop until enough bytes are received! */ if (has_mbyte && (n = MB_BYTE2LEN_CHECK(c)) > 1) { ++no_mapping; buf[0] = c; for (i = 1; i < n; ++i) { buf[i] = vgetorpeek(TRUE); if (buf[i] == K_SPECIAL #ifdef FEAT_GUI || buf[i] == CSI #endif ) { /* Must be a K_SPECIAL - KS_SPECIAL - KE_FILLER sequence, * which represents a K_SPECIAL (0x80), * or a CSI - KS_EXTRA - KE_CSI sequence, which represents * a CSI (0x9B), * of a K_SPECIAL - KS_EXTRA - KE_CSI, which is CSI too. */ c = vgetorpeek(TRUE); if (vgetorpeek(TRUE) == (int)KE_CSI && c == KS_EXTRA) buf[i] = CSI; } } --no_mapping; c = (*mb_ptr2char)(buf); } #endif break; } } #ifdef FEAT_EVAL /* * In the main loop "may_garbage_collect" can be set to do garbage * collection in the first next vgetc(). It's disabled after that to * avoid internally used Lists and Dicts to be freed. */ may_garbage_collect = FALSE; #endif return c; } /* * Like vgetc(), but never return a NUL when called recursively, get a key * directly from the user (ignoring typeahead). */ int safe_vgetc() { int c; c = vgetc(); if (c == NUL) c = get_keystroke(); return c; } /* * Like safe_vgetc(), but loop to handle K_IGNORE. * Also ignore scrollbar events. */ int plain_vgetc() { int c; do { c = safe_vgetc(); } while (c == K_IGNORE || c == K_VER_SCROLLBAR || c == K_HOR_SCROLLBAR); return c; } /* * Check if a character is available, such that vgetc() will not block. * If the next character is a special character or multi-byte, the returned * character is not valid!. */ int vpeekc() { if (old_char != -1) return old_char; return vgetorpeek(FALSE); } #if defined(FEAT_TERMRESPONSE) || defined(PROTO) /* * Like vpeekc(), but don't allow mapping. Do allow checking for terminal * codes. */ int vpeekc_nomap() { int c; ++no_mapping; ++allow_keys; c = vpeekc(); --no_mapping; --allow_keys; return c; } #endif #if defined(FEAT_INS_EXPAND) || defined(PROTO) /* * Check if any character is available, also half an escape sequence. * Trick: when no typeahead found, but there is something in the typeahead * buffer, it must be an ESC that is recognized as the start of a key code. */ int vpeekc_any() { int c; c = vpeekc(); if (c == NUL && typebuf.tb_len > 0) c = ESC; return c; } #endif /* * Call vpeekc() without causing anything to be mapped. * Return TRUE if a character is available, FALSE otherwise. */ int char_avail() { int retval; ++no_mapping; retval = vpeekc(); --no_mapping; return (retval != NUL); } void vungetc(c) /* unget one character (can only be done once!) */ int c; { old_char = c; old_mod_mask = mod_mask; } /* * get a character: * 1. from the stuffbuffer * This is used for abbreviated commands like "D" -> "d$". * Also used to redo a command for ".". * 2. from the typeahead buffer * Stores text obtained previously but not used yet. * Also stores the result of mappings. * Also used for the ":normal" command. * 3. from the user * This may do a blocking wait if "advance" is TRUE. * * if "advance" is TRUE (vgetc()): * really get the character. * KeyTyped is set to TRUE in the case the user typed the key. * KeyStuffed is TRUE if the character comes from the stuff buffer. * if "advance" is FALSE (vpeekc()): * just look whether there is a character available. * * When "no_mapping" is zero, checks for mappings in the current mode. * Only returns one byte (of a multi-byte character). * K_SPECIAL and CSI may be escaped, need to get two more bytes then. */ static int vgetorpeek(advance) int advance; { int c, c1; int keylen; char_u *s; mapblock_T *mp; #ifdef FEAT_LOCALMAP mapblock_T *mp2; #endif mapblock_T *mp_match; int mp_match_len = 0; int timedout = FALSE; /* waited for more than 1 second for mapping to complete */ int mapdepth = 0; /* check for recursive mapping */ int mode_deleted = FALSE; /* set when mode has been deleted */ int local_State; int mlen; int max_mlen; int i; #ifdef FEAT_CMDL_INFO int new_wcol, new_wrow; #endif #ifdef FEAT_GUI # ifdef FEAT_MENU int idx; # endif int shape_changed = FALSE; /* adjusted cursor shape */ #endif int n; #ifdef FEAT_LANGMAP int nolmaplen; #endif int old_wcol, old_wrow; int wait_tb_len; /* * This function doesn't work very well when called recursively. This may * happen though, because of: * 1. The call to add_to_showcmd(). char_avail() is then used to check if * there is a character available, which calls this function. In that * case we must return NUL, to indicate no character is available. * 2. A GUI callback function writes to the screen, causing a * wait_return(). * Using ":normal" can also do this, but it saves the typeahead buffer, * thus it should be OK. But don't get a key from the user then. */ if (vgetc_busy > 0 #ifdef FEAT_EX_EXTRA && ex_normal_busy == 0 #endif ) return NUL; local_State = get_real_state(); ++vgetc_busy; if (advance) KeyStuffed = FALSE; init_typebuf(); start_stuff(); if (advance && typebuf.tb_maplen == 0) Exec_reg = FALSE; do { /* * get a character: 1. from the stuffbuffer */ if (typeahead_char != 0) { c = typeahead_char; if (advance) typeahead_char = 0; } else c = read_stuff(advance); if (c != NUL && !got_int) { if (advance) { /* KeyTyped = FALSE; When the command that stuffed something * was typed, behave like the stuffed command was typed. * needed for CTRL-W CTRl-] to open a fold, for example. */ KeyStuffed = TRUE; } if (typebuf.tb_no_abbr_cnt == 0) typebuf.tb_no_abbr_cnt = 1; /* no abbreviations now */ } else { /* * Loop until we either find a matching mapped key, or we * are sure that it is not a mapped key. * If a mapped key sequence is found we go back to the start to * try re-mapping. */ for (;;) { /* * ui_breakcheck() is slow, don't use it too often when * inside a mapping. But call it each time for typed * characters. */ if (typebuf.tb_maplen) line_breakcheck(); else ui_breakcheck(); /* check for CTRL-C */ keylen = 0; if (got_int) { /* flush all input */ c = inchar(typebuf.tb_buf, typebuf.tb_buflen - 1, 0L, typebuf.tb_change_cnt); /* * If inchar() returns TRUE (script file was active) or we * are inside a mapping, get out of insert mode. * Otherwise we behave like having gotten a CTRL-C. * As a result typing CTRL-C in insert mode will * really insert a CTRL-C. */ if ((c || typebuf.tb_maplen) && (State & (INSERT + CMDLINE))) c = ESC; else c = Ctrl_C; flush_buffers(TRUE); /* flush all typeahead */ if (advance) { /* Also record this character, it might be needed to * get out of Insert mode. */ *typebuf.tb_buf = c; gotchars(typebuf.tb_buf, 1); } cmd_silent = FALSE; break; } else if (typebuf.tb_len > 0) { /* * Check for a mappable key sequence. * Walk through one maphash[] list until we find an * entry that matches. * * Don't look for mappings if: * - no_mapping set: mapping disabled (e.g. for CTRL-V) * - maphash_valid not set: no mappings present. * - typebuf.tb_buf[typebuf.tb_off] should not be remapped * - in insert or cmdline mode and 'paste' option set * - waiting for "hit return to continue" and CR or SPACE * typed * - waiting for a char with --more-- * - in Ctrl-X mode, and we get a valid char for that mode */ mp = NULL; max_mlen = 0; c1 = typebuf.tb_buf[typebuf.tb_off]; if (no_mapping == 0 && maphash_valid && (no_zero_mapping == 0 || c1 != '0') && (typebuf.tb_maplen == 0 || (p_remap && (typebuf.tb_noremap[typebuf.tb_off] & (RM_NONE|RM_ABBR)) == 0)) && !(p_paste && (State & (INSERT + CMDLINE))) && !(State == HITRETURN && (c1 == CAR || c1 == ' ')) && State != ASKMORE && State != CONFIRM #ifdef FEAT_INS_EXPAND && !((ctrl_x_mode != 0 && vim_is_ctrl_x_key(c1)) || ((compl_cont_status & CONT_LOCAL) && (c1 == Ctrl_N || c1 == Ctrl_P))) #endif ) { #ifdef FEAT_LANGMAP if (c1 == K_SPECIAL) nolmaplen = 2; else { LANGMAP_ADJUST(c1, TRUE); nolmaplen = 0; } #endif #ifdef FEAT_LOCALMAP /* First try buffer-local mappings. */ mp = curbuf->b_maphash[MAP_HASH(local_State, c1)]; mp2 = maphash[MAP_HASH(local_State, c1)]; if (mp == NULL) { mp = mp2; mp2 = NULL; } #else mp = maphash[MAP_HASH(local_State, c1)]; #endif /* * Loop until a partly matching mapping is found or * all (local) mappings have been checked. * The longest full match is remembered in "mp_match". * A full match is only accepted if there is no partly * match, so "aa" and "aaa" can both be mapped. */ mp_match = NULL; mp_match_len = 0; for ( ; mp != NULL; #ifdef FEAT_LOCALMAP mp->m_next == NULL ? (mp = mp2, mp2 = NULL) : #endif (mp = mp->m_next)) { /* * Only consider an entry if the first character * matches and it is for the current state. * Skip ":lmap" mappings if keys were mapped. */ if (mp->m_keys[0] == c1 && (mp->m_mode & local_State) && ((mp->m_mode & LANGMAP) == 0 || typebuf.tb_maplen == 0)) { #ifdef FEAT_LANGMAP int nomap = nolmaplen; int c2; #endif /* find the match length of this mapping */ for (mlen = 1; mlen < typebuf.tb_len; ++mlen) { #ifdef FEAT_LANGMAP c2 = typebuf.tb_buf[typebuf.tb_off + mlen]; if (nomap > 0) --nomap; else if (c2 == K_SPECIAL) nomap = 2; else LANGMAP_ADJUST(c2, TRUE); if (mp->m_keys[mlen] != c2) #else if (mp->m_keys[mlen] != typebuf.tb_buf[typebuf.tb_off + mlen]) #endif break; } #ifdef FEAT_MBYTE /* Don't allow mapping the first byte(s) of a * multi-byte char. Happens when mapping * <M-a> and then changing 'encoding'. */ if (has_mbyte && MB_BYTE2LEN(c1) > (*mb_ptr2len)(mp->m_keys)) mlen = 0; #endif /* * Check an entry whether it matches. * - Full match: mlen == keylen * - Partly match: mlen == typebuf.tb_len */ keylen = mp->m_keylen; if (mlen == keylen || (mlen == typebuf.tb_len && typebuf.tb_len < keylen)) { /* * If only script-local mappings are * allowed, check if the mapping starts * with K_SNR. */ s = typebuf.tb_noremap + typebuf.tb_off; if (*s == RM_SCRIPT && (mp->m_keys[0] != K_SPECIAL || mp->m_keys[1] != KS_EXTRA || mp->m_keys[2] != (int)KE_SNR)) continue; /* * If one of the typed keys cannot be * remapped, skip the entry. */ for (n = mlen; --n >= 0; ) if (*s++ & (RM_NONE|RM_ABBR)) break; if (n >= 0) continue; if (keylen > typebuf.tb_len) { if (!timedout) { /* break at a partly match */ keylen = KEYLEN_PART_MAP; break; } } else if (keylen > mp_match_len) { /* found a longer match */ mp_match = mp; mp_match_len = keylen; } } else /* No match; may have to check for * termcode at next character. */ if (max_mlen < mlen) max_mlen = mlen; } } /* If no partly match found, use the longest full * match. */ if (keylen != KEYLEN_PART_MAP) { mp = mp_match; keylen = mp_match_len; } } /* Check for match with 'pastetoggle' */ if (*p_pt != NUL && mp == NULL && (State & (INSERT|NORMAL))) { for (mlen = 0; mlen < typebuf.tb_len && p_pt[mlen]; ++mlen) if (p_pt[mlen] != typebuf.tb_buf[typebuf.tb_off + mlen]) break; if (p_pt[mlen] == NUL) /* match */ { /* write chars to script file(s) */ if (mlen > typebuf.tb_maplen) gotchars(typebuf.tb_buf + typebuf.tb_off + typebuf.tb_maplen, mlen - typebuf.tb_maplen); del_typebuf(mlen, 0); /* remove the chars */ set_option_value((char_u *)"paste", (long)!p_paste, NULL, 0); if (!(State & INSERT)) { msg_col = 0; msg_row = Rows - 1; msg_clr_eos(); /* clear ruler */ } showmode(); setcursor(); continue; } /* Need more chars for partly match. */ if (mlen == typebuf.tb_len) keylen = KEYLEN_PART_KEY; else if (max_mlen < mlen) /* no match, may have to check for termcode at * next character */ max_mlen = mlen + 1; } if ((mp == NULL || max_mlen >= mp_match_len) && keylen != KEYLEN_PART_MAP) { int save_keylen = keylen; /* * When no matching mapping found or found a * non-matching mapping that matches at least what the * matching mapping matched: * Check if we have a terminal code, when: * mapping is allowed, * keys have not been mapped, * and not an ESC sequence, not in insert mode or * p_ek is on, * and when not timed out, */ if ((no_mapping == 0 || allow_keys != 0) && (typebuf.tb_maplen == 0 || (p_remap && typebuf.tb_noremap[ typebuf.tb_off] == RM_YES)) && !timedout) { keylen = check_termcode(max_mlen + 1, NULL, 0, NULL); /* If no termcode matched but 'pastetoggle' * matched partially it's like an incomplete key * sequence. */ if (keylen == 0 && save_keylen == KEYLEN_PART_KEY) keylen = KEYLEN_PART_KEY; /* * When getting a partial match, but the last * characters were not typed, don't wait for a * typed character to complete the termcode. * This helps a lot when a ":normal" command ends * in an ESC. */ if (keylen < 0 && typebuf.tb_len == typebuf.tb_maplen) keylen = 0; } else keylen = 0; if (keylen == 0) /* no matching terminal code */ { #ifdef AMIGA /* check for window bounds report */ if (typebuf.tb_maplen == 0 && (typebuf.tb_buf[ typebuf.tb_off] & 0xff) == CSI) { for (s = typebuf.tb_buf + typebuf.tb_off + 1; s < typebuf.tb_buf + typebuf.tb_off + typebuf.tb_len && (VIM_ISDIGIT(*s) || *s == ';' || *s == ' '); ++s) ; if (*s == 'r' || *s == '|') /* found one */ { del_typebuf((int)(s + 1 - (typebuf.tb_buf + typebuf.tb_off)), 0); /* get size and redraw screen */ shell_resized(); continue; } if (*s == NUL) /* need more characters */ keylen = KEYLEN_PART_KEY; } if (keylen >= 0) #endif /* When there was a matching mapping and no * termcode could be replaced after another one, * use that mapping (loop around). If there was * no mapping use the character from the * typeahead buffer right here. */ if (mp == NULL) { /* * get a character: 2. from the typeahead buffer */ c = typebuf.tb_buf[typebuf.tb_off] & 255; if (advance) /* remove chars from tb_buf */ { cmd_silent = (typebuf.tb_silent > 0); if (typebuf.tb_maplen > 0) KeyTyped = FALSE; else { KeyTyped = TRUE; /* write char to script file(s) */ gotchars(typebuf.tb_buf + typebuf.tb_off, 1); } KeyNoremap = typebuf.tb_noremap[ typebuf.tb_off]; del_typebuf(1, 0); } break; /* got character, break for loop */ } } if (keylen > 0) /* full matching terminal code */ { #if defined(FEAT_GUI) && defined(FEAT_MENU) if (typebuf.tb_len >= 2 && typebuf.tb_buf[typebuf.tb_off] == K_SPECIAL && typebuf.tb_buf[typebuf.tb_off + 1] == KS_MENU) { /* * Using a menu may cause a break in undo! * It's like using gotchars(), but without * recording or writing to a script file. */ may_sync_undo(); del_typebuf(3, 0); idx = get_menu_index(current_menu, local_State); if (idx != MENU_INDEX_INVALID) { # ifdef FEAT_VISUAL /* * In Select mode and a Visual mode menu * is used: Switch to Visual mode * temporarily. Append K_SELECT to switch * back to Select mode. */ if (VIsual_active && VIsual_select && (current_menu->modes & VISUAL)) { VIsual_select = FALSE; (void)ins_typebuf(K_SELECT_STRING, REMAP_NONE, 0, TRUE, FALSE); } # endif ins_typebuf(current_menu->strings[idx], current_menu->noremap[idx], 0, TRUE, current_menu->silent[idx]); } } #endif /* FEAT_GUI && FEAT_MENU */ continue; /* try mapping again */ } /* Partial match: get some more characters. When a * matching mapping was found use that one. */ if (mp == NULL || keylen < 0) keylen = KEYLEN_PART_KEY; else keylen = mp_match_len; } /* complete match */ if (keylen >= 0 && keylen <= typebuf.tb_len) { #ifdef FEAT_EVAL int save_m_expr; int save_m_noremap; int save_m_silent; char_u *save_m_keys; char_u *save_m_str; #else # define save_m_noremap mp->m_noremap # define save_m_silent mp->m_silent #endif /* write chars to script file(s) */ if (keylen > typebuf.tb_maplen) gotchars(typebuf.tb_buf + typebuf.tb_off + typebuf.tb_maplen, keylen - typebuf.tb_maplen); cmd_silent = (typebuf.tb_silent > 0); del_typebuf(keylen, 0); /* remove the mapped keys */ /* * Put the replacement string in front of mapstr. * The depth check catches ":map x y" and ":map y x". */ if (++mapdepth >= p_mmd) { EMSG(_("E223: recursive mapping")); if (State & CMDLINE) redrawcmdline(); else setcursor(); flush_buffers(FALSE); mapdepth = 0; /* for next one */ c = -1; break; } #ifdef FEAT_VISUAL /* * In Select mode and a Visual mode mapping is used: * Switch to Visual mode temporarily. Append K_SELECT * to switch back to Select mode. */ if (VIsual_active && VIsual_select && (mp->m_mode & VISUAL)) { VIsual_select = FALSE; (void)ins_typebuf(K_SELECT_STRING, REMAP_NONE, 0, TRUE, FALSE); } #endif #ifdef FEAT_EVAL /* Copy the values from *mp that are used, because * evaluating the expression may invoke a function * that redefines the mapping, thereby making *mp * invalid. */ save_m_expr = mp->m_expr; save_m_noremap = mp->m_noremap; save_m_silent = mp->m_silent; save_m_keys = NULL; /* only saved when needed */ save_m_str = NULL; /* only saved when needed */ /* * Handle ":map <expr>": evaluate the {rhs} as an * expression. Also save and restore the command line * for "normal :". */ if (mp->m_expr) { int save_vgetc_busy = vgetc_busy; vgetc_busy = 0; save_m_keys = vim_strsave(mp->m_keys); save_m_str = vim_strsave(mp->m_str); s = eval_map_expr(save_m_str, NUL); vgetc_busy = save_vgetc_busy; } else #endif s = mp->m_str; /* * Insert the 'to' part in the typebuf.tb_buf. * If 'from' field is the same as the start of the * 'to' field, don't remap the first character (but do * allow abbreviations). * If m_noremap is set, don't remap the whole 'to' * part. */ if (s == NULL) i = FAIL; else { int noremap; if (save_m_noremap != REMAP_YES) noremap = save_m_noremap; else if ( #ifdef FEAT_EVAL STRNCMP(s, save_m_keys != NULL ? save_m_keys : mp->m_keys, (size_t)keylen) #else STRNCMP(s, mp->m_keys, (size_t)keylen) #endif != 0) noremap = REMAP_YES; else noremap = REMAP_SKIP; i = ins_typebuf(s, noremap, 0, TRUE, cmd_silent || save_m_silent); #ifdef FEAT_EVAL if (save_m_expr) vim_free(s); #endif } #ifdef FEAT_EVAL vim_free(save_m_keys); vim_free(save_m_str); #endif if (i == FAIL) { c = -1; break; } continue; } } /* * get a character: 3. from the user - handle <Esc> in Insert mode */ /* * special case: if we get an <ESC> in insert mode and there * are no more characters at once, we pretend to go out of * insert mode. This prevents the one second delay after * typing an <ESC>. If we get something after all, we may * have to redisplay the mode. That the cursor is in the wrong * place does not matter. */ c = 0; #ifdef FEAT_CMDL_INFO new_wcol = curwin->w_wcol; new_wrow = curwin->w_wrow; #endif if ( advance && typebuf.tb_len == 1 && typebuf.tb_buf[typebuf.tb_off] == ESC && !no_mapping #ifdef FEAT_EX_EXTRA && ex_normal_busy == 0 #endif && typebuf.tb_maplen == 0 && (State & INSERT) && (p_timeout || (keylen == KEYLEN_PART_KEY && p_ttimeout)) && (c = inchar(typebuf.tb_buf + typebuf.tb_off + typebuf.tb_len, 3, 25L, typebuf.tb_change_cnt)) == 0) { colnr_T col = 0, vcol; char_u *ptr; if (mode_displayed) { unshowmode(TRUE); mode_deleted = TRUE; } #ifdef FEAT_GUI /* may show different cursor shape */ if (gui.in_use) { int save_State; save_State = State; State = NORMAL; gui_update_cursor(TRUE, FALSE); State = save_State; shape_changed = TRUE; } #endif validate_cursor(); old_wcol = curwin->w_wcol; old_wrow = curwin->w_wrow; /* move cursor left, if possible */ if (curwin->w_cursor.col != 0) { if (curwin->w_wcol > 0) { if (did_ai) { /* * We are expecting to truncate the trailing * white-space, so find the last non-white * character -- webb */ col = vcol = curwin->w_wcol = 0; ptr = ml_get_curline(); while (col < curwin->w_cursor.col) { if (!vim_iswhite(ptr[col])) curwin->w_wcol = vcol; vcol += lbr_chartabsize(ptr + col, (colnr_T)vcol); #ifdef FEAT_MBYTE if (has_mbyte) col += (*mb_ptr2len)(ptr + col); else #endif ++col; } curwin->w_wrow = curwin->w_cline_row + curwin->w_wcol / W_WIDTH(curwin); curwin->w_wcol %= W_WIDTH(curwin); curwin->w_wcol += curwin_col_off(); #ifdef FEAT_MBYTE col = 0; /* no correction needed */ #endif } else { --curwin->w_wcol; #ifdef FEAT_MBYTE col = curwin->w_cursor.col - 1; #endif } } else if (curwin->w_p_wrap && curwin->w_wrow) { --curwin->w_wrow; curwin->w_wcol = W_WIDTH(curwin) - 1; #ifdef FEAT_MBYTE col = curwin->w_cursor.col - 1; #endif } #ifdef FEAT_MBYTE if (has_mbyte && col > 0 && curwin->w_wcol > 0) { /* Correct when the cursor is on the right halve * of a double-wide character. */ ptr = ml_get_curline(); col -= (*mb_head_off)(ptr, ptr + col); if ((*mb_ptr2cells)(ptr + col) > 1) --curwin->w_wcol; } #endif } setcursor(); out_flush(); #ifdef FEAT_CMDL_INFO new_wcol = curwin->w_wcol; new_wrow = curwin->w_wrow; #endif curwin->w_wcol = old_wcol; curwin->w_wrow = old_wrow; } if (c < 0) continue; /* end of input script reached */ typebuf.tb_len += c; /* buffer full, don't map */ if (typebuf.tb_len >= typebuf.tb_maplen + MAXMAPLEN) { timedout = TRUE; continue; } #ifdef FEAT_EX_EXTRA if (ex_normal_busy > 0) { # ifdef FEAT_CMDWIN static int tc = 0; # endif /* No typeahead left and inside ":normal". Must return * something to avoid getting stuck. When an incomplete * mapping is present, behave like it timed out. */ if (typebuf.tb_len > 0) { timedout = TRUE; continue; } /* When 'insertmode' is set, ESC just beeps in Insert * mode. Use CTRL-L to make edit() return. * For the command line only CTRL-C always breaks it. * For the cmdline window: Alternate between ESC and * CTRL-C: ESC for most situations and CTRL-C to close the * cmdline window. */ if (p_im && (State & INSERT)) c = Ctrl_L; else if ((State & CMDLINE) # ifdef FEAT_CMDWIN || (cmdwin_type > 0 && tc == ESC) # endif ) c = Ctrl_C; else c = ESC; # ifdef FEAT_CMDWIN tc = c; # endif break; } #endif /* * get a character: 3. from the user - update display */ /* In insert mode a screen update is skipped when characters * are still available. But when those available characters * are part of a mapping, and we are going to do a blocking * wait here. Need to update the screen to display the * changed text so far. Also for when 'lazyredraw' is set and * redrawing was postponed because there was something in the * input buffer (e.g., termresponse). */ if (((State & INSERT) != 0 || p_lz) && (State & CMDLINE) == 0 && advance && must_redraw != 0 && !need_wait_return) { update_screen(0); setcursor(); /* put cursor back where it belongs */ } /* * If we have a partial match (and are going to wait for more * input from the user), show the partially matched characters * to the user with showcmd. */ #ifdef FEAT_CMDL_INFO i = 0; #endif c1 = 0; if (typebuf.tb_len > 0 && advance && !exmode_active) { if (((State & (NORMAL | INSERT)) || State == LANGMAP) && State != HITRETURN) { /* this looks nice when typing a dead character map */ if (State & INSERT && ptr2cells(typebuf.tb_buf + typebuf.tb_off + typebuf.tb_len - 1) == 1) { edit_putchar(typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len - 1], FALSE); setcursor(); /* put cursor back where it belongs */ c1 = 1; } #ifdef FEAT_CMDL_INFO /* need to use the col and row from above here */ old_wcol = curwin->w_wcol; old_wrow = curwin->w_wrow; curwin->w_wcol = new_wcol; curwin->w_wrow = new_wrow; push_showcmd(); if (typebuf.tb_len > SHOWCMD_COLS) i = typebuf.tb_len - SHOWCMD_COLS; while (i < typebuf.tb_len) (void)add_to_showcmd(typebuf.tb_buf[typebuf.tb_off + i++]); curwin->w_wcol = old_wcol; curwin->w_wrow = old_wrow; #endif } /* this looks nice when typing a dead character map */ if ((State & CMDLINE) #if defined(FEAT_CRYPT) || defined(FEAT_EVAL) && cmdline_star == 0 #endif && ptr2cells(typebuf.tb_buf + typebuf.tb_off + typebuf.tb_len - 1) == 1) { putcmdline(typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len - 1], FALSE); c1 = 1; } } /* * get a character: 3. from the user - get it */ wait_tb_len = typebuf.tb_len; c = inchar(typebuf.tb_buf + typebuf.tb_off + typebuf.tb_len, typebuf.tb_buflen - typebuf.tb_off - typebuf.tb_len - 1, !advance ? 0 : ((typebuf.tb_len == 0 || !(p_timeout || (p_ttimeout && keylen == KEYLEN_PART_KEY))) ? -1L : ((keylen == KEYLEN_PART_KEY && p_ttm >= 0) ? p_ttm : p_tm)), typebuf.tb_change_cnt); #ifdef FEAT_CMDL_INFO if (i != 0) pop_showcmd(); #endif if (c1 == 1) { if (State & INSERT) edit_unputchar(); if (State & CMDLINE) unputcmdline(); else setcursor(); /* put cursor back where it belongs */ } if (c < 0) continue; /* end of input script reached */ if (c == NUL) /* no character available */ { if (!advance) break; if (wait_tb_len > 0) /* timed out */ { timedout = TRUE; continue; } } else { /* allow mapping for just typed characters */ while (typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len] != NUL) typebuf.tb_noremap[typebuf.tb_off + typebuf.tb_len++] = RM_YES; #ifdef USE_IM_CONTROL /* Get IM status right after getting keys, not after the * timeout for a mapping (focus may be lost by then). */ vgetc_im_active = im_get_status(); #endif } } /* for (;;) */ } /* if (!character from stuffbuf) */ /* if advance is FALSE don't loop on NULs */ } while (c < 0 || (advance && c == NUL)); /* * The "INSERT" message is taken care of here: * if we return an ESC to exit insert mode, the message is deleted * if we don't return an ESC but deleted the message before, redisplay it */ if (advance && p_smd && msg_silent == 0 && (State & INSERT)) { if (c == ESC && !mode_deleted && !no_mapping && mode_displayed) { if (typebuf.tb_len && !KeyTyped) redraw_cmdline = TRUE; /* delete mode later */ else unshowmode(FALSE); } else if (c != ESC && mode_deleted) { if (typebuf.tb_len && !KeyTyped) redraw_cmdline = TRUE; /* show mode later */ else showmode(); } } #ifdef FEAT_GUI /* may unshow different cursor shape */ if (gui.in_use && shape_changed) gui_update_cursor(TRUE, FALSE); #endif --vgetc_busy; return c; } /* * inchar() - get one character from * 1. a scriptfile * 2. the keyboard * * As much characters as we can get (upto 'maxlen') are put in "buf" and * NUL terminated (buffer length must be 'maxlen' + 1). * Minimum for "maxlen" is 3!!!! * * "tb_change_cnt" is the value of typebuf.tb_change_cnt if "buf" points into * it. When typebuf.tb_change_cnt changes (e.g., when a message is received * from a remote client) "buf" can no longer be used. "tb_change_cnt" is 0 * otherwise. * * If we got an interrupt all input is read until none is available. * * If wait_time == 0 there is no waiting for the char. * If wait_time == n we wait for n msec for a character to arrive. * If wait_time == -1 we wait forever for a character to arrive. * * Return the number of obtained characters. * Return -1 when end of input script reached. */ int inchar(buf, maxlen, wait_time, tb_change_cnt) char_u *buf; int maxlen; long wait_time; /* milli seconds */ int tb_change_cnt; { int len = 0; /* init for GCC */ int retesc = FALSE; /* return ESC with gotint */ int script_char; if (wait_time == -1L || wait_time > 100L) /* flush output before waiting */ { cursor_on(); out_flush(); #ifdef FEAT_GUI if (gui.in_use) { gui_update_cursor(FALSE, FALSE); # ifdef FEAT_MOUSESHAPE if (postponed_mouseshape) update_mouseshape(-1); # endif } #endif } /* * Don't reset these when at the hit-return prompt, otherwise a endless * recursive loop may result (write error in swapfile, hit-return, timeout * on char wait, flush swapfile, write error....). */ if (State != HITRETURN) { did_outofmem_msg = FALSE; /* display out of memory message (again) */ did_swapwrite_msg = FALSE; /* display swap file write error again */ } undo_off = FALSE; /* restart undo now */ /* * Get a character from a script file if there is one. * If interrupted: Stop reading script files, close them all. */ script_char = -1; while (scriptin[curscript] != NULL && script_char < 0 #ifdef FEAT_EVAL && !ignore_script #endif ) { #if defined(FEAT_NETBEANS_INTG) /* Process the queued netbeans messages. */ netbeans_parse_messages(); #endif if (got_int || (script_char = getc(scriptin[curscript])) < 0) { /* Reached EOF. * Careful: closescript() frees typebuf.tb_buf[] and buf[] may * point inside typebuf.tb_buf[]. Don't use buf[] after this! */ closescript(); /* * When reading script file is interrupted, return an ESC to get * back to normal mode. * Otherwise return -1, because typebuf.tb_buf[] has changed. */ if (got_int) retesc = TRUE; else return -1; } else { buf[0] = script_char; len = 1; } } if (script_char < 0) /* did not get a character from script */ { /* * If we got an interrupt, skip all previously typed characters and * return TRUE if quit reading script file. * Stop reading typeahead when a single CTRL-C was read, * fill_input_buf() returns this when not able to read from stdin. * Don't use buf[] here, closescript() may have freed typebuf.tb_buf[] * and buf may be pointing inside typebuf.tb_buf[]. */ if (got_int) { #define DUM_LEN MAXMAPLEN * 3 + 3 char_u dum[DUM_LEN + 1]; for (;;) { len = ui_inchar(dum, DUM_LEN, 0L, 0); if (len == 0 || (len == 1 && dum[0] == 3)) break; } return retesc; } /* * Always flush the output characters when getting input characters * from the user. */ out_flush(); /* * Fill up to a third of the buffer, because each character may be * tripled below. */ len = ui_inchar(buf, maxlen / 3, wait_time, tb_change_cnt); } if (typebuf_changed(tb_change_cnt)) return 0; return fix_input_buffer(buf, len, script_char >= 0); } /* * Fix typed characters for use by vgetc() and check_termcode(). * buf[] must have room to triple the number of bytes! * Returns the new length. */ int fix_input_buffer(buf, len, script) char_u *buf; int len; int script; /* TRUE when reading from a script */ { int i; char_u *p = buf; /* * Two characters are special: NUL and K_SPECIAL. * When compiled With the GUI CSI is also special. * Replace NUL by K_SPECIAL KS_ZERO KE_FILLER * Replace K_SPECIAL by K_SPECIAL KS_SPECIAL KE_FILLER * Replace CSI by K_SPECIAL KS_EXTRA KE_CSI * Don't replace K_SPECIAL when reading a script file. */ for (i = len; --i >= 0; ++p) { #ifdef FEAT_GUI /* When the GUI is used any character can come after a CSI, don't * escape it. */ if (gui.in_use && p[0] == CSI && i >= 2) { p += 2; i -= 2; } /* When the GUI is not used CSI needs to be escaped. */ else if (!gui.in_use && p[0] == CSI) { mch_memmove(p + 3, p + 1, (size_t)i); *p++ = K_SPECIAL; *p++ = KS_EXTRA; *p = (int)KE_CSI; len += 2; } else #endif if (p[0] == NUL || (p[0] == K_SPECIAL && !script #ifdef FEAT_AUTOCMD /* timeout may generate K_CURSORHOLD */ && (i < 2 || p[1] != KS_EXTRA || p[2] != (int)KE_CURSORHOLD) #endif #if defined(WIN3264) && !defined(FEAT_GUI) /* Win32 console passes modifiers */ && (i < 2 || p[1] != KS_MODIFIER) #endif )) { mch_memmove(p + 3, p + 1, (size_t)i); p[2] = K_THIRD(p[0]); p[1] = K_SECOND(p[0]); p[0] = K_SPECIAL; p += 2; len += 2; } } *p = NUL; /* add trailing NUL */ return len; } #if defined(USE_INPUT_BUF) || defined(PROTO) /* * Return TRUE when bytes are in the input buffer or in the typeahead buffer. * Normally the input buffer would be sufficient, but the server_to_input_buf() * or feedkeys() may insert characters in the typeahead buffer while we are * waiting for input to arrive. */ int input_available() { return (!vim_is_input_buf_empty() # if defined(FEAT_CLIENTSERVER) || defined(FEAT_EVAL) || typebuf_was_filled # endif ); } #endif /* * map[!] : show all key mappings * map[!] {lhs} : show key mapping for {lhs} * map[!] {lhs} {rhs} : set key mapping for {lhs} to {rhs} * noremap[!] {lhs} {rhs} : same, but no remapping for {rhs} * unmap[!] {lhs} : remove key mapping for {lhs} * abbr : show all abbreviations * abbr {lhs} : show abbreviations for {lhs} * abbr {lhs} {rhs} : set abbreviation for {lhs} to {rhs} * noreabbr {lhs} {rhs} : same, but no remapping for {rhs} * unabbr {lhs} : remove abbreviation for {lhs} * * maptype: 0 for :map, 1 for :unmap, 2 for noremap. * * arg is pointer to any arguments. Note: arg cannot be a read-only string, * it will be modified. * * for :map mode is NORMAL + VISUAL + SELECTMODE + OP_PENDING * for :map! mode is INSERT + CMDLINE * for :cmap mode is CMDLINE * for :imap mode is INSERT * for :lmap mode is LANGMAP * for :nmap mode is NORMAL * for :vmap mode is VISUAL + SELECTMODE * for :xmap mode is VISUAL * for :smap mode is SELECTMODE * for :omap mode is OP_PENDING * * for :abbr mode is INSERT + CMDLINE * for :iabbr mode is INSERT * for :cabbr mode is CMDLINE * * Return 0 for success * 1 for invalid arguments * 2 for no match * 4 for out of mem * 5 for entry not unique */ int do_map(maptype, arg, mode, abbrev) int maptype; char_u *arg; int mode; int abbrev; /* not a mapping but an abbreviation */ { char_u *keys; mapblock_T *mp, **mpp; char_u *rhs; char_u *p; int n; int len = 0; /* init for GCC */ char_u *newstr; int hasarg; int haskey; int did_it = FALSE; #ifdef FEAT_LOCALMAP int did_local = FALSE; #endif int round; char_u *keys_buf = NULL; char_u *arg_buf = NULL; int retval = 0; int do_backslash; int hash; int new_hash; mapblock_T **abbr_table; mapblock_T **map_table; int unique = FALSE; int silent = FALSE; int special = FALSE; #ifdef FEAT_EVAL int expr = FALSE; #endif int noremap; char_u *orig_rhs; keys = arg; map_table = maphash; abbr_table = &first_abbr; /* For ":noremap" don't remap, otherwise do remap. */ if (maptype == 2) noremap = REMAP_NONE; else noremap = REMAP_YES; /* Accept <buffer>, <silent>, <expr> <script> and <unique> in any order. */ for (;;) { #ifdef FEAT_LOCALMAP /* * Check for "<buffer>": mapping local to buffer. */ if (STRNCMP(keys, "<buffer>", 8) == 0) { keys = skipwhite(keys + 8); map_table = curbuf->b_maphash; abbr_table = &curbuf->b_first_abbr; continue; } #endif /* * Check for "<silent>": don't echo commands. */ if (STRNCMP(keys, "<silent>", 8) == 0) { keys = skipwhite(keys + 8); silent = TRUE; continue; } /* * Check for "<special>": accept special keys in <> */ if (STRNCMP(keys, "<special>", 9) == 0) { keys = skipwhite(keys + 9); special = TRUE; continue; } #ifdef FEAT_EVAL /* * Check for "<script>": remap script-local mappings only */ if (STRNCMP(keys, "<script>", 8) == 0) { keys = skipwhite(keys + 8); noremap = REMAP_SCRIPT; continue; } /* * Check for "<expr>": {rhs} is an expression. */ if (STRNCMP(keys, "<expr>", 6) == 0) { keys = skipwhite(keys + 6); expr = TRUE; continue; } #endif /* * Check for "<unique>": don't overwrite an existing mapping. */ if (STRNCMP(keys, "<unique>", 8) == 0) { keys = skipwhite(keys + 8); unique = TRUE; continue; } break; } validate_maphash(); /* * Find end of keys and skip CTRL-Vs (and backslashes) in it. * Accept backslash like CTRL-V when 'cpoptions' does not contain 'B'. * with :unmap white space is included in the keys, no argument possible. */ p = keys; do_backslash = (vim_strchr(p_cpo, CPO_BSLASH) == NULL); while (*p && (maptype == 1 || !vim_iswhite(*p))) { if ((p[0] == Ctrl_V || (do_backslash && p[0] == '\\')) && p[1] != NUL) ++p; /* skip CTRL-V or backslash */ ++p; } if (*p != NUL) *p++ = NUL; p = skipwhite(p); rhs = p; hasarg = (*rhs != NUL); haskey = (*keys != NUL); /* check for :unmap without argument */ if (maptype == 1 && !haskey) { retval = 1; goto theend; } /* * If mapping has been given as ^V<C_UP> say, then replace the term codes * with the appropriate two bytes. If it is a shifted special key, unshift * it too, giving another two bytes. * replace_termcodes() may move the result to allocated memory, which * needs to be freed later (*keys_buf and *arg_buf). * replace_termcodes() also removes CTRL-Vs and sometimes backslashes. */ if (haskey) keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, special); orig_rhs = rhs; if (hasarg) { if (STRICMP(rhs, "<nop>") == 0) /* "<Nop>" means nothing */ rhs = (char_u *)""; else rhs = replace_termcodes(rhs, &arg_buf, FALSE, TRUE, special); } #ifdef FEAT_FKMAP /* * When in right-to-left mode and alternate keymap option set, * reverse the character flow in the rhs in Farsi. */ if (p_altkeymap && curwin->w_p_rl) lrswap(rhs); #endif /* * check arguments and translate function keys */ if (haskey) { len = (int)STRLEN(keys); if (len > MAXMAPLEN) /* maximum length of MAXMAPLEN chars */ { retval = 1; goto theend; } if (abbrev && maptype != 1) { /* * If an abbreviation ends in a keyword character, the * rest must be all keyword-char or all non-keyword-char. * Otherwise we won't be able to find the start of it in a * vi-compatible way. */ #ifdef FEAT_MBYTE if (has_mbyte) { int first, last; int same = -1; first = vim_iswordp(keys); last = first; p = keys + (*mb_ptr2len)(keys); n = 1; while (p < keys + len) { ++n; /* nr of (multi-byte) chars */ last = vim_iswordp(p); /* type of last char */ if (same == -1 && last != first) same = n - 1; /* count of same char type */ p += (*mb_ptr2len)(p); } if (last && n > 2 && same >= 0 && same < n - 1) { retval = 1; goto theend; } } else #endif if (vim_iswordc(keys[len - 1])) /* ends in keyword char */ for (n = 0; n < len - 2; ++n) if (vim_iswordc(keys[n]) != vim_iswordc(keys[len - 2])) { retval = 1; goto theend; } /* An abbreviation cannot contain white space. */ for (n = 0; n < len; ++n) if (vim_iswhite(keys[n])) { retval = 1; goto theend; } } } if (haskey && hasarg && abbrev) /* if we will add an abbreviation */ no_abbr = FALSE; /* reset flag that indicates there are no abbreviations */ if (!haskey || (maptype != 1 && !hasarg)) msg_start(); #ifdef FEAT_LOCALMAP /* * Check if a new local mapping wasn't already defined globally. */ if (map_table == curbuf->b_maphash && haskey && hasarg && maptype != 1) { /* need to loop over all global hash lists */ for (hash = 0; hash < 256 && !got_int; ++hash) { if (abbrev) { if (hash != 0) /* there is only one abbreviation list */ break; mp = first_abbr; } else mp = maphash[hash]; for ( ; mp != NULL && !got_int; mp = mp->m_next) { /* check entries with the same mode */ if ((mp->m_mode & mode) != 0 && mp->m_keylen == len && unique && STRNCMP(mp->m_keys, keys, (size_t)len) == 0) { if (abbrev) EMSG2(_("E224: global abbreviation already exists for %s"), mp->m_keys); else EMSG2(_("E225: global mapping already exists for %s"), mp->m_keys); retval = 5; goto theend; } } } } /* * When listing global mappings, also list buffer-local ones here. */ if (map_table != curbuf->b_maphash && !hasarg && maptype != 1) { /* need to loop over all global hash lists */ for (hash = 0; hash < 256 && !got_int; ++hash) { if (abbrev) { if (hash != 0) /* there is only one abbreviation list */ break; mp = curbuf->b_first_abbr; } else mp = curbuf->b_maphash[hash]; for ( ; mp != NULL && !got_int; mp = mp->m_next) { /* check entries with the same mode */ if ((mp->m_mode & mode) != 0) { if (!haskey) /* show all entries */ { showmap(mp, TRUE); did_local = TRUE; } else { n = mp->m_keylen; if (STRNCMP(mp->m_keys, keys, (size_t)(n < len ? n : len)) == 0) { showmap(mp, TRUE); did_local = TRUE; } } } } } } #endif /* * Find an entry in the maphash[] list that matches. * For :unmap we may loop two times: once to try to unmap an entry with a * matching 'from' part, a second time, if the first fails, to unmap an * entry with a matching 'to' part. This was done to allow ":ab foo bar" * to be unmapped by typing ":unab foo", where "foo" will be replaced by * "bar" because of the abbreviation. */ for (round = 0; (round == 0 || maptype == 1) && round <= 1 && !did_it && !got_int; ++round) { /* need to loop over all hash lists */ for (hash = 0; hash < 256 && !got_int; ++hash) { if (abbrev) { if (hash > 0) /* there is only one abbreviation list */ break; mpp = abbr_table; } else mpp = &(map_table[hash]); for (mp = *mpp; mp != NULL && !got_int; mp = *mpp) { if (!(mp->m_mode & mode)) /* skip entries with wrong mode */ { mpp = &(mp->m_next); continue; } if (!haskey) /* show all entries */ { showmap(mp, map_table != maphash); did_it = TRUE; } else /* do we have a match? */ { if (round) /* second round: Try unmap "rhs" string */ { n = (int)STRLEN(mp->m_str); p = mp->m_str; } else { n = mp->m_keylen; p = mp->m_keys; } if (STRNCMP(p, keys, (size_t)(n < len ? n : len)) == 0) { if (maptype == 1) /* delete entry */ { /* Only accept a full match. For abbreviations we * ignore trailing space when matching with the * "lhs", since an abbreviation can't have * trailing space. */ if (n != len && (!abbrev || round || n > len || *skipwhite(keys + n) != NUL)) { mpp = &(mp->m_next); continue; } /* * We reset the indicated mode bits. If nothing is * left the entry is deleted below. */ mp->m_mode &= ~mode; did_it = TRUE; /* remember we did something */ } else if (!hasarg) /* show matching entry */ { showmap(mp, map_table != maphash); did_it = TRUE; } else if (n != len) /* new entry is ambiguous */ { mpp = &(mp->m_next); continue; } else if (unique) { if (abbrev) EMSG2(_("E226: abbreviation already exists for %s"), p); else EMSG2(_("E227: mapping already exists for %s"), p); retval = 5; goto theend; } else /* new rhs for existing entry */ { mp->m_mode &= ~mode; /* remove mode bits */ if (mp->m_mode == 0 && !did_it) /* reuse entry */ { newstr = vim_strsave(rhs); if (newstr == NULL) { retval = 4; /* no mem */ goto theend; } vim_free(mp->m_str); mp->m_str = newstr; vim_free(mp->m_orig_str); mp->m_orig_str = vim_strsave(orig_rhs); mp->m_noremap = noremap; mp->m_silent = silent; mp->m_mode = mode; #ifdef FEAT_EVAL mp->m_expr = expr; mp->m_script_ID = current_SID; #endif did_it = TRUE; } } if (mp->m_mode == 0) /* entry can be deleted */ { map_free(mpp); continue; /* continue with *mpp */ } /* * May need to put this entry into another hash list. */ new_hash = MAP_HASH(mp->m_mode, mp->m_keys[0]); if (!abbrev && new_hash != hash) { *mpp = mp->m_next; mp->m_next = map_table[new_hash]; map_table[new_hash] = mp; continue; /* continue with *mpp */ } } } mpp = &(mp->m_next); } } } if (maptype == 1) /* delete entry */ { if (!did_it) retval = 2; /* no match */ goto theend; } if (!haskey || !hasarg) /* print entries */ { if (!did_it #ifdef FEAT_LOCALMAP && !did_local #endif ) { if (abbrev) MSG(_("No abbreviation found")); else MSG(_("No mapping found")); } goto theend; /* listing finished */ } if (did_it) /* have added the new entry already */ goto theend; /* * Get here when adding a new entry to the maphash[] list or abbrlist. */ mp = (mapblock_T *)alloc((unsigned)sizeof(mapblock_T)); if (mp == NULL) { retval = 4; /* no mem */ goto theend; } /* If CTRL-C has been mapped, don't always use it for Interrupting */ if (*keys == Ctrl_C) mapped_ctrl_c = TRUE; mp->m_keys = vim_strsave(keys); mp->m_str = vim_strsave(rhs); mp->m_orig_str = vim_strsave(orig_rhs); if (mp->m_keys == NULL || mp->m_str == NULL) { vim_free(mp->m_keys); vim_free(mp->m_str); vim_free(mp->m_orig_str); vim_free(mp); retval = 4; /* no mem */ goto theend; } mp->m_keylen = (int)STRLEN(mp->m_keys); mp->m_noremap = noremap; mp->m_silent = silent; mp->m_mode = mode; #ifdef FEAT_EVAL mp->m_expr = expr; mp->m_script_ID = current_SID; #endif /* add the new entry in front of the abbrlist or maphash[] list */ if (abbrev) { mp->m_next = *abbr_table; *abbr_table = mp; } else { n = MAP_HASH(mp->m_mode, mp->m_keys[0]); mp->m_next = map_table[n]; map_table[n] = mp; } theend: vim_free(keys_buf); vim_free(arg_buf); return retval; } /* * Delete one entry from the abbrlist or maphash[]. * "mpp" is a pointer to the m_next field of the PREVIOUS entry! */ static void map_free(mpp) mapblock_T **mpp; { mapblock_T *mp; mp = *mpp; vim_free(mp->m_keys); vim_free(mp->m_str); vim_free(mp->m_orig_str); *mpp = mp->m_next; vim_free(mp); } /* * Initialize maphash[] for first use. */ static void validate_maphash() { if (!maphash_valid) { vim_memset(maphash, 0, sizeof(maphash)); maphash_valid = TRUE; } } /* * Get the mapping mode from the command name. */ int get_map_mode(cmdp, forceit) char_u **cmdp; int forceit; { char_u *p; int modec; int mode; p = *cmdp; modec = *p++; if (modec == 'i') mode = INSERT; /* :imap */ else if (modec == 'l') mode = LANGMAP; /* :lmap */ else if (modec == 'c') mode = CMDLINE; /* :cmap */ else if (modec == 'n' && *p != 'o') /* avoid :noremap */ mode = NORMAL; /* :nmap */ else if (modec == 'v') mode = VISUAL + SELECTMODE; /* :vmap */ else if (modec == 'x') mode = VISUAL; /* :xmap */ else if (modec == 's') mode = SELECTMODE; /* :smap */ else if (modec == 'o') mode = OP_PENDING; /* :omap */ else { --p; if (forceit) mode = INSERT + CMDLINE; /* :map ! */ else mode = VISUAL + SELECTMODE + NORMAL + OP_PENDING;/* :map */ } *cmdp = p; return mode; } /* * Clear all mappings or abbreviations. * 'abbr' should be FALSE for mappings, TRUE for abbreviations. */ void map_clear(cmdp, arg, forceit, abbr) char_u *cmdp; char_u *arg UNUSED; int forceit; int abbr; { int mode; #ifdef FEAT_LOCALMAP int local; local = (STRCMP(arg, "<buffer>") == 0); if (!local && *arg != NUL) { EMSG(_(e_invarg)); return; } #endif mode = get_map_mode(&cmdp, forceit); map_clear_int(curbuf, mode, #ifdef FEAT_LOCALMAP local, #else FALSE, #endif abbr); } /* * Clear all mappings in "mode". */ void map_clear_int(buf, mode, local, abbr) buf_T *buf UNUSED; /* buffer for local mappings */ int mode; /* mode in which to delete */ int local UNUSED; /* TRUE for buffer-local mappings */ int abbr; /* TRUE for abbreviations */ { mapblock_T *mp, **mpp; int hash; int new_hash; validate_maphash(); for (hash = 0; hash < 256; ++hash) { if (abbr) { if (hash > 0) /* there is only one abbrlist */ break; #ifdef FEAT_LOCALMAP if (local) mpp = &buf->b_first_abbr; else #endif mpp = &first_abbr; } else { #ifdef FEAT_LOCALMAP if (local) mpp = &buf->b_maphash[hash]; else #endif mpp = &maphash[hash]; } while (*mpp != NULL) { mp = *mpp; if (mp->m_mode & mode) { mp->m_mode &= ~mode; if (mp->m_mode == 0) /* entry can be deleted */ { map_free(mpp); continue; } /* * May need to put this entry into another hash list. */ new_hash = MAP_HASH(mp->m_mode, mp->m_keys[0]); if (!abbr && new_hash != hash) { *mpp = mp->m_next; #ifdef FEAT_LOCALMAP if (local) { mp->m_next = buf->b_maphash[new_hash]; buf->b_maphash[new_hash] = mp; } else #endif { mp->m_next = maphash[new_hash]; maphash[new_hash] = mp; } continue; /* continue with *mpp */ } } mpp = &(mp->m_next); } } } /* * Return characters to represent the map mode in an allocated string. * Returns NULL when out of memory. */ char_u * map_mode_to_chars(mode) int mode; { garray_T mapmode; ga_init2(&mapmode, 1, 7); if ((mode & (INSERT + CMDLINE)) == INSERT + CMDLINE) ga_append(&mapmode, '!'); /* :map! */ else if (mode & INSERT) ga_append(&mapmode, 'i'); /* :imap */ else if (mode & LANGMAP) ga_append(&mapmode, 'l'); /* :lmap */ else if (mode & CMDLINE) ga_append(&mapmode, 'c'); /* :cmap */ else if ((mode & (NORMAL + VISUAL + SELECTMODE + OP_PENDING)) == NORMAL + VISUAL + SELECTMODE + OP_PENDING) ga_append(&mapmode, ' '); /* :map */ else { if (mode & NORMAL) ga_append(&mapmode, 'n'); /* :nmap */ if (mode & OP_PENDING) ga_append(&mapmode, 'o'); /* :omap */ if ((mode & (VISUAL + SELECTMODE)) == VISUAL + SELECTMODE) ga_append(&mapmode, 'v'); /* :vmap */ else { if (mode & VISUAL) ga_append(&mapmode, 'x'); /* :xmap */ if (mode & SELECTMODE) ga_append(&mapmode, 's'); /* :smap */ } } ga_append(&mapmode, NUL); return (char_u *)mapmode.ga_data; } static void showmap(mp, local) mapblock_T *mp; int local; /* TRUE for buffer-local map */ { int len = 1; char_u *mapchars; if (msg_didout || msg_silent != 0) { msg_putchar('\n'); if (got_int) /* 'q' typed at MORE prompt */ return; } mapchars = map_mode_to_chars(mp->m_mode); if (mapchars != NULL) { msg_puts(mapchars); len = (int)STRLEN(mapchars); vim_free(mapchars); } while (++len <= 3) msg_putchar(' '); /* Display the LHS. Get length of what we write. */ len = msg_outtrans_special(mp->m_keys, TRUE); do { msg_putchar(' '); /* padd with blanks */ ++len; } while (len < 12); if (mp->m_noremap == REMAP_NONE) msg_puts_attr((char_u *)"*", hl_attr(HLF_8)); else if (mp->m_noremap == REMAP_SCRIPT) msg_puts_attr((char_u *)"&", hl_attr(HLF_8)); else msg_putchar(' '); if (local) msg_putchar('@'); else msg_putchar(' '); /* Use FALSE below if we only want things like <Up> to show up as such on * the rhs, and not M-x etc, TRUE gets both -- webb */ if (*mp->m_str == NUL) msg_puts_attr((char_u *)"<Nop>", hl_attr(HLF_8)); else { /* Remove escaping of CSI, because "m_str" is in a format to be used * as typeahead. */ char_u *s = vim_strsave(mp->m_str); if (s != NULL) { vim_unescape_csi(s); msg_outtrans_special(s, FALSE); vim_free(s); } } #ifdef FEAT_EVAL if (p_verbose > 0) last_set_msg(mp->m_script_ID); #endif out_flush(); /* show one line at a time */ } #if defined(FEAT_EVAL) || defined(PROTO) /* * Return TRUE if a map exists that has "str" in the rhs for mode "modechars". * Recognize termcap codes in "str". * Also checks mappings local to the current buffer. */ int map_to_exists(str, modechars, abbr) char_u *str; char_u *modechars; int abbr; { int mode = 0; char_u *rhs; char_u *buf; int retval; rhs = replace_termcodes(str, &buf, FALSE, TRUE, FALSE); if (vim_strchr(modechars, 'n') != NULL) mode |= NORMAL; if (vim_strchr(modechars, 'v') != NULL) mode |= VISUAL + SELECTMODE; if (vim_strchr(modechars, 'x') != NULL) mode |= VISUAL; if (vim_strchr(modechars, 's') != NULL) mode |= SELECTMODE; if (vim_strchr(modechars, 'o') != NULL) mode |= OP_PENDING; if (vim_strchr(modechars, 'i') != NULL) mode |= INSERT; if (vim_strchr(modechars, 'l') != NULL) mode |= LANGMAP; if (vim_strchr(modechars, 'c') != NULL) mode |= CMDLINE; retval = map_to_exists_mode(rhs, mode, abbr); vim_free(buf); return retval; } #endif /* * Return TRUE if a map exists that has "str" in the rhs for mode "mode". * Also checks mappings local to the current buffer. */ int map_to_exists_mode(rhs, mode, abbr) char_u *rhs; int mode; int abbr; { mapblock_T *mp; int hash; # ifdef FEAT_LOCALMAP int expand_buffer = FALSE; validate_maphash(); /* Do it twice: once for global maps and once for local maps. */ for (;;) { # endif for (hash = 0; hash < 256; ++hash) { if (abbr) { if (hash > 0) /* there is only one abbr list */ break; #ifdef FEAT_LOCALMAP if (expand_buffer) mp = curbuf->b_first_abbr; else #endif mp = first_abbr; } # ifdef FEAT_LOCALMAP else if (expand_buffer) mp = curbuf->b_maphash[hash]; # endif else mp = maphash[hash]; for (; mp; mp = mp->m_next) { if ((mp->m_mode & mode) && strstr((char *)mp->m_str, (char *)rhs) != NULL) return TRUE; } } # ifdef FEAT_LOCALMAP if (expand_buffer) break; expand_buffer = TRUE; } # endif return FALSE; } #if defined(FEAT_CMDL_COMPL) || defined(PROTO) /* * Used below when expanding mapping/abbreviation names. */ static int expand_mapmodes = 0; static int expand_isabbrev = 0; #ifdef FEAT_LOCALMAP static int expand_buffer = FALSE; #endif /* * Work out what to complete when doing command line completion of mapping * or abbreviation names. */ char_u * set_context_in_map_cmd(xp, cmd, arg, forceit, isabbrev, isunmap, cmdidx) expand_T *xp; char_u *cmd; char_u *arg; int forceit; /* TRUE if '!' given */ int isabbrev; /* TRUE if abbreviation */ int isunmap; /* TRUE if unmap/unabbrev command */ cmdidx_T cmdidx; { if (forceit && cmdidx != CMD_map && cmdidx != CMD_unmap) xp->xp_context = EXPAND_NOTHING; else { if (isunmap) expand_mapmodes = get_map_mode(&cmd, forceit || isabbrev); else { expand_mapmodes = INSERT + CMDLINE; if (!isabbrev) expand_mapmodes += VISUAL + SELECTMODE + NORMAL + OP_PENDING; } expand_isabbrev = isabbrev; xp->xp_context = EXPAND_MAPPINGS; #ifdef FEAT_LOCALMAP expand_buffer = FALSE; #endif for (;;) { #ifdef FEAT_LOCALMAP if (STRNCMP(arg, "<buffer>", 8) == 0) { expand_buffer = TRUE; arg = skipwhite(arg + 8); continue; } #endif if (STRNCMP(arg, "<unique>", 8) == 0) { arg = skipwhite(arg + 8); continue; } if (STRNCMP(arg, "<silent>", 8) == 0) { arg = skipwhite(arg + 8); continue; } #ifdef FEAT_EVAL if (STRNCMP(arg, "<script>", 8) == 0) { arg = skipwhite(arg + 8); continue; } if (STRNCMP(arg, "<expr>", 6) == 0) { arg = skipwhite(arg + 6); continue; } #endif break; } xp->xp_pattern = arg; } return NULL; } /* * Find all mapping/abbreviation names that match regexp 'prog'. * For command line expansion of ":[un]map" and ":[un]abbrev" in all modes. * Return OK if matches found, FAIL otherwise. */ int ExpandMappings(regmatch, num_file, file) regmatch_T *regmatch; int *num_file; char_u ***file; { mapblock_T *mp; int hash; int count; int round; char_u *p; int i; validate_maphash(); *num_file = 0; /* return values in case of FAIL */ *file = NULL; /* * round == 1: Count the matches. * round == 2: Build the array to keep the matches. */ for (round = 1; round <= 2; ++round) { count = 0; for (i = 0; i < 5; ++i) { if (i == 0) p = (char_u *)"<silent>"; else if (i == 1) p = (char_u *)"<unique>"; #ifdef FEAT_EVAL else if (i == 2) p = (char_u *)"<script>"; else if (i == 3) p = (char_u *)"<expr>"; #endif #ifdef FEAT_LOCALMAP else if (i == 4 && !expand_buffer) p = (char_u *)"<buffer>"; #endif else continue; if (vim_regexec(regmatch, p, (colnr_T)0)) { if (round == 1) ++count; else (*file)[count++] = vim_strsave(p); } } for (hash = 0; hash < 256; ++hash) { if (expand_isabbrev) { if (hash > 0) /* only one abbrev list */ break; /* for (hash) */ mp = first_abbr; } #ifdef FEAT_LOCALMAP else if (expand_buffer) mp = curbuf->b_maphash[hash]; #endif else mp = maphash[hash]; for (; mp; mp = mp->m_next) { if (mp->m_mode & expand_mapmodes) { p = translate_mapping(mp->m_keys, TRUE); if (p != NULL && vim_regexec(regmatch, p, (colnr_T)0)) { if (round == 1) ++count; else { (*file)[count++] = p; p = NULL; } } vim_free(p); } } /* for (mp) */ } /* for (hash) */ if (count == 0) /* no match found */ break; /* for (round) */ if (round == 1) { *file = (char_u **)alloc((unsigned)(count * sizeof(char_u *))); if (*file == NULL) return FAIL; } } /* for (round) */ if (count > 1) { char_u **ptr1; char_u **ptr2; char_u **ptr3; /* Sort the matches */ sort_strings(*file, count); /* Remove multiple entries */ ptr1 = *file; ptr2 = ptr1 + 1; ptr3 = ptr1 + count; while (ptr2 < ptr3) { if (STRCMP(*ptr1, *ptr2)) *++ptr1 = *ptr2++; else { vim_free(*ptr2++); count--; } } } *num_file = count; return (count == 0 ? FAIL : OK); } #endif /* FEAT_CMDL_COMPL */ /* * Check for an abbreviation. * Cursor is at ptr[col]. When inserting, mincol is where insert started. * "c" is the character typed before check_abbr was called. It may have * ABBR_OFF added to avoid prepending a CTRL-V to it. * * Historic vi practice: The last character of an abbreviation must be an id * character ([a-zA-Z0-9_]). The characters in front of it must be all id * characters or all non-id characters. This allows for abbr. "#i" to * "#include". * * Vim addition: Allow for abbreviations that end in a non-keyword character. * Then there must be white space before the abbr. * * return TRUE if there is an abbreviation, FALSE if not */ int check_abbr(c, ptr, col, mincol) int c; char_u *ptr; int col; int mincol; { int len; int scol; /* starting column of the abbr. */ int j; char_u *s; char_u tb[MB_MAXBYTES + 4]; mapblock_T *mp; #ifdef FEAT_LOCALMAP mapblock_T *mp2; #endif #ifdef FEAT_MBYTE int clen = 0; /* length in characters */ #endif int is_id = TRUE; int vim_abbr; if (typebuf.tb_no_abbr_cnt) /* abbrev. are not recursive */ return FALSE; /* no remapping implies no abbreviation, except for CTRL-] */ if ((KeyNoremap & (RM_NONE|RM_SCRIPT)) != 0 && c != Ctrl_RSB) return FALSE; /* * Check for word before the cursor: If it ends in a keyword char all * chars before it must be keyword chars or non-keyword chars, but not * white space. If it ends in a non-keyword char we accept any characters * before it except white space. */ if (col == 0) /* cannot be an abbr. */ return FALSE; #ifdef FEAT_MBYTE if (has_mbyte) { char_u *p; p = mb_prevptr(ptr, ptr + col); if (!vim_iswordp(p)) vim_abbr = TRUE; /* Vim added abbr. */ else { vim_abbr = FALSE; /* vi compatible abbr. */ if (p > ptr) is_id = vim_iswordp(mb_prevptr(ptr, p)); } clen = 1; while (p > ptr + mincol) { p = mb_prevptr(ptr, p); if (vim_isspace(*p) || (!vim_abbr && is_id != vim_iswordp(p))) { p += (*mb_ptr2len)(p); break; } ++clen; } scol = (int)(p - ptr); } else #endif { if (!vim_iswordc(ptr[col - 1])) vim_abbr = TRUE; /* Vim added abbr. */ else { vim_abbr = FALSE; /* vi compatible abbr. */ if (col > 1) is_id = vim_iswordc(ptr[col - 2]); } for (scol = col - 1; scol > 0 && !vim_isspace(ptr[scol - 1]) && (vim_abbr || is_id == vim_iswordc(ptr[scol - 1])); --scol) ; } if (scol < mincol) scol = mincol; if (scol < col) /* there is a word in front of the cursor */ { ptr += scol; len = col - scol; #ifdef FEAT_LOCALMAP mp = curbuf->b_first_abbr; mp2 = first_abbr; if (mp == NULL) { mp = mp2; mp2 = NULL; } #else mp = first_abbr; #endif for ( ; mp; #ifdef FEAT_LOCALMAP mp->m_next == NULL ? (mp = mp2, mp2 = NULL) : #endif (mp = mp->m_next)) { /* find entries with right mode and keys */ if ( (mp->m_mode & State) && mp->m_keylen == len && !STRNCMP(mp->m_keys, ptr, (size_t)len)) break; } if (mp != NULL) { /* * Found a match: * Insert the rest of the abbreviation in typebuf.tb_buf[]. * This goes from end to start. * * Characters 0x000 - 0x100: normal chars, may need CTRL-V, * except K_SPECIAL: Becomes K_SPECIAL KS_SPECIAL KE_FILLER * Characters where IS_SPECIAL() == TRUE: key codes, need * K_SPECIAL. Other characters (with ABBR_OFF): don't use CTRL-V. * * Character CTRL-] is treated specially - it completes the * abbreviation, but is not inserted into the input stream. */ j = 0; if (c != Ctrl_RSB) { /* special key code, split up */ if (IS_SPECIAL(c) || c == K_SPECIAL) { tb[j++] = K_SPECIAL; tb[j++] = K_SECOND(c); tb[j++] = K_THIRD(c); } else { if (c < ABBR_OFF && (c < ' ' || c > '~')) tb[j++] = Ctrl_V; /* special char needs CTRL-V */ #ifdef FEAT_MBYTE if (has_mbyte) { /* if ABBR_OFF has been added, remove it here */ if (c >= ABBR_OFF) c -= ABBR_OFF; j += (*mb_char2bytes)(c, tb + j); } else #endif tb[j++] = c; } tb[j] = NUL; /* insert the last typed char */ (void)ins_typebuf(tb, 1, 0, TRUE, mp->m_silent); } #ifdef FEAT_EVAL if (mp->m_expr) s = eval_map_expr(mp->m_str, c); else #endif s = mp->m_str; if (s != NULL) { /* insert the to string */ (void)ins_typebuf(s, mp->m_noremap, 0, TRUE, mp->m_silent); /* no abbrev. for these chars */ typebuf.tb_no_abbr_cnt += (int)STRLEN(s) + j + 1; #ifdef FEAT_EVAL if (mp->m_expr) vim_free(s); #endif } tb[0] = Ctrl_H; tb[1] = NUL; #ifdef FEAT_MBYTE if (has_mbyte) len = clen; /* Delete characters instead of bytes */ #endif while (len-- > 0) /* delete the from string */ (void)ins_typebuf(tb, 1, 0, TRUE, mp->m_silent); return TRUE; } } return FALSE; } #ifdef FEAT_EVAL /* * Evaluate the RHS of a mapping or abbreviations and take care of escaping * special characters. */ static char_u * eval_map_expr(str, c) char_u *str; int c; /* NUL or typed character for abbreviation */ { char_u *res; char_u *p; char_u *expr; char_u *save_cmd; pos_T save_cursor; int save_msg_col; int save_msg_row; /* Remove escaping of CSI, because "str" is in a format to be used as * typeahead. */ expr = vim_strsave(str); if (expr == NULL) return NULL; vim_unescape_csi(expr); save_cmd = save_cmdline_alloc(); if (save_cmd == NULL) { vim_free(expr); return NULL; } /* Forbid changing text or using ":normal" to avoid most of the bad side * effects. Also restore the cursor position. */ ++textlock; #ifdef FEAT_EX_EXTRA ++ex_normal_lock; #endif set_vim_var_char(c); /* set v:char to the typed character */ save_cursor = curwin->w_cursor; save_msg_col = msg_col; save_msg_row = msg_row; p = eval_to_string(expr, NULL, FALSE); --textlock; #ifdef FEAT_EX_EXTRA --ex_normal_lock; #endif curwin->w_cursor = save_cursor; msg_col = save_msg_col; msg_row = save_msg_row; restore_cmdline_alloc(save_cmd); vim_free(expr); if (p == NULL) return NULL; /* Escape CSI in the result to be able to use the string as typeahead. */ res = vim_strsave_escape_csi(p); vim_free(p); return res; } #endif /* * Copy "p" to allocated memory, escaping K_SPECIAL and CSI so that the result * can be put in the typeahead buffer. * Returns NULL when out of memory. */ char_u * vim_strsave_escape_csi(p) char_u *p; { char_u *res; char_u *s, *d; /* Need a buffer to hold up to three times as much. */ res = alloc((unsigned)(STRLEN(p) * 3) + 1); if (res != NULL) { d = res; for (s = p; *s != NUL; ) { if (s[0] == K_SPECIAL && s[1] != NUL && s[2] != NUL) { /* Copy special key unmodified. */ *d++ = *s++; *d++ = *s++; *d++ = *s++; } else { /* Add character, possibly multi-byte to destination, escaping * CSI and K_SPECIAL. */ d = add_char2buf(PTR2CHAR(s), d); mb_ptr_adv(s); } } *d = NUL; } return res; } /* * Remove escaping from CSI and K_SPECIAL characters. Reverse of * vim_strsave_escape_csi(). Works in-place. */ void vim_unescape_csi(p) char_u *p; { char_u *s = p, *d = p; while (*s != NUL) { if (s[0] == K_SPECIAL && s[1] == KS_SPECIAL && s[2] == KE_FILLER) { *d++ = K_SPECIAL; s += 3; } else if ((s[0] == K_SPECIAL || s[0] == CSI) && s[1] == KS_EXTRA && s[2] == (int)KE_CSI) { *d++ = CSI; s += 3; } else *d++ = *s++; } *d = NUL; } /* * Write map commands for the current mappings to an .exrc file. * Return FAIL on error, OK otherwise. */ int makemap(fd, buf) FILE *fd; buf_T *buf; /* buffer for local mappings or NULL */ { mapblock_T *mp; char_u c1, c2, c3; char_u *p; char *cmd; int abbr; int hash; int did_cpo = FALSE; int i; validate_maphash(); /* * Do the loop twice: Once for mappings, once for abbreviations. * Then loop over all map hash lists. */ for (abbr = 0; abbr < 2; ++abbr) for (hash = 0; hash < 256; ++hash) { if (abbr) { if (hash > 0) /* there is only one abbr list */ break; #ifdef FEAT_LOCALMAP if (buf != NULL) mp = buf->b_first_abbr; else #endif mp = first_abbr; } else { #ifdef FEAT_LOCALMAP if (buf != NULL) mp = buf->b_maphash[hash]; else #endif mp = maphash[hash]; } for ( ; mp; mp = mp->m_next) { /* skip script-local mappings */ if (mp->m_noremap == REMAP_SCRIPT) continue; /* skip mappings that contain a <SNR> (script-local thing), * they probably don't work when loaded again */ for (p = mp->m_str; *p != NUL; ++p) if (p[0] == K_SPECIAL && p[1] == KS_EXTRA && p[2] == (int)KE_SNR) break; if (*p != NUL) continue; /* It's possible to create a mapping and then ":unmap" certain * modes. We recreate this here by mapping the individual * modes, which requires up to three of them. */ c1 = NUL; c2 = NUL; c3 = NUL; if (abbr) cmd = "abbr"; else cmd = "map"; switch (mp->m_mode) { case NORMAL + VISUAL + SELECTMODE + OP_PENDING: break; case NORMAL: c1 = 'n'; break; case VISUAL: c1 = 'x'; break; case SELECTMODE: c1 = 's'; break; case OP_PENDING: c1 = 'o'; break; case NORMAL + VISUAL: c1 = 'n'; c2 = 'x'; break; case NORMAL + SELECTMODE: c1 = 'n'; c2 = 's'; break; case NORMAL + OP_PENDING: c1 = 'n'; c2 = 'o'; break; case VISUAL + SELECTMODE: c1 = 'v'; break; case VISUAL + OP_PENDING: c1 = 'x'; c2 = 'o'; break; case SELECTMODE + OP_PENDING: c1 = 's'; c2 = 'o'; break; case NORMAL + VISUAL + SELECTMODE: c1 = 'n'; c2 = 'v'; break; case NORMAL + VISUAL + OP_PENDING: c1 = 'n'; c2 = 'x'; c3 = 'o'; break; case NORMAL + SELECTMODE + OP_PENDING: c1 = 'n'; c2 = 's'; c3 = 'o'; break; case VISUAL + SELECTMODE + OP_PENDING: c1 = 'v'; c2 = 'o'; break; case CMDLINE + INSERT: if (!abbr) cmd = "map!"; break; case CMDLINE: c1 = 'c'; break; case INSERT: c1 = 'i'; break; case LANGMAP: c1 = 'l'; break; default: EMSG(_("E228: makemap: Illegal mode")); return FAIL; } do /* do this twice if c2 is set, 3 times with c3 */ { /* When outputting <> form, need to make sure that 'cpo' * is set to the Vim default. */ if (!did_cpo) { if (*mp->m_str == NUL) /* will use <Nop> */ did_cpo = TRUE; else for (i = 0; i < 2; ++i) for (p = (i ? mp->m_str : mp->m_keys); *p; ++p) if (*p == K_SPECIAL || *p == NL) did_cpo = TRUE; if (did_cpo) { if (fprintf(fd, "let s:cpo_save=&cpo") < 0 || put_eol(fd) < 0 || fprintf(fd, "set cpo&vim") < 0 || put_eol(fd) < 0) return FAIL; } } if (c1 && putc(c1, fd) < 0) return FAIL; if (mp->m_noremap != REMAP_YES && fprintf(fd, "nore") < 0) return FAIL; if (fputs(cmd, fd) < 0) return FAIL; if (buf != NULL && fputs(" <buffer>", fd) < 0) return FAIL; if (mp->m_silent && fputs(" <silent>", fd) < 0) return FAIL; #ifdef FEAT_EVAL if (mp->m_noremap == REMAP_SCRIPT && fputs("<script>", fd) < 0) return FAIL; if (mp->m_expr && fputs(" <expr>", fd) < 0) return FAIL; #endif if ( putc(' ', fd) < 0 || put_escstr(fd, mp->m_keys, 0) == FAIL || putc(' ', fd) < 0 || put_escstr(fd, mp->m_str, 1) == FAIL || put_eol(fd) < 0) return FAIL; c1 = c2; c2 = c3; c3 = NUL; } while (c1 != NUL); } } if (did_cpo) if (fprintf(fd, "let &cpo=s:cpo_save") < 0 || put_eol(fd) < 0 || fprintf(fd, "unlet s:cpo_save") < 0 || put_eol(fd) < 0) return FAIL; return OK; } /* * write escape string to file * "what": 0 for :map lhs, 1 for :map rhs, 2 for :set * * return FAIL for failure, OK otherwise */ int put_escstr(fd, strstart, what) FILE *fd; char_u *strstart; int what; { char_u *str = strstart; int c; int modifiers; /* :map xx <Nop> */ if (*str == NUL && what == 1) { if (fprintf(fd, "<Nop>") < 0) return FAIL; return OK; } for ( ; *str != NUL; ++str) { #ifdef FEAT_MBYTE char_u *p; /* Check for a multi-byte character, which may contain escaped * K_SPECIAL and CSI bytes */ p = mb_unescape(&str); if (p != NULL) { while (*p != NUL) if (fputc(*p++, fd) < 0) return FAIL; --str; continue; } #endif c = *str; /* * Special key codes have to be translated to be able to make sense * when they are read back. */ if (c == K_SPECIAL && what != 2) { modifiers = 0x0; if (str[1] == KS_MODIFIER) { modifiers = str[2]; str += 3; c = *str; } if (c == K_SPECIAL) { c = TO_SPECIAL(str[1], str[2]); str += 2; } if (IS_SPECIAL(c) || modifiers) /* special key */ { if (fputs((char *)get_special_key_name(c, modifiers), fd) < 0) return FAIL; continue; } } /* * A '\n' in a map command should be written as <NL>. * A '\n' in a set command should be written as \^V^J. */ if (c == NL) { if (what == 2) { if (fprintf(fd, IF_EB("\\\026\n", "\\" CTRL_V_STR "\n")) < 0) return FAIL; } else { if (fprintf(fd, "<NL>") < 0) return FAIL; } continue; } /* * Some characters have to be escaped with CTRL-V to * prevent them from misinterpreted in DoOneCmd(). * A space, Tab and '"' has to be escaped with a backslash to * prevent it to be misinterpreted in do_set(). * A space has to be escaped with a CTRL-V when it's at the start of a * ":map" rhs. * A '<' has to be escaped with a CTRL-V to prevent it being * interpreted as the start of a special key name. * A space in the lhs of a :map needs a CTRL-V. */ if (what == 2 && (vim_iswhite(c) || c == '"' || c == '\\')) { if (putc('\\', fd) < 0) return FAIL; } else if (c < ' ' || c > '~' || c == '|' || (what == 0 && c == ' ') || (what == 1 && str == strstart && c == ' ') || (what != 2 && c == '<')) { if (putc(Ctrl_V, fd) < 0) return FAIL; } if (putc(c, fd) < 0) return FAIL; } return OK; } /* * Check all mappings for the presence of special key codes. * Used after ":set term=xxx". */ void check_map_keycodes() { mapblock_T *mp; char_u *p; int i; char_u buf[3]; char_u *save_name; int abbr; int hash; #ifdef FEAT_LOCALMAP buf_T *bp; #endif validate_maphash(); save_name = sourcing_name; sourcing_name = (char_u *)"mappings"; /* avoids giving error messages */ #ifdef FEAT_LOCALMAP /* This this once for each buffer, and then once for global * mappings/abbreviations with bp == NULL */ for (bp = firstbuf; ; bp = bp->b_next) { #endif /* * Do the loop twice: Once for mappings, once for abbreviations. * Then loop over all map hash lists. */ for (abbr = 0; abbr <= 1; ++abbr) for (hash = 0; hash < 256; ++hash) { if (abbr) { if (hash) /* there is only one abbr list */ break; #ifdef FEAT_LOCALMAP if (bp != NULL) mp = bp->b_first_abbr; else #endif mp = first_abbr; } else { #ifdef FEAT_LOCALMAP if (bp != NULL) mp = bp->b_maphash[hash]; else #endif mp = maphash[hash]; } for ( ; mp != NULL; mp = mp->m_next) { for (i = 0; i <= 1; ++i) /* do this twice */ { if (i == 0) p = mp->m_keys; /* once for the "from" part */ else p = mp->m_str; /* and once for the "to" part */ while (*p) { if (*p == K_SPECIAL) { ++p; if (*p < 128) /* for "normal" tcap entries */ { buf[0] = p[0]; buf[1] = p[1]; buf[2] = NUL; (void)add_termcap_entry(buf, FALSE); } ++p; } ++p; } } } } #ifdef FEAT_LOCALMAP if (bp == NULL) break; } #endif sourcing_name = save_name; } #if defined(FEAT_EVAL) || defined(PROTO) /* * Check the string "keys" against the lhs of all mappings. * Return pointer to rhs of mapping (mapblock->m_str). * NULL when no mapping found. */ char_u * check_map(keys, mode, exact, ign_mod, abbr, mp_ptr, local_ptr) char_u *keys; int mode; int exact; /* require exact match */ int ign_mod; /* ignore preceding modifier */ int abbr; /* do abbreviations */ mapblock_T **mp_ptr; /* return: pointer to mapblock or NULL */ int *local_ptr; /* return: buffer-local mapping or NULL */ { int hash; int len, minlen; mapblock_T *mp; char_u *s; #ifdef FEAT_LOCALMAP int local; #endif validate_maphash(); len = (int)STRLEN(keys); #ifdef FEAT_LOCALMAP for (local = 1; local >= 0; --local) #endif /* loop over all hash lists */ for (hash = 0; hash < 256; ++hash) { if (abbr) { if (hash > 0) /* there is only one list. */ break; #ifdef FEAT_LOCALMAP if (local) mp = curbuf->b_first_abbr; else #endif mp = first_abbr; } #ifdef FEAT_LOCALMAP else if (local) mp = curbuf->b_maphash[hash]; #endif else mp = maphash[hash]; for ( ; mp != NULL; mp = mp->m_next) { /* skip entries with wrong mode, wrong length and not matching * ones */ if ((mp->m_mode & mode) && (!exact || mp->m_keylen == len)) { if (len > mp->m_keylen) minlen = mp->m_keylen; else minlen = len; s = mp->m_keys; if (ign_mod && s[0] == K_SPECIAL && s[1] == KS_MODIFIER && s[2] != NUL) { s += 3; if (len > mp->m_keylen - 3) minlen = mp->m_keylen - 3; } if (STRNCMP(s, keys, minlen) == 0) { if (mp_ptr != NULL) *mp_ptr = mp; if (local_ptr != NULL) #ifdef FEAT_LOCALMAP *local_ptr = local; #else *local_ptr = 0; #endif return mp->m_str; } } } } return NULL; } #endif #if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(MACOS) #define VIS_SEL (VISUAL+SELECTMODE) /* abbreviation */ /* * Default mappings for some often used keys. */ static struct initmap { char_u *arg; int mode; } initmappings[] = { #if defined(MSDOS) || defined(MSWIN) || defined(OS2) /* Use the Windows (CUA) keybindings. */ # ifdef FEAT_GUI /* paste, copy and cut */ {(char_u *)"<S-Insert> \"*P", NORMAL}, {(char_u *)"<S-Insert> \"-d\"*P", VIS_SEL}, {(char_u *)"<S-Insert> <C-R><C-O>*", INSERT+CMDLINE}, {(char_u *)"<C-Insert> \"*y", VIS_SEL}, {(char_u *)"<S-Del> \"*d", VIS_SEL}, {(char_u *)"<C-Del> \"*d", VIS_SEL}, {(char_u *)"<C-X> \"*d", VIS_SEL}, /* Missing: CTRL-C (cancel) and CTRL-V (block selection) */ # else {(char_u *)"\316w <C-Home>", NORMAL+VIS_SEL}, {(char_u *)"\316w <C-Home>", INSERT+CMDLINE}, {(char_u *)"\316u <C-End>", NORMAL+VIS_SEL}, {(char_u *)"\316u <C-End>", INSERT+CMDLINE}, /* paste, copy and cut */ # ifdef FEAT_CLIPBOARD # ifdef DJGPP {(char_u *)"\316\122 \"*P", NORMAL}, /* SHIFT-Insert is "*P */ {(char_u *)"\316\122 \"-d\"*P", VIS_SEL}, /* SHIFT-Insert is "-d"*P */ {(char_u *)"\316\122 \022\017*", INSERT}, /* SHIFT-Insert is ^R^O* */ {(char_u *)"\316\222 \"*y", VIS_SEL}, /* CTRL-Insert is "*y */ # if 0 /* Shift-Del produces the same code as Del */ {(char_u *)"\316\123 \"*d", VIS_SEL}, /* SHIFT-Del is "*d */ # endif {(char_u *)"\316\223 \"*d", VIS_SEL}, /* CTRL-Del is "*d */ {(char_u *)"\030 \"-d", VIS_SEL}, /* CTRL-X is "-d */ # else {(char_u *)"\316\324 \"*P", NORMAL}, /* SHIFT-Insert is "*P */ {(char_u *)"\316\324 \"-d\"*P", VIS_SEL}, /* SHIFT-Insert is "-d"*P */ {(char_u *)"\316\324 \022\017*", INSERT}, /* SHIFT-Insert is ^R^O* */ {(char_u *)"\316\325 \"*y", VIS_SEL}, /* CTRL-Insert is "*y */ {(char_u *)"\316\327 \"*d", VIS_SEL}, /* SHIFT-Del is "*d */ {(char_u *)"\316\330 \"*d", VIS_SEL}, /* CTRL-Del is "*d */ {(char_u *)"\030 \"-d", VIS_SEL}, /* CTRL-X is "-d */ # endif # else {(char_u *)"\316\324 P", NORMAL}, /* SHIFT-Insert is P */ {(char_u *)"\316\324 \"-dP", VIS_SEL}, /* SHIFT-Insert is "-dP */ {(char_u *)"\316\324 \022\017\"", INSERT}, /* SHIFT-Insert is ^R^O" */ {(char_u *)"\316\325 y", VIS_SEL}, /* CTRL-Insert is y */ {(char_u *)"\316\327 d", VIS_SEL}, /* SHIFT-Del is d */ {(char_u *)"\316\330 d", VIS_SEL}, /* CTRL-Del is d */ # endif # endif #endif #if defined(MACOS) /* Use the Standard MacOS binding. */ /* paste, copy and cut */ {(char_u *)"<D-v> \"*P", NORMAL}, {(char_u *)"<D-v> \"-d\"*P", VIS_SEL}, {(char_u *)"<D-v> <C-R>*", INSERT+CMDLINE}, {(char_u *)"<D-c> \"*y", VIS_SEL}, {(char_u *)"<D-x> \"*d", VIS_SEL}, {(char_u *)"<Backspace> \"-d", VIS_SEL}, #endif }; # undef VIS_SEL #endif /* * Set up default mappings. */ void init_mappings() { #if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(MACOS) int i; for (i = 0; i < sizeof(initmappings) / sizeof(struct initmap); ++i) add_map(initmappings[i].arg, initmappings[i].mode); #endif } #if defined(MSDOS) || defined(MSWIN) || defined(OS2) \ || defined(FEAT_CMDWIN) || defined(MACOS) || defined(PROTO) /* * Add a mapping "map" for mode "mode". * Need to put string in allocated memory, because do_map() will modify it. */ void add_map(map, mode) char_u *map; int mode; { char_u *s; char_u *cpo_save = p_cpo; p_cpo = (char_u *)""; /* Allow <> notation */ s = vim_strsave(map); if (s != NULL) { (void)do_map(0, s, mode, FALSE); vim_free(s); } p_cpo = cpo_save; } #endif
zyz2011-vim
src/getchar.c
C
gpl2
125,936
#! /bin/sh # # pathdef.sh: adjust pathdef.c for auto/link.sed, if it exists # if test -s auto/link.sed; then cp auto/pathdef.c auto/pathdef.tmp sed -f auto/link.sed <auto/pathdef.tmp >auto/pathdef.c rm -f auto/pathdef.tmp fi # vim:set sw=2 et:
zyz2011-vim
src/pathdef.sh
Shell
gpl2
251
/* vi:set ts=8 sts=4 sw=4: * * CSCOPE support for Vim added by Andy Kahn <kahn@zk3.dec.com> * Ported to Win32 by Sergey Khorev <sergey.khorev@gmail.com> * * The basic idea/structure of cscope for Vim was borrowed from Nvi. * There might be a few lines of code that look similar to what Nvi * has. If this is a problem and requires inclusion of the annoying * BSD license, then sue me; I'm not worth much anyway. */ #if defined(FEAT_CSCOPE) || defined(PROTO) #if defined(UNIX) # include <sys/types.h> /* pid_t */ # include <sys/stat.h> /* dev_t, ino_t */ #else # if defined (WIN32) # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # include <windows.h> # endif #endif #define CSCOPE_SUCCESS 0 #define CSCOPE_FAILURE -1 #define CSCOPE_DBFILE "cscope.out" #define CSCOPE_PROMPT ">> " /* * s 0name Find this C symbol * g 1name Find this definition * d 2name Find functions called by this function * c 3name Find functions calling this function * t 4string find text string (cscope 12.9) * t 4name Find assignments to (cscope 13.3) * 5pattern change pattern -- NOT USED * e 6pattern Find this egrep pattern * f 7name Find this file * i 8name Find files #including this file */ typedef struct { char * name; int (*func) __ARGS((exarg_T *eap)); char * help; char * usage; int cansplit; /* if supports splitting window */ } cscmd_T; typedef struct csi { char * fname; /* cscope db name */ char * ppath; /* path to prepend (the -P option) */ char * flags; /* additional cscope flags/options (e.g, -p2) */ #if defined(UNIX) pid_t pid; /* PID of the connected cscope process. */ dev_t st_dev; /* ID of dev containing cscope db */ ino_t st_ino; /* inode number of cscope db */ #else # if defined(WIN32) DWORD pid; /* PID of the connected cscope process. */ HANDLE hProc; /* cscope process handle */ DWORD nVolume; /* Volume serial number, instead of st_dev */ DWORD nIndexHigh; /* st_ino has no meaning in the Windows */ DWORD nIndexLow; # endif #endif FILE * fr_fp; /* from cscope: FILE. */ FILE * to_fp; /* to cscope: FILE. */ } csinfo_T; typedef enum { Add, Find, Help, Kill, Reset, Show } csid_e; typedef enum { Store, Get, Free, Print } mcmd_e; #endif /* FEAT_CSCOPE */ /* the end */
zyz2011-vim
src/if_cscope.h
C
gpl2
2,393
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * Visual Workshop integration by Gordon Prieur * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ #include "vim.h" #if defined(FEAT_BEVAL) || defined(PROTO) /* * Common code, invoked when the mouse is resting for a moment. */ void general_beval_cb(beval, state) BalloonEval *beval; int state UNUSED; { #ifdef FEAT_EVAL win_T *wp; int col; int use_sandbox; linenr_T lnum; char_u *text; static char_u *result = NULL; long winnr = 0; char_u *bexpr; buf_T *save_curbuf; # ifdef FEAT_WINDOWS win_T *cw; # endif #endif static int recursive = FALSE; /* Don't do anything when 'ballooneval' is off, messages scrolled the * windows up or we have no beval area. */ if (!p_beval || balloonEval == NULL || msg_scrolled > 0) return; /* Don't do this recursively. Happens when the expression evaluation * takes a long time and invokes something that checks for CTRL-C typed. */ if (recursive) return; recursive = TRUE; #ifdef FEAT_EVAL if (get_beval_info(balloonEval, TRUE, &wp, &lnum, &text, &col) == OK) { bexpr = (*wp->w_buffer->b_p_bexpr == NUL) ? p_bexpr : wp->w_buffer->b_p_bexpr; if (*bexpr != NUL) { # ifdef FEAT_WINDOWS /* Convert window pointer to number. */ for (cw = firstwin; cw != wp; cw = cw->w_next) ++winnr; # endif set_vim_var_nr(VV_BEVAL_BUFNR, (long)wp->w_buffer->b_fnum); set_vim_var_nr(VV_BEVAL_WINNR, winnr); set_vim_var_nr(VV_BEVAL_LNUM, (long)lnum); set_vim_var_nr(VV_BEVAL_COL, (long)(col + 1)); set_vim_var_string(VV_BEVAL_TEXT, text, -1); vim_free(text); /* * Temporarily change the curbuf, so that we can determine whether * the buffer-local balloonexpr option was set insecurely. */ save_curbuf = curbuf; curbuf = wp->w_buffer; use_sandbox = was_set_insecurely((char_u *)"balloonexpr", *curbuf->b_p_bexpr == NUL ? 0 : OPT_LOCAL); curbuf = save_curbuf; if (use_sandbox) ++sandbox; ++textlock; vim_free(result); result = eval_to_string(bexpr, NULL, TRUE); if (use_sandbox) --sandbox; --textlock; set_vim_var_string(VV_BEVAL_TEXT, NULL, -1); if (result != NULL && result[0] != NUL) { gui_mch_post_balloon(beval, result); recursive = FALSE; return; } } } #endif #ifdef FEAT_NETBEANS_INTG if (bevalServers & BEVAL_NETBEANS) netbeans_beval_cb(beval, state); #endif #ifdef FEAT_SUN_WORKSHOP if (bevalServers & BEVAL_WORKSHOP) workshop_beval_cb(beval, state); #endif recursive = FALSE; } /* on Win32 only get_beval_info() is required */ #if !defined(FEAT_GUI_W32) || defined(PROTO) #ifdef FEAT_GUI_GTK # include <gdk/gdkkeysyms.h> # include <gtk/gtk.h> #else # include <X11/keysym.h> # ifdef FEAT_GUI_MOTIF # include <Xm/PushB.h> # include <Xm/Separator.h> # include <Xm/List.h> # include <Xm/Label.h> # include <Xm/AtomMgr.h> # include <Xm/Protocols.h> # else /* Assume Athena */ # include <X11/Shell.h> # ifdef FEAT_GUI_NEXTAW # include <X11/neXtaw/Label.h> # else # include <X11/Xaw/Label.h> # endif # endif #endif #include "gui_beval.h" #ifndef FEAT_GUI_GTK extern Widget vimShell; /* * Currently, we assume that there can be only one BalloonEval showing * on-screen at any given moment. This variable will hold the currently * showing BalloonEval or NULL if none is showing. */ static BalloonEval *current_beval = NULL; #endif #ifdef FEAT_GUI_GTK static void addEventHandler __ARGS((GtkWidget *, BalloonEval *)); static void removeEventHandler __ARGS((BalloonEval *)); static gint target_event_cb __ARGS((GtkWidget *, GdkEvent *, gpointer)); static gint mainwin_event_cb __ARGS((GtkWidget *, GdkEvent *, gpointer)); static void pointer_event __ARGS((BalloonEval *, int, int, unsigned)); static void key_event __ARGS((BalloonEval *, unsigned, int)); static gint timeout_cb __ARGS((gpointer)); static gint balloon_expose_event_cb __ARGS((GtkWidget *, GdkEventExpose *, gpointer)); #else static void addEventHandler __ARGS((Widget, BalloonEval *)); static void removeEventHandler __ARGS((BalloonEval *)); static void pointerEventEH __ARGS((Widget, XtPointer, XEvent *, Boolean *)); static void pointerEvent __ARGS((BalloonEval *, XEvent *)); static void timerRoutine __ARGS((XtPointer, XtIntervalId *)); #endif static void cancelBalloon __ARGS((BalloonEval *)); static void requestBalloon __ARGS((BalloonEval *)); static void drawBalloon __ARGS((BalloonEval *)); static void undrawBalloon __ARGS((BalloonEval *beval)); static void createBalloonEvalWindow __ARGS((BalloonEval *)); /* * Create a balloon-evaluation area for a Widget. * There can be either a "mesg" for a fixed string or "mesgCB" to generate a * message by calling this callback function. * When "mesg" is not NULL it must remain valid for as long as the balloon is * used. It is not freed here. * Returns a pointer to the resulting object (NULL when out of memory). */ BalloonEval * gui_mch_create_beval_area(target, mesg, mesgCB, clientData) void *target; char_u *mesg; void (*mesgCB)__ARGS((BalloonEval *, int)); void *clientData; { #ifndef FEAT_GUI_GTK char *display_name; /* get from gui.dpy */ int screen_num; char *p; #endif BalloonEval *beval; if (mesg != NULL && mesgCB != NULL) { EMSG(_("E232: Cannot create BalloonEval with both message and callback")); return NULL; } beval = (BalloonEval *)alloc(sizeof(BalloonEval)); if (beval != NULL) { #ifdef FEAT_GUI_GTK beval->target = GTK_WIDGET(target); beval->balloonShell = NULL; beval->timerID = 0; #else beval->target = (Widget)target; beval->balloonShell = NULL; beval->timerID = (XtIntervalId)NULL; beval->appContext = XtWidgetToApplicationContext((Widget)target); #endif beval->showState = ShS_NEUTRAL; beval->x = 0; beval->y = 0; beval->msg = mesg; beval->msgCB = mesgCB; beval->clientData = clientData; /* * Set up event handler which will keep its eyes on the pointer, * and when the pointer rests in a certain spot for a given time * interval, show the beval. */ addEventHandler(beval->target, beval); createBalloonEvalWindow(beval); #ifndef FEAT_GUI_GTK /* * Now create and save the screen width and height. Used in drawing. */ display_name = DisplayString(gui.dpy); p = strrchr(display_name, '.'); if (p != NULL) screen_num = atoi(++p); else screen_num = 0; beval->screen_width = DisplayWidth(gui.dpy, screen_num); beval->screen_height = DisplayHeight(gui.dpy, screen_num); #endif } return beval; } #if defined(FEAT_BEVAL_TIP) || defined(PROTO) /* * Destroy a balloon-eval and free its associated memory. */ void gui_mch_destroy_beval_area(beval) BalloonEval *beval; { cancelBalloon(beval); removeEventHandler(beval); /* Children will automatically be destroyed */ # ifdef FEAT_GUI_GTK gtk_widget_destroy(beval->balloonShell); # else XtDestroyWidget(beval->balloonShell); # endif vim_free(beval); } #endif void gui_mch_enable_beval_area(beval) BalloonEval *beval; { if (beval != NULL) addEventHandler(beval->target, beval); } void gui_mch_disable_beval_area(beval) BalloonEval *beval; { if (beval != NULL) removeEventHandler(beval); } #if defined(FEAT_BEVAL_TIP) || defined(PROTO) /* * This function returns the BalloonEval * associated with the currently * displayed tooltip. Returns NULL if there is no tooltip currently showing. * * Assumption: Only one tooltip can be shown at a time. */ BalloonEval * gui_mch_currently_showing_beval() { return current_beval; } #endif #endif /* !FEAT_GUI_W32 */ #if defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG) \ || defined(FEAT_EVAL) || defined(PROTO) /* * Get the text and position to be evaluated for "beval". * If "getword" is true the returned text is not the whole line but the * relevant word in allocated memory. * Returns OK or FAIL. */ int get_beval_info(beval, getword, winp, lnump, textp, colp) BalloonEval *beval; int getword; win_T **winp; linenr_T *lnump; char_u **textp; int *colp; { win_T *wp; int row, col; char_u *lbuf; linenr_T lnum; *textp = NULL; row = Y_2_ROW(beval->y); col = X_2_COL(beval->x); #ifdef FEAT_WINDOWS wp = mouse_find_win(&row, &col); #else wp = firstwin; #endif if (wp != NULL && row < wp->w_height && col < W_WIDTH(wp)) { /* Found a window and the cursor is in the text. Now find the line * number. */ if (!mouse_comp_pos(wp, &row, &col, &lnum)) { /* Not past end of the file. */ lbuf = ml_get_buf(wp->w_buffer, lnum, FALSE); if (col <= win_linetabsize(wp, lbuf, (colnr_T)MAXCOL)) { /* Not past end of line. */ if (getword) { /* For Netbeans we get the relevant part of the line * instead of the whole line. */ int len; pos_T *spos = NULL, *epos = NULL; if (VIsual_active) { if (lt(VIsual, curwin->w_cursor)) { spos = &VIsual; epos = &curwin->w_cursor; } else { spos = &curwin->w_cursor; epos = &VIsual; } } col = vcol2col(wp, lnum, col) - 1; if (VIsual_active && wp->w_buffer == curwin->w_buffer && (lnum == spos->lnum ? col >= (int)spos->col : lnum > spos->lnum) && (lnum == epos->lnum ? col <= (int)epos->col : lnum < epos->lnum)) { /* Visual mode and pointing to the line with the * Visual selection: return selected text, with a * maximum of one line. */ if (spos->lnum != epos->lnum || spos->col == epos->col) return FAIL; lbuf = ml_get_buf(curwin->w_buffer, VIsual.lnum, FALSE); lbuf = vim_strnsave(lbuf + spos->col, epos->col - spos->col + (*p_sel != 'e')); lnum = spos->lnum; col = spos->col; } else { /* Find the word under the cursor. */ ++emsg_off; len = find_ident_at_pos(wp, lnum, (colnr_T)col, &lbuf, FIND_IDENT + FIND_STRING + FIND_EVAL); --emsg_off; if (len == 0) return FAIL; lbuf = vim_strnsave(lbuf, len); } } *winp = wp; *lnump = lnum; *textp = lbuf; *colp = col; beval->ts = wp->w_buffer->b_p_ts; return OK; } } } return FAIL; } # if !defined(FEAT_GUI_W32) || defined(PROTO) /* * Show a balloon with "mesg". */ void gui_mch_post_balloon(beval, mesg) BalloonEval *beval; char_u *mesg; { beval->msg = mesg; if (mesg != NULL) drawBalloon(beval); else undrawBalloon(beval); } # endif /* FEAT_GUI_W32 */ #endif /* FEAT_SUN_WORKSHOP || FEAT_NETBEANS_INTG || PROTO */ #if !defined(FEAT_GUI_W32) || defined(PROTO) #if defined(FEAT_BEVAL_TIP) || defined(PROTO) /* * Hide the given balloon. */ void gui_mch_unpost_balloon(beval) BalloonEval *beval; { undrawBalloon(beval); } #endif #ifdef FEAT_GUI_GTK /* * We can unconditionally use ANSI-style prototypes here since * GTK+ requires an ANSI C compiler anyway. */ static void addEventHandler(GtkWidget *target, BalloonEval *beval) { /* * Connect to the generic "event" signal instead of the individual * signals for each event type, because the former is emitted earlier. * This allows us to catch events independently of the signal handlers * in gui_gtk_x11.c. */ /* Should use GTK_OBJECT() here, but that causes a lint warning... */ gtk_signal_connect((GtkObject*)(target), "event", GTK_SIGNAL_FUNC(target_event_cb), beval); /* * Nasty: Key press events go to the main window thus the drawing area * will never see them. This means we have to connect to the main window * as well in order to catch those events. */ if (gtk_socket_id == 0 && gui.mainwin != NULL && gtk_widget_is_ancestor(target, gui.mainwin)) { gtk_signal_connect((GtkObject*)(gui.mainwin), "event", GTK_SIGNAL_FUNC(mainwin_event_cb), beval); } } static void removeEventHandler(BalloonEval *beval) { /* LINTED: avoid warning: dubious operation on enum */ gtk_signal_disconnect_by_func((GtkObject*)(beval->target), GTK_SIGNAL_FUNC(target_event_cb), beval); if (gtk_socket_id == 0 && gui.mainwin != NULL && gtk_widget_is_ancestor(beval->target, gui.mainwin)) { /* LINTED: avoid warning: dubious operation on enum */ gtk_signal_disconnect_by_func((GtkObject*)(gui.mainwin), GTK_SIGNAL_FUNC(mainwin_event_cb), beval); } } static gint target_event_cb(GtkWidget *widget, GdkEvent *event, gpointer data) { BalloonEval *beval = (BalloonEval *)data; switch (event->type) { case GDK_ENTER_NOTIFY: pointer_event(beval, (int)event->crossing.x, (int)event->crossing.y, event->crossing.state); break; case GDK_MOTION_NOTIFY: if (event->motion.is_hint) { int x; int y; GdkModifierType state; /* * GDK_POINTER_MOTION_HINT_MASK is set, thus we cannot obtain * the coordinates from the GdkEventMotion struct directly. */ gdk_window_get_pointer(widget->window, &x, &y, &state); pointer_event(beval, x, y, (unsigned int)state); } else { pointer_event(beval, (int)event->motion.x, (int)event->motion.y, event->motion.state); } break; case GDK_LEAVE_NOTIFY: /* * Ignore LeaveNotify events that are not "normal". * Apparently we also get it when somebody else grabs focus. */ if (event->crossing.mode == GDK_CROSSING_NORMAL) cancelBalloon(beval); break; case GDK_BUTTON_PRESS: case GDK_SCROLL: cancelBalloon(beval); break; case GDK_KEY_PRESS: key_event(beval, event->key.keyval, TRUE); break; case GDK_KEY_RELEASE: key_event(beval, event->key.keyval, FALSE); break; default: break; } return FALSE; /* continue emission */ } static gint mainwin_event_cb(GtkWidget *widget UNUSED, GdkEvent *event, gpointer data) { BalloonEval *beval = (BalloonEval *)data; switch (event->type) { case GDK_KEY_PRESS: key_event(beval, event->key.keyval, TRUE); break; case GDK_KEY_RELEASE: key_event(beval, event->key.keyval, FALSE); break; default: break; } return FALSE; /* continue emission */ } static void pointer_event(BalloonEval *beval, int x, int y, unsigned state) { int distance; distance = ABS(x - beval->x) + ABS(y - beval->y); if (distance > 4) { /* * Moved out of the balloon location: cancel it. * Remember button state */ beval->state = state; cancelBalloon(beval); /* Mouse buttons are pressed - no balloon now */ if (!(state & ((int)GDK_BUTTON1_MASK | (int)GDK_BUTTON2_MASK | (int)GDK_BUTTON3_MASK))) { beval->x = x; beval->y = y; if (state & (int)GDK_MOD1_MASK) { /* * Alt is pressed -- enter super-evaluate-mode, * where there is no time delay */ if (beval->msgCB != NULL) { beval->showState = ShS_PENDING; (*beval->msgCB)(beval, state); } } else { beval->timerID = gtk_timeout_add((guint32)p_bdlay, &timeout_cb, beval); } } } } static void key_event(BalloonEval *beval, unsigned keyval, int is_keypress) { if (beval->showState == ShS_SHOWING && beval->msgCB != NULL) { switch (keyval) { case GDK_Shift_L: case GDK_Shift_R: beval->showState = ShS_UPDATE_PENDING; (*beval->msgCB)(beval, (is_keypress) ? (int)GDK_SHIFT_MASK : 0); break; case GDK_Control_L: case GDK_Control_R: beval->showState = ShS_UPDATE_PENDING; (*beval->msgCB)(beval, (is_keypress) ? (int)GDK_CONTROL_MASK : 0); break; default: /* Don't do this for key release, we apparently get these with * focus changes in some GTK version. */ if (is_keypress) cancelBalloon(beval); break; } } else cancelBalloon(beval); } static gint timeout_cb(gpointer data) { BalloonEval *beval = (BalloonEval *)data; beval->timerID = 0; /* * If the timer event happens then the mouse has stopped long enough for * a request to be started. The request will only send to the debugger if * there the mouse is pointing at real data. */ requestBalloon(beval); return FALSE; /* don't call me again */ } static gint balloon_expose_event_cb(GtkWidget *widget, GdkEventExpose *event, gpointer data UNUSED) { gtk_paint_flat_box(widget->style, widget->window, GTK_STATE_NORMAL, GTK_SHADOW_OUT, &event->area, widget, "tooltip", 0, 0, -1, -1); return FALSE; /* continue emission */ } #else /* !FEAT_GUI_GTK */ static void addEventHandler(target, beval) Widget target; BalloonEval *beval; { XtAddEventHandler(target, PointerMotionMask | EnterWindowMask | LeaveWindowMask | ButtonPressMask | KeyPressMask | KeyReleaseMask, False, pointerEventEH, (XtPointer)beval); } static void removeEventHandler(beval) BalloonEval *beval; { XtRemoveEventHandler(beval->target, PointerMotionMask | EnterWindowMask | LeaveWindowMask | ButtonPressMask | KeyPressMask | KeyReleaseMask, False, pointerEventEH, (XtPointer)beval); } /* * The X event handler. All it does is call the real event handler. */ static void pointerEventEH(w, client_data, event, unused) Widget w UNUSED; XtPointer client_data; XEvent *event; Boolean *unused UNUSED; { BalloonEval *beval = (BalloonEval *)client_data; pointerEvent(beval, event); } /* * The real event handler. Called by pointerEventEH() whenever an event we are * interested in occurs. */ static void pointerEvent(beval, event) BalloonEval *beval; XEvent *event; { Position distance; /* a measure of how much the ponter moved */ Position delta; /* used to compute distance */ switch (event->type) { case EnterNotify: case MotionNotify: delta = event->xmotion.x - beval->x; if (delta < 0) delta = -delta; distance = delta; delta = event->xmotion.y - beval->y; if (delta < 0) delta = -delta; distance += delta; if (distance > 4) { /* * Moved out of the balloon location: cancel it. * Remember button state */ beval->state = event->xmotion.state; if (beval->state & (Button1Mask|Button2Mask|Button3Mask)) { /* Mouse buttons are pressed - no balloon now */ cancelBalloon(beval); } else if (beval->state & (Mod1Mask|Mod2Mask|Mod3Mask)) { /* * Alt is pressed -- enter super-evaluate-mode, * where there is no time delay */ beval->x = event->xmotion.x; beval->y = event->xmotion.y; beval->x_root = event->xmotion.x_root; beval->y_root = event->xmotion.y_root; cancelBalloon(beval); if (beval->msgCB != NULL) { beval->showState = ShS_PENDING; (*beval->msgCB)(beval, beval->state); } } else { beval->x = event->xmotion.x; beval->y = event->xmotion.y; beval->x_root = event->xmotion.x_root; beval->y_root = event->xmotion.y_root; cancelBalloon(beval); beval->timerID = XtAppAddTimeOut( beval->appContext, (long_u)p_bdlay, timerRoutine, beval); } } break; /* * Motif and Athena version: Keystrokes will be caught by the * "textArea" widget, and handled in gui_x11_key_hit_cb(). */ case KeyPress: if (beval->showState == ShS_SHOWING && beval->msgCB != NULL) { Modifiers modifier; KeySym keysym; XtTranslateKeycode(gui.dpy, event->xkey.keycode, event->xkey.state, &modifier, &keysym); if (keysym == XK_Shift_L || keysym == XK_Shift_R) { beval->showState = ShS_UPDATE_PENDING; (*beval->msgCB)(beval, ShiftMask); } else if (keysym == XK_Control_L || keysym == XK_Control_R) { beval->showState = ShS_UPDATE_PENDING; (*beval->msgCB)(beval, ControlMask); } else cancelBalloon(beval); } else cancelBalloon(beval); break; case KeyRelease: if (beval->showState == ShS_SHOWING && beval->msgCB != NULL) { Modifiers modifier; KeySym keysym; XtTranslateKeycode(gui.dpy, event->xkey.keycode, event->xkey.state, &modifier, &keysym); if ((keysym == XK_Shift_L) || (keysym == XK_Shift_R)) { beval->showState = ShS_UPDATE_PENDING; (*beval->msgCB)(beval, 0); } else if ((keysym == XK_Control_L) || (keysym == XK_Control_R)) { beval->showState = ShS_UPDATE_PENDING; (*beval->msgCB)(beval, 0); } else cancelBalloon(beval); } else cancelBalloon(beval); break; case LeaveNotify: /* Ignore LeaveNotify events that are not "normal". * Apparently we also get it when somebody else grabs focus. * Happens for me every two seconds (some clipboard tool?) */ if (event->xcrossing.mode == NotifyNormal) cancelBalloon(beval); break; case ButtonPress: cancelBalloon(beval); break; default: break; } } static void timerRoutine(dx, id) XtPointer dx; XtIntervalId *id UNUSED; { BalloonEval *beval = (BalloonEval *)dx; beval->timerID = (XtIntervalId)NULL; /* * If the timer event happens then the mouse has stopped long enough for * a request to be started. The request will only send to the debugger if * there the mouse is pointing at real data. */ requestBalloon(beval); } #endif /* !FEAT_GUI_GTK */ static void requestBalloon(beval) BalloonEval *beval; { if (beval->showState != ShS_PENDING) { /* Determine the beval to display */ if (beval->msgCB != NULL) { beval->showState = ShS_PENDING; (*beval->msgCB)(beval, beval->state); } else if (beval->msg != NULL) drawBalloon(beval); } } #ifdef FEAT_GUI_GTK /* * Convert the string to UTF-8 if 'encoding' is not "utf-8". * Replace any non-printable characters and invalid bytes sequences with * "^X" or "<xx>" escapes, and apply SpecialKey highlighting to them. * TAB and NL are passed through unscathed. */ # define IS_NONPRINTABLE(c) (((c) < 0x20 && (c) != TAB && (c) != NL) \ || (c) == DEL) static void set_printable_label_text(GtkLabel *label, char_u *text) { char_u *convbuf = NULL; char_u *buf; char_u *p; char_u *pdest; unsigned int len; int charlen; int uc; PangoAttrList *attr_list; /* Convert to UTF-8 if it isn't already */ if (output_conv.vc_type != CONV_NONE) { convbuf = string_convert(&output_conv, text, NULL); if (convbuf != NULL) text = convbuf; } /* First let's see how much we need to allocate */ len = 0; for (p = text; *p != NUL; p += charlen) { if ((*p & 0x80) == 0) /* be quick for ASCII */ { charlen = 1; len += IS_NONPRINTABLE(*p) ? 2 : 1; /* nonprintable: ^X */ } else { charlen = utf_ptr2len(p); uc = utf_ptr2char(p); if (charlen != utf_char2len(uc)) charlen = 1; /* reject overlong sequences */ if (charlen == 1 || uc < 0xa0) /* illegal byte or */ len += 4; /* control char: <xx> */ else if (!utf_printable(uc)) /* Note: we assume here that utf_printable() doesn't * care about characters outside the BMP. */ len += 6; /* nonprintable: <xxxx> */ else len += charlen; } } attr_list = pango_attr_list_new(); buf = alloc(len + 1); /* Now go for the real work */ if (buf != NULL) { attrentry_T *aep; PangoAttribute *attr; guicolor_T pixel; GdkColor color = { 0, 0, 0, 0 }; /* Look up the RGB values of the SpecialKey foreground color. */ aep = syn_gui_attr2entry(hl_attr(HLF_8)); pixel = (aep != NULL) ? aep->ae_u.gui.fg_color : INVALCOLOR; if (pixel != INVALCOLOR) gdk_colormap_query_color(gtk_widget_get_colormap(gui.drawarea), (unsigned long)pixel, &color); pdest = buf; p = text; while (*p != NUL) { /* Be quick for ASCII */ if ((*p & 0x80) == 0 && !IS_NONPRINTABLE(*p)) { *pdest++ = *p++; } else { charlen = utf_ptr2len(p); uc = utf_ptr2char(p); if (charlen != utf_char2len(uc)) charlen = 1; /* reject overlong sequences */ if (charlen == 1 || uc < 0xa0 || !utf_printable(uc)) { int outlen; /* Careful: we can't just use transchar_byte() here, * since 'encoding' is not necessarily set to "utf-8". */ if (*p & 0x80 && charlen == 1) { transchar_hex(pdest, *p); /* <xx> */ outlen = 4; } else if (uc >= 0x80) { /* Note: we assume here that utf_printable() doesn't * care about characters outside the BMP. */ transchar_hex(pdest, uc); /* <xx> or <xxxx> */ outlen = (uc < 0x100) ? 4 : 6; } else { transchar_nonprint(pdest, *p); /* ^X */ outlen = 2; } if (pixel != INVALCOLOR) { attr = pango_attr_foreground_new( color.red, color.green, color.blue); attr->start_index = pdest - buf; attr->end_index = pdest - buf + outlen; pango_attr_list_insert(attr_list, attr); } pdest += outlen; p += charlen; } else { do *pdest++ = *p++; while (--charlen != 0); } } } *pdest = NUL; } vim_free(convbuf); gtk_label_set_text(label, (const char *)buf); vim_free(buf); gtk_label_set_attributes(label, attr_list); pango_attr_list_unref(attr_list); } # undef IS_NONPRINTABLE /* * Draw a balloon. */ static void drawBalloon(BalloonEval *beval) { if (beval->msg != NULL) { GtkRequisition requisition; int screen_w; int screen_h; int x; int y; int x_offset = EVAL_OFFSET_X; int y_offset = EVAL_OFFSET_Y; PangoLayout *layout; # ifdef HAVE_GTK_MULTIHEAD GdkScreen *screen; screen = gtk_widget_get_screen(beval->target); gtk_window_set_screen(GTK_WINDOW(beval->balloonShell), screen); screen_w = gdk_screen_get_width(screen); screen_h = gdk_screen_get_height(screen); # else screen_w = gdk_screen_width(); screen_h = gdk_screen_height(); # endif gtk_widget_ensure_style(beval->balloonShell); gtk_widget_ensure_style(beval->balloonLabel); set_printable_label_text(GTK_LABEL(beval->balloonLabel), beval->msg); /* * Dirty trick: Enable wrapping mode on the label's layout behind its * back. This way GtkLabel won't try to constrain the wrap width to a * builtin maximum value of about 65 Latin characters. */ layout = gtk_label_get_layout(GTK_LABEL(beval->balloonLabel)); # ifdef PANGO_WRAP_WORD_CHAR pango_layout_set_wrap(layout, PANGO_WRAP_WORD_CHAR); # else pango_layout_set_wrap(layout, PANGO_WRAP_WORD); # endif pango_layout_set_width(layout, /* try to come up with some reasonable width */ PANGO_SCALE * CLAMP(gui.num_cols * gui.char_width, screen_w / 2, MAX(20, screen_w - 20))); /* Calculate the balloon's width and height. */ gtk_widget_size_request(beval->balloonShell, &requisition); /* Compute position of the balloon area */ gdk_window_get_origin(beval->target->window, &x, &y); x += beval->x; y += beval->y; /* Get out of the way of the mouse pointer */ if (x + x_offset + requisition.width > screen_w) y_offset += 15; if (y + y_offset + requisition.height > screen_h) y_offset = -requisition.height - EVAL_OFFSET_Y; /* Sanitize values */ x = CLAMP(x + x_offset, 0, MAX(0, screen_w - requisition.width)); y = CLAMP(y + y_offset, 0, MAX(0, screen_h - requisition.height)); /* Show the balloon */ gtk_widget_set_uposition(beval->balloonShell, x, y); gtk_widget_show(beval->balloonShell); beval->showState = ShS_SHOWING; } } /* * Undraw a balloon. */ static void undrawBalloon(BalloonEval *beval) { if (beval->balloonShell != NULL) gtk_widget_hide(beval->balloonShell); beval->showState = ShS_NEUTRAL; } static void cancelBalloon(BalloonEval *beval) { if (beval->showState == ShS_SHOWING || beval->showState == ShS_UPDATE_PENDING) undrawBalloon(beval); if (beval->timerID != 0) { gtk_timeout_remove(beval->timerID); beval->timerID = 0; } beval->showState = ShS_NEUTRAL; } static void createBalloonEvalWindow(BalloonEval *beval) { beval->balloonShell = gtk_window_new(GTK_WINDOW_POPUP); gtk_widget_set_app_paintable(beval->balloonShell, TRUE); gtk_window_set_policy(GTK_WINDOW(beval->balloonShell), FALSE, FALSE, TRUE); gtk_widget_set_name(beval->balloonShell, "gtk-tooltips"); gtk_container_border_width(GTK_CONTAINER(beval->balloonShell), 4); gtk_signal_connect((GtkObject*)(beval->balloonShell), "expose_event", GTK_SIGNAL_FUNC(balloon_expose_event_cb), NULL); beval->balloonLabel = gtk_label_new(NULL); gtk_label_set_line_wrap(GTK_LABEL(beval->balloonLabel), FALSE); gtk_label_set_justify(GTK_LABEL(beval->balloonLabel), GTK_JUSTIFY_LEFT); gtk_misc_set_alignment(GTK_MISC(beval->balloonLabel), 0.5f, 0.5f); gtk_widget_set_name(beval->balloonLabel, "vim-balloon-label"); gtk_widget_show(beval->balloonLabel); gtk_container_add(GTK_CONTAINER(beval->balloonShell), beval->balloonLabel); } #else /* !FEAT_GUI_GTK */ /* * Draw a balloon. */ static void drawBalloon(beval) BalloonEval *beval; { Dimension w; Dimension h; Position tx; Position ty; if (beval->msg != NULL) { /* Show the Balloon */ /* Calculate the label's width and height */ #ifdef FEAT_GUI_MOTIF XmString s; /* For the callback function we parse NL characters to create a * multi-line label. This doesn't work for all languages, but * XmStringCreateLocalized() doesn't do multi-line labels... */ if (beval->msgCB != NULL) s = XmStringCreateLtoR((char *)beval->msg, XmFONTLIST_DEFAULT_TAG); else s = XmStringCreateLocalized((char *)beval->msg); { XmFontList fl; fl = gui_motif_fontset2fontlist(&gui.tooltip_fontset); if (fl != NULL) { XmStringExtent(fl, s, &w, &h); XmFontListFree(fl); } } w += gui.border_offset << 1; h += gui.border_offset << 1; XtVaSetValues(beval->balloonLabel, XmNlabelString, s, NULL); XmStringFree(s); #else /* Athena */ /* Assume XtNinternational == True */ XFontSet fset; XFontSetExtents *ext; XtVaGetValues(beval->balloonLabel, XtNfontSet, &fset, NULL); ext = XExtentsOfFontSet(fset); h = ext->max_ink_extent.height; w = XmbTextEscapement(fset, (char *)beval->msg, (int)STRLEN(beval->msg)); w += gui.border_offset << 1; h += gui.border_offset << 1; XtVaSetValues(beval->balloonLabel, XtNlabel, beval->msg, NULL); #endif /* Compute position of the balloon area */ tx = beval->x_root + EVAL_OFFSET_X; ty = beval->y_root + EVAL_OFFSET_Y; if ((tx + w) > beval->screen_width) tx = beval->screen_width - w; if ((ty + h) > beval->screen_height) ty = beval->screen_height - h; #ifdef FEAT_GUI_MOTIF XtVaSetValues(beval->balloonShell, XmNx, tx, XmNy, ty, NULL); #else /* Athena */ XtVaSetValues(beval->balloonShell, XtNx, tx, XtNy, ty, NULL); #endif /* Set tooltip colors */ { Arg args[2]; #ifdef FEAT_GUI_MOTIF args[0].name = XmNbackground; args[0].value = gui.tooltip_bg_pixel; args[1].name = XmNforeground; args[1].value = gui.tooltip_fg_pixel; #else /* Athena */ args[0].name = XtNbackground; args[0].value = gui.tooltip_bg_pixel; args[1].name = XtNforeground; args[1].value = gui.tooltip_fg_pixel; #endif XtSetValues(beval->balloonLabel, &args[0], XtNumber(args)); } XtPopup(beval->balloonShell, XtGrabNone); beval->showState = ShS_SHOWING; current_beval = beval; } } /* * Undraw a balloon. */ static void undrawBalloon(beval) BalloonEval *beval; { if (beval->balloonShell != (Widget)0) XtPopdown(beval->balloonShell); beval->showState = ShS_NEUTRAL; current_beval = NULL; } static void cancelBalloon(beval) BalloonEval *beval; { if (beval->showState == ShS_SHOWING || beval->showState == ShS_UPDATE_PENDING) undrawBalloon(beval); if (beval->timerID != (XtIntervalId)NULL) { XtRemoveTimeOut(beval->timerID); beval->timerID = (XtIntervalId)NULL; } beval->showState = ShS_NEUTRAL; } static void createBalloonEvalWindow(beval) BalloonEval *beval; { Arg args[12]; int n; n = 0; #ifdef FEAT_GUI_MOTIF XtSetArg(args[n], XmNallowShellResize, True); n++; beval->balloonShell = XtAppCreateShell("balloonEval", "BalloonEval", overrideShellWidgetClass, gui.dpy, args, n); #else /* Athena */ XtSetArg(args[n], XtNallowShellResize, True); n++; beval->balloonShell = XtAppCreateShell("balloonEval", "BalloonEval", overrideShellWidgetClass, gui.dpy, args, n); #endif n = 0; #ifdef FEAT_GUI_MOTIF { XmFontList fl; fl = gui_motif_fontset2fontlist(&gui.tooltip_fontset); XtSetArg(args[n], XmNforeground, gui.tooltip_fg_pixel); n++; XtSetArg(args[n], XmNbackground, gui.tooltip_bg_pixel); n++; XtSetArg(args[n], XmNfontList, fl); n++; XtSetArg(args[n], XmNalignment, XmALIGNMENT_BEGINNING); n++; beval->balloonLabel = XtCreateManagedWidget("balloonLabel", xmLabelWidgetClass, beval->balloonShell, args, n); } #else /* FEAT_GUI_ATHENA */ XtSetArg(args[n], XtNforeground, gui.tooltip_fg_pixel); n++; XtSetArg(args[n], XtNbackground, gui.tooltip_bg_pixel); n++; XtSetArg(args[n], XtNinternational, True); n++; XtSetArg(args[n], XtNfontSet, gui.tooltip_fontset); n++; beval->balloonLabel = XtCreateManagedWidget("balloonLabel", labelWidgetClass, beval->balloonShell, args, n); #endif } #endif /* !FEAT_GUI_GTK */ #endif /* !FEAT_GUI_W32 */ #endif /* FEAT_BEVAL */
zyz2011-vim
src/gui_beval.c
C
gpl2
33,898
# Makefile for Borland C++ 3.1 or 4.0 to compile a 16 bit version of Vim. # # There are compilation options at the end of this file. # # Command line variables: # BOR path to root of Borland C (E:\BORLANDC) # DEBUG set to "yes" for debugging (no) # SPAWNO path to the spawno library directory, empty if you do not have # it; use 8.3 filenames! (C:\CC\SPAWN) .AUTODEPEND !ifndef BOR BOR = E:\BORLANDC !endif !if ("$(DEBUG)" == "yes") DEBUG_FLAG = -v !else DEBUG_FLAG = !endif CC = $(BOR)\bin\bcc.exe +VIM.CFG TLINK = $(BOR)\bin\tlink.exe !ifndef SPAWNO SPAWNO = C:\CC\SPAWN !endif !if ("$(SPAWNO)" == "") LIBPATH = $(BOR)\LIB INCLUDEPATH = $(BOR)\INCLUDE SPAWND = SPAWNL = !else LIBPATH = $(BOR)\LIB;$(SPAWNO) INCLUDEPATH = $(BOR)\INCLUDE;$(SPAWNO) SPAWND = ;SPAWNO SPAWNL = spawnl.lib !endif # *Implicit Rules* # # use -v for debugging # .c.obj: $(CC) -c $(DEBUG_FLAG) {$< } # *List Macros* EXE_dependencies = \ blowfish.obj \ buffer.obj \ charset.obj \ diff.obj \ digraph.obj \ edit.obj \ eval.obj \ ex_cmds.obj \ ex_cmds2.obj \ ex_docmd.obj \ ex_eval.obj \ ex_getln.obj \ fileio.obj \ fold.obj \ getchar.obj \ hardcopy.obj \ hashtab.obj \ main.obj \ mark.obj \ memfile.obj \ memline.obj \ menu.obj \ message.obj \ misc1.obj \ misc2.obj \ move.obj \ os_msdos.obj \ normal.obj \ ops.obj \ option.obj \ popupmnu.obj \ quickfix.obj \ regexp.obj \ screen.obj \ search.obj \ sha256.obj \ spell.obj \ syntax.obj \ tag.obj \ term.obj \ ui.obj \ undo.obj \ window.obj all: vim.exe install.exe uninstal.exe xxd/xxd.exe # *Explicit Rules* vim.exe: vim.cfg $(EXE_dependencies) version.c $(CC) $(DEBUG_FLAG) -c version.c $(TLINK) /x/c/L$(LIBPATH) $(DEBUG_FLAG) @&&| c0l.obj $(EXE_dependencies) version.obj vim # no map file $(SPAWNL) cl.lib | install.exe: dosinst.c $(CC) -einstall $(DEBUG_FLAG) dosinst.c uninstal.exe: uninstal.c $(CC) $(DEBUG_FLAG) uninstal.c # This may fail for older make versions, building xxd will fail anyway then. xxd/xxd.exe: xxd/xxd.c cd xxd $(MAKE) -f Make_bc3.mak BOR=$(BOR) DEBUG=$(DEBUG) cd .. # cleaning up: Delete all generated files clean: -del *.obj -del vim.exe -del vim.sym -del install.exe -del uninstal.exe -del xxd\*.obj -del xxd\xxd.exe -del vim.cfg -del testdir\*.out # Individual File Dependencies (incomplete) ex_docmd.obj: ex_docmd.c ex_cmds.h ex_eval.obj: ex_eval.c ex_cmds.h main.obj: main.c globals.h option.h term.obj: term.c term.h version.obj: version.c version.h # Compiler Configuration File # # The following compile options can be changed for better machines. # replace -1- with -2 to produce code for a 80286 or higher # replace -1- with -3 to produce code for a 80386 or higher # add -v for source debugging vim.cfg: Make_bc3.mak copy &&| -ml -1- -f- -C -N -O -Z -k- -d -h -vi- -H=VIM.SYM -w-par -weas -wpre -Iproto -I$(INCLUDEPATH) -L$(LIBPATH) -DMSDOS;FEAT_TINY$(SPAWND) | vim.cfg test: cd testdir $(MAKE) -f Make_dos.mak small cd ..
zyz2011-vim
src/Make_bc3.mak
Makefile
gpl2
2,980
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * misc2.c: Various functions. */ #include "vim.h" static char_u *username = NULL; /* cached result of mch_get_user_name() */ static char_u *ff_expand_buffer = NULL; /* used for expanding filenames */ #if defined(FEAT_VIRTUALEDIT) || defined(PROTO) static int coladvance2 __ARGS((pos_T *pos, int addspaces, int finetune, colnr_T wcol)); /* * Return TRUE if in the current mode we need to use virtual. */ int virtual_active() { /* While an operator is being executed we return "virtual_op", because * VIsual_active has already been reset, thus we can't check for "block" * being used. */ if (virtual_op != MAYBE) return virtual_op; return (ve_flags == VE_ALL # ifdef FEAT_VISUAL || ((ve_flags & VE_BLOCK) && VIsual_active && VIsual_mode == Ctrl_V) # endif || ((ve_flags & VE_INSERT) && (State & INSERT))); } /* * Get the screen position of the cursor. */ int getviscol() { colnr_T x; getvvcol(curwin, &curwin->w_cursor, &x, NULL, NULL); return (int)x; } /* * Get the screen position of character col with a coladd in the cursor line. */ int getviscol2(col, coladd) colnr_T col; colnr_T coladd; { colnr_T x; pos_T pos; pos.lnum = curwin->w_cursor.lnum; pos.col = col; pos.coladd = coladd; getvvcol(curwin, &pos, &x, NULL, NULL); return (int)x; } /* * Go to column "wcol", and add/insert white space as necessary to get the * cursor in that column. * The caller must have saved the cursor line for undo! */ int coladvance_force(wcol) colnr_T wcol; { int rc = coladvance2(&curwin->w_cursor, TRUE, FALSE, wcol); if (wcol == MAXCOL) curwin->w_valid &= ~VALID_VIRTCOL; else { /* Virtcol is valid */ curwin->w_valid |= VALID_VIRTCOL; curwin->w_virtcol = wcol; } return rc; } #endif /* * Try to advance the Cursor to the specified screen column. * If virtual editing: fine tune the cursor position. * Note that all virtual positions off the end of a line should share * a curwin->w_cursor.col value (n.b. this is equal to STRLEN(line)), * beginning at coladd 0. * * return OK if desired column is reached, FAIL if not */ int coladvance(wcol) colnr_T wcol; { int rc = getvpos(&curwin->w_cursor, wcol); if (wcol == MAXCOL || rc == FAIL) curwin->w_valid &= ~VALID_VIRTCOL; else if (*ml_get_cursor() != TAB) { /* Virtcol is valid when not on a TAB */ curwin->w_valid |= VALID_VIRTCOL; curwin->w_virtcol = wcol; } return rc; } /* * Return in "pos" the position of the cursor advanced to screen column "wcol". * return OK if desired column is reached, FAIL if not */ int getvpos(pos, wcol) pos_T *pos; colnr_T wcol; { #ifdef FEAT_VIRTUALEDIT return coladvance2(pos, FALSE, virtual_active(), wcol); } static int coladvance2(pos, addspaces, finetune, wcol) pos_T *pos; int addspaces; /* change the text to achieve our goal? */ int finetune; /* change char offset for the exact column */ colnr_T wcol; /* column to move to */ { #endif int idx; char_u *ptr; char_u *line; colnr_T col = 0; int csize = 0; int one_more; #ifdef FEAT_LINEBREAK int head = 0; #endif one_more = (State & INSERT) || restart_edit != NUL #ifdef FEAT_VISUAL || (VIsual_active && *p_sel != 'o') #endif #ifdef FEAT_VIRTUALEDIT || ((ve_flags & VE_ONEMORE) && wcol < MAXCOL) #endif ; line = ml_get_buf(curbuf, pos->lnum, FALSE); if (wcol >= MAXCOL) { idx = (int)STRLEN(line) - 1 + one_more; col = wcol; #ifdef FEAT_VIRTUALEDIT if ((addspaces || finetune) && !VIsual_active) { curwin->w_curswant = linetabsize(line) + one_more; if (curwin->w_curswant > 0) --curwin->w_curswant; } #endif } else { #ifdef FEAT_VIRTUALEDIT int width = W_WIDTH(curwin) - win_col_off(curwin); if (finetune && curwin->w_p_wrap # ifdef FEAT_VERTSPLIT && curwin->w_width != 0 # endif && wcol >= (colnr_T)width) { csize = linetabsize(line); if (csize > 0) csize--; if (wcol / width > (colnr_T)csize / width && ((State & INSERT) == 0 || (int)wcol > csize + 1)) { /* In case of line wrapping don't move the cursor beyond the * right screen edge. In Insert mode allow going just beyond * the last character (like what happens when typing and * reaching the right window edge). */ wcol = (csize / width + 1) * width - 1; } } #endif ptr = line; while (col <= wcol && *ptr != NUL) { /* Count a tab for what it's worth (if list mode not on) */ #ifdef FEAT_LINEBREAK csize = win_lbr_chartabsize(curwin, ptr, col, &head); mb_ptr_adv(ptr); #else csize = lbr_chartabsize_adv(&ptr, col); #endif col += csize; } idx = (int)(ptr - line); /* * Handle all the special cases. The virtual_active() check * is needed to ensure that a virtual position off the end of * a line has the correct indexing. The one_more comparison * replaces an explicit add of one_more later on. */ if (col > wcol || (!virtual_active() && one_more == 0)) { idx -= 1; # ifdef FEAT_LINEBREAK /* Don't count the chars from 'showbreak'. */ csize -= head; # endif col -= csize; } #ifdef FEAT_VIRTUALEDIT if (virtual_active() && addspaces && ((col != wcol && col != wcol + 1) || csize > 1)) { /* 'virtualedit' is set: The difference between wcol and col is * filled with spaces. */ if (line[idx] == NUL) { /* Append spaces */ int correct = wcol - col; char_u *newline = alloc(idx + correct + 1); int t; if (newline == NULL) return FAIL; for (t = 0; t < idx; ++t) newline[t] = line[t]; for (t = 0; t < correct; ++t) newline[t + idx] = ' '; newline[idx + correct] = NUL; ml_replace(pos->lnum, newline, FALSE); changed_bytes(pos->lnum, (colnr_T)idx); idx += correct; col = wcol; } else { /* Break a tab */ int linelen = (int)STRLEN(line); int correct = wcol - col - csize + 1; /* negative!! */ char_u *newline; int t, s = 0; int v; if (-correct > csize) return FAIL; newline = alloc(linelen + csize); if (newline == NULL) return FAIL; for (t = 0; t < linelen; t++) { if (t != idx) newline[s++] = line[t]; else for (v = 0; v < csize; v++) newline[s++] = ' '; } newline[linelen + csize - 1] = NUL; ml_replace(pos->lnum, newline, FALSE); changed_bytes(pos->lnum, idx); idx += (csize - 1 + correct); col += correct; } } #endif } if (idx < 0) pos->col = 0; else pos->col = idx; #ifdef FEAT_VIRTUALEDIT pos->coladd = 0; if (finetune) { if (wcol == MAXCOL) { /* The width of the last character is used to set coladd. */ if (!one_more) { colnr_T scol, ecol; getvcol(curwin, pos, &scol, NULL, &ecol); pos->coladd = ecol - scol; } } else { int b = (int)wcol - (int)col; /* The difference between wcol and col is used to set coladd. */ if (b > 0 && b < (MAXCOL - 2 * W_WIDTH(curwin))) pos->coladd = b; col += b; } } #endif #ifdef FEAT_MBYTE /* prevent from moving onto a trail byte */ if (has_mbyte) mb_adjustpos(curbuf, pos); #endif if (col < wcol) return FAIL; return OK; } /* * Increment the cursor position. See inc() for return values. */ int inc_cursor() { return inc(&curwin->w_cursor); } /* * Increment the line pointer "lp" crossing line boundaries as necessary. * Return 1 when going to the next line. * Return 2 when moving forward onto a NUL at the end of the line). * Return -1 when at the end of file. * Return 0 otherwise. */ int inc(lp) pos_T *lp; { char_u *p = ml_get_pos(lp); if (*p != NUL) /* still within line, move to next char (may be NUL) */ { #ifdef FEAT_MBYTE if (has_mbyte) { int l = (*mb_ptr2len)(p); lp->col += l; return ((p[l] != NUL) ? 0 : 2); } #endif lp->col++; #ifdef FEAT_VIRTUALEDIT lp->coladd = 0; #endif return ((p[1] != NUL) ? 0 : 2); } if (lp->lnum != curbuf->b_ml.ml_line_count) /* there is a next line */ { lp->col = 0; lp->lnum++; #ifdef FEAT_VIRTUALEDIT lp->coladd = 0; #endif return 1; } return -1; } /* * incl(lp): same as inc(), but skip the NUL at the end of non-empty lines */ int incl(lp) pos_T *lp; { int r; if ((r = inc(lp)) >= 1 && lp->col) r = inc(lp); return r; } /* * dec(p) * * Decrement the line pointer 'p' crossing line boundaries as necessary. * Return 1 when crossing a line, -1 when at start of file, 0 otherwise. */ int dec_cursor() { return dec(&curwin->w_cursor); } int dec(lp) pos_T *lp; { char_u *p; #ifdef FEAT_VIRTUALEDIT lp->coladd = 0; #endif if (lp->col > 0) /* still within line */ { lp->col--; #ifdef FEAT_MBYTE if (has_mbyte) { p = ml_get(lp->lnum); lp->col -= (*mb_head_off)(p, p + lp->col); } #endif return 0; } if (lp->lnum > 1) /* there is a prior line */ { lp->lnum--; p = ml_get(lp->lnum); lp->col = (colnr_T)STRLEN(p); #ifdef FEAT_MBYTE if (has_mbyte) lp->col -= (*mb_head_off)(p, p + lp->col); #endif return 1; } return -1; /* at start of file */ } /* * decl(lp): same as dec(), but skip the NUL at the end of non-empty lines */ int decl(lp) pos_T *lp; { int r; if ((r = dec(lp)) == 1 && lp->col) r = dec(lp); return r; } /* * Get the line number relative to the current cursor position, i.e. the * difference between line number and cursor position. Only look for lines that * can be visible, folded lines don't count. */ linenr_T get_cursor_rel_lnum(wp, lnum) win_T *wp; linenr_T lnum; /* line number to get the result for */ { linenr_T cursor = wp->w_cursor.lnum; linenr_T retval = 0; #ifdef FEAT_FOLDING if (hasAnyFolding(wp)) { if (lnum > cursor) { while (lnum > cursor) { (void)hasFolding(lnum, &lnum, NULL); /* if lnum and cursor are in the same fold, * now lnum <= cursor */ if (lnum > cursor) retval++; lnum--; } } else if (lnum < cursor) { while (lnum < cursor) { (void)hasFolding(lnum, NULL, &lnum); /* if lnum and cursor are in the same fold, * now lnum >= cursor */ if (lnum < cursor) retval--; lnum++; } } /* else if (lnum == cursor) * retval = 0; */ } else #endif retval = lnum - cursor; return retval; } /* * Make sure curwin->w_cursor.lnum is valid. */ void check_cursor_lnum() { if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) { #ifdef FEAT_FOLDING /* If there is a closed fold at the end of the file, put the cursor in * its first line. Otherwise in the last line. */ if (!hasFolding(curbuf->b_ml.ml_line_count, &curwin->w_cursor.lnum, NULL)) #endif curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; } if (curwin->w_cursor.lnum <= 0) curwin->w_cursor.lnum = 1; } /* * Make sure curwin->w_cursor.col is valid. */ void check_cursor_col() { check_cursor_col_win(curwin); } /* * Make sure win->w_cursor.col is valid. */ void check_cursor_col_win(win) win_T *win; { colnr_T len; #ifdef FEAT_VIRTUALEDIT colnr_T oldcol = win->w_cursor.col; colnr_T oldcoladd = win->w_cursor.col + win->w_cursor.coladd; #endif len = (colnr_T)STRLEN(ml_get_buf(win->w_buffer, win->w_cursor.lnum, FALSE)); if (len == 0) win->w_cursor.col = 0; else if (win->w_cursor.col >= len) { /* Allow cursor past end-of-line when: * - in Insert mode or restarting Insert mode * - in Visual mode and 'selection' isn't "old" * - 'virtualedit' is set */ if ((State & INSERT) || restart_edit #ifdef FEAT_VISUAL || (VIsual_active && *p_sel != 'o') #endif #ifdef FEAT_VIRTUALEDIT || (ve_flags & VE_ONEMORE) #endif || virtual_active()) win->w_cursor.col = len; else { win->w_cursor.col = len - 1; #ifdef FEAT_MBYTE /* Move the cursor to the head byte. */ if (has_mbyte) mb_adjustpos(win->w_buffer, &win->w_cursor); #endif } } else if (win->w_cursor.col < 0) win->w_cursor.col = 0; #ifdef FEAT_VIRTUALEDIT /* If virtual editing is on, we can leave the cursor on the old position, * only we must set it to virtual. But don't do it when at the end of the * line. */ if (oldcol == MAXCOL) win->w_cursor.coladd = 0; else if (ve_flags == VE_ALL) { if (oldcoladd > win->w_cursor.col) win->w_cursor.coladd = oldcoladd - win->w_cursor.col; else /* avoid weird number when there is a miscalculation or overflow */ win->w_cursor.coladd = 0; } #endif } /* * make sure curwin->w_cursor in on a valid character */ void check_cursor() { check_cursor_lnum(); check_cursor_col(); } #if defined(FEAT_TEXTOBJ) || defined(PROTO) /* * Make sure curwin->w_cursor is not on the NUL at the end of the line. * Allow it when in Visual mode and 'selection' is not "old". */ void adjust_cursor_col() { if (curwin->w_cursor.col > 0 # ifdef FEAT_VISUAL && (!VIsual_active || *p_sel == 'o') # endif && gchar_cursor() == NUL) --curwin->w_cursor.col; } #endif /* * When curwin->w_leftcol has changed, adjust the cursor position. * Return TRUE if the cursor was moved. */ int leftcol_changed() { long lastcol; colnr_T s, e; int retval = FALSE; changed_cline_bef_curs(); lastcol = curwin->w_leftcol + W_WIDTH(curwin) - curwin_col_off() - 1; validate_virtcol(); /* * If the cursor is right or left of the screen, move it to last or first * character. */ if (curwin->w_virtcol > (colnr_T)(lastcol - p_siso)) { retval = TRUE; coladvance((colnr_T)(lastcol - p_siso)); } else if (curwin->w_virtcol < curwin->w_leftcol + p_siso) { retval = TRUE; (void)coladvance((colnr_T)(curwin->w_leftcol + p_siso)); } /* * If the start of the character under the cursor is not on the screen, * advance the cursor one more char. If this fails (last char of the * line) adjust the scrolling. */ getvvcol(curwin, &curwin->w_cursor, &s, NULL, &e); if (e > (colnr_T)lastcol) { retval = TRUE; coladvance(s - 1); } else if (s < curwin->w_leftcol) { retval = TRUE; if (coladvance(e + 1) == FAIL) /* there isn't another character */ { curwin->w_leftcol = s; /* adjust w_leftcol instead */ changed_cline_bef_curs(); } } if (retval) curwin->w_set_curswant = TRUE; redraw_later(NOT_VALID); return retval; } /********************************************************************** * Various routines dealing with allocation and deallocation of memory. */ #if defined(MEM_PROFILE) || defined(PROTO) # define MEM_SIZES 8200 static long_u mem_allocs[MEM_SIZES]; static long_u mem_frees[MEM_SIZES]; static long_u mem_allocated; static long_u mem_freed; static long_u mem_peak; static long_u num_alloc; static long_u num_freed; static void mem_pre_alloc_s __ARGS((size_t *sizep)); static void mem_pre_alloc_l __ARGS((long_u *sizep)); static void mem_post_alloc __ARGS((void **pp, size_t size)); static void mem_pre_free __ARGS((void **pp)); static void mem_pre_alloc_s(sizep) size_t *sizep; { *sizep += sizeof(size_t); } static void mem_pre_alloc_l(sizep) long_u *sizep; { *sizep += sizeof(size_t); } static void mem_post_alloc(pp, size) void **pp; size_t size; { if (*pp == NULL) return; size -= sizeof(size_t); *(long_u *)*pp = size; if (size <= MEM_SIZES-1) mem_allocs[size-1]++; else mem_allocs[MEM_SIZES-1]++; mem_allocated += size; if (mem_allocated - mem_freed > mem_peak) mem_peak = mem_allocated - mem_freed; num_alloc++; *pp = (void *)((char *)*pp + sizeof(size_t)); } static void mem_pre_free(pp) void **pp; { long_u size; *pp = (void *)((char *)*pp - sizeof(size_t)); size = *(size_t *)*pp; if (size <= MEM_SIZES-1) mem_frees[size-1]++; else mem_frees[MEM_SIZES-1]++; mem_freed += size; num_freed++; } /* * called on exit via atexit() */ void vim_mem_profile_dump() { int i, j; printf("\r\n"); j = 0; for (i = 0; i < MEM_SIZES - 1; i++) { if (mem_allocs[i] || mem_frees[i]) { if (mem_frees[i] > mem_allocs[i]) printf("\r\n%s", _("ERROR: ")); printf("[%4d / %4lu-%-4lu] ", i + 1, mem_allocs[i], mem_frees[i]); j++; if (j > 3) { j = 0; printf("\r\n"); } } } i = MEM_SIZES - 1; if (mem_allocs[i]) { printf("\r\n"); if (mem_frees[i] > mem_allocs[i]) puts(_("ERROR: ")); printf("[>%d / %4lu-%-4lu]", i, mem_allocs[i], mem_frees[i]); } printf(_("\n[bytes] total alloc-freed %lu-%lu, in use %lu, peak use %lu\n"), mem_allocated, mem_freed, mem_allocated - mem_freed, mem_peak); printf(_("[calls] total re/malloc()'s %lu, total free()'s %lu\n\n"), num_alloc, num_freed); } #endif /* MEM_PROFILE */ /* * Some memory is reserved for error messages and for being able to * call mf_release_all(), which needs some memory for mf_trans_add(). */ #if defined(MSDOS) && !defined(DJGPP) # define SMALL_MEM # define KEEP_ROOM 8192L #else # define KEEP_ROOM (2 * 8192L) #endif /* * Note: if unsigned is 16 bits we can only allocate up to 64K with alloc(). * Use lalloc for larger blocks. */ char_u * alloc(size) unsigned size; { return (lalloc((long_u)size, TRUE)); } /* * Allocate memory and set all bytes to zero. */ char_u * alloc_clear(size) unsigned size; { char_u *p; p = lalloc((long_u)size, TRUE); if (p != NULL) (void)vim_memset(p, 0, (size_t)size); return p; } /* * alloc() with check for maximum line length */ char_u * alloc_check(size) unsigned size; { #if !defined(UNIX) && !defined(__EMX__) if (sizeof(int) == 2 && size > 0x7fff) { /* Don't hide this message */ emsg_silent = 0; EMSG(_("E340: Line is becoming too long")); return NULL; } #endif return (lalloc((long_u)size, TRUE)); } /* * Allocate memory like lalloc() and set all bytes to zero. */ char_u * lalloc_clear(size, message) long_u size; int message; { char_u *p; p = (lalloc(size, message)); if (p != NULL) (void)vim_memset(p, 0, (size_t)size); return p; } /* * Low level memory allocation function. * This is used often, KEEP IT FAST! */ char_u * lalloc(size, message) long_u size; int message; { char_u *p; /* pointer to new storage space */ static int releasing = FALSE; /* don't do mf_release_all() recursive */ int try_again; #if defined(HAVE_AVAIL_MEM) && !defined(SMALL_MEM) static long_u allocated = 0; /* allocated since last avail check */ #endif /* Safety check for allocating zero bytes */ if (size == 0) { /* Don't hide this message */ emsg_silent = 0; EMSGN(_("E341: Internal error: lalloc(%ld, )"), size); return NULL; } #ifdef MEM_PROFILE mem_pre_alloc_l(&size); #endif #if defined(MSDOS) && !defined(DJGPP) if (size >= 0xfff0) /* in MSDOS we can't deal with >64K blocks */ p = NULL; else #endif /* * Loop when out of memory: Try to release some memfile blocks and * if some blocks are released call malloc again. */ for (;;) { /* * Handle three kind of systems: * 1. No check for available memory: Just return. * 2. Slow check for available memory: call mch_avail_mem() after * allocating KEEP_ROOM amount of memory. * 3. Strict check for available memory: call mch_avail_mem() */ if ((p = (char_u *)malloc((size_t)size)) != NULL) { #ifndef HAVE_AVAIL_MEM /* 1. No check for available memory: Just return. */ goto theend; #else # ifndef SMALL_MEM /* 2. Slow check for available memory: call mch_avail_mem() after * allocating (KEEP_ROOM / 2) amount of memory. */ allocated += size; if (allocated < KEEP_ROOM / 2) goto theend; allocated = 0; # endif /* 3. check for available memory: call mch_avail_mem() */ if (mch_avail_mem(TRUE) < KEEP_ROOM && !releasing) { free((char *)p); /* System is low... no go! */ p = NULL; } else goto theend; #endif } /* * Remember that mf_release_all() is being called to avoid an endless * loop, because mf_release_all() may call alloc() recursively. */ if (releasing) break; releasing = TRUE; clear_sb_text(); /* free any scrollback text */ try_again = mf_release_all(); /* release as many blocks as possible */ #ifdef FEAT_EVAL try_again |= garbage_collect(); /* cleanup recursive lists/dicts */ #endif releasing = FALSE; if (!try_again) break; } if (message && p == NULL) do_outofmem_msg(size); theend: #ifdef MEM_PROFILE mem_post_alloc((void **)&p, (size_t)size); #endif return p; } #if defined(MEM_PROFILE) || defined(PROTO) /* * realloc() with memory profiling. */ void * mem_realloc(ptr, size) void *ptr; size_t size; { void *p; mem_pre_free(&ptr); mem_pre_alloc_s(&size); p = realloc(ptr, size); mem_post_alloc(&p, size); return p; } #endif /* * Avoid repeating the error message many times (they take 1 second each). * Did_outofmem_msg is reset when a character is read. */ void do_outofmem_msg(size) long_u size; { if (!did_outofmem_msg) { /* Don't hide this message */ emsg_silent = 0; /* Must come first to avoid coming back here when printing the error * message fails, e.g. when setting v:errmsg. */ did_outofmem_msg = TRUE; EMSGN(_("E342: Out of memory! (allocating %lu bytes)"), size); } } #if defined(EXITFREE) || defined(PROTO) # if defined(FEAT_SEARCHPATH) static void free_findfile __ARGS((void)); # endif /* * Free everything that we allocated. * Can be used to detect memory leaks, e.g., with ccmalloc. * NOTE: This is tricky! Things are freed that functions depend on. Don't be * surprised if Vim crashes... * Some things can't be freed, esp. things local to a library function. */ void free_all_mem() { buf_T *buf, *nextbuf; static int entered = FALSE; /* When we cause a crash here it is caught and Vim tries to exit cleanly. * Don't try freeing everything again. */ if (entered) return; entered = TRUE; # ifdef FEAT_AUTOCMD block_autocmds(); /* don't want to trigger autocommands here */ # endif # ifdef FEAT_WINDOWS /* Close all tabs and windows. Reset 'equalalways' to avoid redraws. */ p_ea = FALSE; if (first_tabpage->tp_next != NULL) do_cmdline_cmd((char_u *)"tabonly!"); if (firstwin != lastwin) do_cmdline_cmd((char_u *)"only!"); # endif # if defined(FEAT_SPELL) /* Free all spell info. */ spell_free_all(); # endif # if defined(FEAT_USR_CMDS) /* Clear user commands (before deleting buffers). */ ex_comclear(NULL); # endif # ifdef FEAT_MENU /* Clear menus. */ do_cmdline_cmd((char_u *)"aunmenu *"); # ifdef FEAT_MULTI_LANG do_cmdline_cmd((char_u *)"menutranslate clear"); # endif # endif /* Clear mappings, abbreviations, breakpoints. */ do_cmdline_cmd((char_u *)"lmapclear"); do_cmdline_cmd((char_u *)"xmapclear"); do_cmdline_cmd((char_u *)"mapclear"); do_cmdline_cmd((char_u *)"mapclear!"); do_cmdline_cmd((char_u *)"abclear"); # if defined(FEAT_EVAL) do_cmdline_cmd((char_u *)"breakdel *"); # endif # if defined(FEAT_PROFILE) do_cmdline_cmd((char_u *)"profdel *"); # endif # if defined(FEAT_KEYMAP) do_cmdline_cmd((char_u *)"set keymap="); #endif # ifdef FEAT_TITLE free_titles(); # endif # if defined(FEAT_SEARCHPATH) free_findfile(); # endif /* Obviously named calls. */ # if defined(FEAT_AUTOCMD) free_all_autocmds(); # endif clear_termcodes(); free_all_options(); free_all_marks(); alist_clear(&global_alist); free_homedir(); free_search_patterns(); free_old_sub(); free_last_insert(); free_prev_shellcmd(); free_regexp_stuff(); free_tag_stuff(); free_cd_dir(); # ifdef FEAT_SIGNS free_signs(); # endif # ifdef FEAT_EVAL set_expr_line(NULL); # endif # ifdef FEAT_DIFF diff_clear(curtab); # endif clear_sb_text(); /* free any scrollback text */ /* Free some global vars. */ vim_free(username); # ifdef FEAT_CLIPBOARD vim_free(clip_exclude_prog); # endif vim_free(last_cmdline); # ifdef FEAT_CMDHIST vim_free(new_last_cmdline); # endif set_keep_msg(NULL, 0); vim_free(ff_expand_buffer); /* Clear cmdline history. */ p_hi = 0; # ifdef FEAT_CMDHIST init_history(); # endif #ifdef FEAT_QUICKFIX { win_T *win; tabpage_T *tab; qf_free_all(NULL); /* Free all location lists */ FOR_ALL_TAB_WINDOWS(tab, win) qf_free_all(win); } #endif /* Close all script inputs. */ close_all_scripts(); #if defined(FEAT_WINDOWS) /* Destroy all windows. Must come before freeing buffers. */ win_free_all(); #endif /* Free all buffers. Reset 'autochdir' to avoid accessing things that * were freed already. */ #ifdef FEAT_AUTOCHDIR p_acd = FALSE; #endif for (buf = firstbuf; buf != NULL; ) { nextbuf = buf->b_next; close_buffer(NULL, buf, DOBUF_WIPE, FALSE); if (buf_valid(buf)) buf = nextbuf; /* didn't work, try next one */ else buf = firstbuf; } #ifdef FEAT_ARABIC free_cmdline_buf(); #endif /* Clear registers. */ clear_registers(); ResetRedobuff(); ResetRedobuff(); #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11) vim_free(serverDelayedStartName); #endif /* highlight info */ free_highlight(); reset_last_sourcing(); #ifdef FEAT_WINDOWS free_tabpage(first_tabpage); first_tabpage = NULL; #endif # ifdef UNIX /* Machine-specific free. */ mch_free_mem(); # endif /* message history */ for (;;) if (delete_first_msg() == FAIL) break; # ifdef FEAT_EVAL eval_clear(); # endif free_termoptions(); /* screenlines (can't display anything now!) */ free_screenlines(); #if defined(USE_XSMP) xsmp_close(); #endif #ifdef FEAT_GUI_GTK gui_mch_free_all(); #endif clear_hl_tables(); vim_free(IObuff); vim_free(NameBuff); } #endif /* * Copy "string" into newly allocated memory. */ char_u * vim_strsave(string) char_u *string; { char_u *p; unsigned len; len = (unsigned)STRLEN(string) + 1; p = alloc(len); if (p != NULL) mch_memmove(p, string, (size_t)len); return p; } /* * Copy up to "len" bytes of "string" into newly allocated memory and * terminate with a NUL. * The allocated memory always has size "len + 1", also when "string" is * shorter. */ char_u * vim_strnsave(string, len) char_u *string; int len; { char_u *p; p = alloc((unsigned)(len + 1)); if (p != NULL) { STRNCPY(p, string, len); p[len] = NUL; } return p; } /* * Same as vim_strsave(), but any characters found in esc_chars are preceded * by a backslash. */ char_u * vim_strsave_escaped(string, esc_chars) char_u *string; char_u *esc_chars; { return vim_strsave_escaped_ext(string, esc_chars, '\\', FALSE); } /* * Same as vim_strsave_escaped(), but when "bsl" is TRUE also escape * characters where rem_backslash() would remove the backslash. * Escape the characters with "cc". */ char_u * vim_strsave_escaped_ext(string, esc_chars, cc, bsl) char_u *string; char_u *esc_chars; int cc; int bsl; { char_u *p; char_u *p2; char_u *escaped_string; unsigned length; #ifdef FEAT_MBYTE int l; #endif /* * First count the number of backslashes required. * Then allocate the memory and insert them. */ length = 1; /* count the trailing NUL */ for (p = string; *p; p++) { #ifdef FEAT_MBYTE if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1) { length += l; /* count a multibyte char */ p += l - 1; continue; } #endif if (vim_strchr(esc_chars, *p) != NULL || (bsl && rem_backslash(p))) ++length; /* count a backslash */ ++length; /* count an ordinary char */ } escaped_string = alloc(length); if (escaped_string != NULL) { p2 = escaped_string; for (p = string; *p; p++) { #ifdef FEAT_MBYTE if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1) { mch_memmove(p2, p, (size_t)l); p2 += l; p += l - 1; /* skip multibyte char */ continue; } #endif if (vim_strchr(esc_chars, *p) != NULL || (bsl && rem_backslash(p))) *p2++ = cc; *p2++ = *p; } *p2 = NUL; } return escaped_string; } /* * Return TRUE when 'shell' has "csh" in the tail. */ int csh_like_shell() { return (strstr((char *)gettail(p_sh), "csh") != NULL); } /* * Escape "string" for use as a shell argument with system(). * This uses single quotes, except when we know we need to use double quotes * (MS-DOS and MS-Windows without 'shellslash' set). * Escape a newline, depending on the 'shell' option. * When "do_special" is TRUE also replace "!", "%", "#" and things starting * with "<" like "<cfile>". * Returns the result in allocated memory, NULL if we have run out. */ char_u * vim_strsave_shellescape(string, do_special) char_u *string; int do_special; { unsigned length; char_u *p; char_u *d; char_u *escaped_string; int l; int csh_like; /* Only csh and similar shells expand '!' within single quotes. For sh and * the like we must not put a backslash before it, it will be taken * literally. If do_special is set the '!' will be escaped twice. * Csh also needs to have "\n" escaped twice when do_special is set. */ csh_like = csh_like_shell(); /* First count the number of extra bytes required. */ length = (unsigned)STRLEN(string) + 3; /* two quotes and a trailing NUL */ for (p = string; *p != NUL; mb_ptr_adv(p)) { # if defined(WIN32) || defined(WIN16) || defined(DOS) if (!p_ssl) { if (*p == '"') ++length; /* " -> "" */ } else # endif if (*p == '\'') length += 3; /* ' => '\'' */ if (*p == '\n' || (*p == '!' && (csh_like || do_special))) { ++length; /* insert backslash */ if (csh_like && do_special) ++length; /* insert backslash */ } if (do_special && find_cmdline_var(p, &l) >= 0) { ++length; /* insert backslash */ p += l - 1; } } /* Allocate memory for the result and fill it. */ escaped_string = alloc(length); if (escaped_string != NULL) { d = escaped_string; /* add opening quote */ # if defined(WIN32) || defined(WIN16) || defined(DOS) if (!p_ssl) *d++ = '"'; else # endif *d++ = '\''; for (p = string; *p != NUL; ) { # if defined(WIN32) || defined(WIN16) || defined(DOS) if (!p_ssl) { if (*p == '"') { *d++ = '"'; *d++ = '"'; ++p; continue; } } else # endif if (*p == '\'') { *d++ = '\''; *d++ = '\\'; *d++ = '\''; *d++ = '\''; ++p; continue; } if (*p == '\n' || (*p == '!' && (csh_like || do_special))) { *d++ = '\\'; if (csh_like && do_special) *d++ = '\\'; *d++ = *p++; continue; } if (do_special && find_cmdline_var(p, &l) >= 0) { *d++ = '\\'; /* insert backslash */ while (--l >= 0) /* copy the var */ *d++ = *p++; continue; } MB_COPY_CHAR(p, d); } /* add terminating quote and finish with a NUL */ # if defined(WIN32) || defined(WIN16) || defined(DOS) if (!p_ssl) *d++ = '"'; else # endif *d++ = '\''; *d = NUL; } return escaped_string; } /* * Like vim_strsave(), but make all characters uppercase. * This uses ASCII lower-to-upper case translation, language independent. */ char_u * vim_strsave_up(string) char_u *string; { char_u *p1; p1 = vim_strsave(string); vim_strup(p1); return p1; } /* * Like vim_strnsave(), but make all characters uppercase. * This uses ASCII lower-to-upper case translation, language independent. */ char_u * vim_strnsave_up(string, len) char_u *string; int len; { char_u *p1; p1 = vim_strnsave(string, len); vim_strup(p1); return p1; } /* * ASCII lower-to-upper case translation, language independent. */ void vim_strup(p) char_u *p; { char_u *p2; int c; if (p != NULL) { p2 = p; while ((c = *p2) != NUL) #ifdef EBCDIC *p2++ = isalpha(c) ? toupper(c) : c; #else *p2++ = (c < 'a' || c > 'z') ? c : (c - 0x20); #endif } } #if defined(FEAT_EVAL) || defined(FEAT_SPELL) || defined(PROTO) /* * Make string "s" all upper-case and return it in allocated memory. * Handles multi-byte characters as well as possible. * Returns NULL when out of memory. */ char_u * strup_save(orig) char_u *orig; { char_u *p; char_u *res; res = p = vim_strsave(orig); if (res != NULL) while (*p != NUL) { # ifdef FEAT_MBYTE int l; if (enc_utf8) { int c, uc; int newl; char_u *s; c = utf_ptr2char(p); uc = utf_toupper(c); /* Reallocate string when byte count changes. This is rare, * thus it's OK to do another malloc()/free(). */ l = utf_ptr2len(p); newl = utf_char2len(uc); if (newl != l) { s = alloc((unsigned)STRLEN(res) + 1 + newl - l); if (s == NULL) break; mch_memmove(s, res, p - res); STRCPY(s + (p - res) + newl, p + l); p = s + (p - res); vim_free(res); res = s; } utf_char2bytes(uc, p); p += newl; } else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1) p += l; /* skip multi-byte character */ else # endif { *p = TOUPPER_LOC(*p); /* note that toupper() can be a macro */ p++; } } return res; } #endif /* * copy a space a number of times */ void copy_spaces(ptr, count) char_u *ptr; size_t count; { size_t i = count; char_u *p = ptr; while (i--) *p++ = ' '; } #if defined(FEAT_VISUALEXTRA) || defined(PROTO) /* * Copy a character a number of times. * Does not work for multi-byte characters! */ void copy_chars(ptr, count, c) char_u *ptr; size_t count; int c; { size_t i = count; char_u *p = ptr; while (i--) *p++ = c; } #endif /* * delete spaces at the end of a string */ void del_trailing_spaces(ptr) char_u *ptr; { char_u *q; q = ptr + STRLEN(ptr); while (--q > ptr && vim_iswhite(q[0]) && q[-1] != '\\' && q[-1] != Ctrl_V) *q = NUL; } /* * Like strncpy(), but always terminate the result with one NUL. * "to" must be "len + 1" long! */ void vim_strncpy(to, from, len) char_u *to; char_u *from; size_t len; { STRNCPY(to, from, len); to[len] = NUL; } /* * Like strcat(), but make sure the result fits in "tosize" bytes and is * always NUL terminated. */ void vim_strcat(to, from, tosize) char_u *to; char_u *from; size_t tosize; { size_t tolen = STRLEN(to); size_t fromlen = STRLEN(from); if (tolen + fromlen + 1 > tosize) { mch_memmove(to + tolen, from, tosize - tolen - 1); to[tosize - 1] = NUL; } else STRCPY(to + tolen, from); } /* * Isolate one part of a string option where parts are separated with * "sep_chars". * The part is copied into "buf[maxlen]". * "*option" is advanced to the next part. * The length is returned. */ int copy_option_part(option, buf, maxlen, sep_chars) char_u **option; char_u *buf; int maxlen; char *sep_chars; { int len = 0; char_u *p = *option; /* skip '.' at start of option part, for 'suffixes' */ if (*p == '.') buf[len++] = *p++; while (*p != NUL && vim_strchr((char_u *)sep_chars, *p) == NULL) { /* * Skip backslash before a separator character and space. */ if (p[0] == '\\' && vim_strchr((char_u *)sep_chars, p[1]) != NULL) ++p; if (len < maxlen - 1) buf[len++] = *p; ++p; } buf[len] = NUL; if (*p != NUL && *p != ',') /* skip non-standard separator */ ++p; p = skip_to_option_part(p); /* p points to next file name */ *option = p; return len; } /* * Replacement for free() that ignores NULL pointers. * Also skip free() when exiting for sure, this helps when we caught a deadly * signal that was caused by a crash in free(). */ void vim_free(x) void *x; { if (x != NULL && !really_exiting) { #ifdef MEM_PROFILE mem_pre_free(&x); #endif free(x); } } #ifndef HAVE_MEMSET void * vim_memset(ptr, c, size) void *ptr; int c; size_t size; { char *p = ptr; while (size-- > 0) *p++ = c; return ptr; } #endif #ifdef VIM_MEMCMP /* * Return zero when "b1" and "b2" are the same for "len" bytes. * Return non-zero otherwise. */ int vim_memcmp(b1, b2, len) void *b1; void *b2; size_t len; { char_u *p1 = (char_u *)b1, *p2 = (char_u *)b2; for ( ; len > 0; --len) { if (*p1 != *p2) return 1; ++p1; ++p2; } return 0; } #endif #ifdef VIM_MEMMOVE /* * Version of memmove() that handles overlapping source and destination. * For systems that don't have a function that is guaranteed to do that (SYSV). */ void mch_memmove(dst_arg, src_arg, len) void *src_arg, *dst_arg; size_t len; { /* * A void doesn't have a size, we use char pointers. */ char *dst = dst_arg, *src = src_arg; /* overlap, copy backwards */ if (dst > src && dst < src + len) { src += len; dst += len; while (len-- > 0) *--dst = *--src; } else /* copy forwards */ while (len-- > 0) *dst++ = *src++; } #endif #if (!defined(HAVE_STRCASECMP) && !defined(HAVE_STRICMP)) || defined(PROTO) /* * Compare two strings, ignoring case, using current locale. * Doesn't work for multi-byte characters. * return 0 for match, < 0 for smaller, > 0 for bigger */ int vim_stricmp(s1, s2) char *s1; char *s2; { int i; for (;;) { i = (int)TOLOWER_LOC(*s1) - (int)TOLOWER_LOC(*s2); if (i != 0) return i; /* this character different */ if (*s1 == NUL) break; /* strings match until NUL */ ++s1; ++s2; } return 0; /* strings match */ } #endif #if (!defined(HAVE_STRNCASECMP) && !defined(HAVE_STRNICMP)) || defined(PROTO) /* * Compare two strings, for length "len", ignoring case, using current locale. * Doesn't work for multi-byte characters. * return 0 for match, < 0 for smaller, > 0 for bigger */ int vim_strnicmp(s1, s2, len) char *s1; char *s2; size_t len; { int i; while (len > 0) { i = (int)TOLOWER_LOC(*s1) - (int)TOLOWER_LOC(*s2); if (i != 0) return i; /* this character different */ if (*s1 == NUL) break; /* strings match until NUL */ ++s1; ++s2; --len; } return 0; /* strings match */ } #endif /* * Version of strchr() and strrchr() that handle unsigned char strings * with characters from 128 to 255 correctly. It also doesn't return a * pointer to the NUL at the end of the string. */ char_u * vim_strchr(string, c) char_u *string; int c; { char_u *p; int b; p = string; #ifdef FEAT_MBYTE if (enc_utf8 && c >= 0x80) { while (*p != NUL) { if (utf_ptr2char(p) == c) return p; p += (*mb_ptr2len)(p); } return NULL; } if (enc_dbcs != 0 && c > 255) { int n2 = c & 0xff; c = ((unsigned)c >> 8) & 0xff; while ((b = *p) != NUL) { if (b == c && p[1] == n2) return p; p += (*mb_ptr2len)(p); } return NULL; } if (has_mbyte) { while ((b = *p) != NUL) { if (b == c) return p; p += (*mb_ptr2len)(p); } return NULL; } #endif while ((b = *p) != NUL) { if (b == c) return p; ++p; } return NULL; } /* * Version of strchr() that only works for bytes and handles unsigned char * strings with characters above 128 correctly. It also doesn't return a * pointer to the NUL at the end of the string. */ char_u * vim_strbyte(string, c) char_u *string; int c; { char_u *p = string; while (*p != NUL) { if (*p == c) return p; ++p; } return NULL; } /* * Search for last occurrence of "c" in "string". * Return NULL if not found. * Does not handle multi-byte char for "c"! */ char_u * vim_strrchr(string, c) char_u *string; int c; { char_u *retval = NULL; char_u *p = string; while (*p) { if (*p == c) retval = p; mb_ptr_adv(p); } return retval; } /* * Vim's version of strpbrk(), in case it's missing. * Don't generate a prototype for this, causes problems when it's not used. */ #ifndef PROTO # ifndef HAVE_STRPBRK # ifdef vim_strpbrk # undef vim_strpbrk # endif char_u * vim_strpbrk(s, charset) char_u *s; char_u *charset; { while (*s) { if (vim_strchr(charset, *s) != NULL) return s; mb_ptr_adv(s); } return NULL; } # endif #endif /* * Vim has its own isspace() function, because on some machines isspace() * can't handle characters above 128. */ int vim_isspace(x) int x; { return ((x >= 9 && x <= 13) || x == ' '); } /************************************************************************ * Functions for handling growing arrays. */ /* * Clear an allocated growing array. */ void ga_clear(gap) garray_T *gap; { vim_free(gap->ga_data); ga_init(gap); } /* * Clear a growing array that contains a list of strings. */ void ga_clear_strings(gap) garray_T *gap; { int i; for (i = 0; i < gap->ga_len; ++i) vim_free(((char_u **)(gap->ga_data))[i]); ga_clear(gap); } /* * Initialize a growing array. Don't forget to set ga_itemsize and * ga_growsize! Or use ga_init2(). */ void ga_init(gap) garray_T *gap; { gap->ga_data = NULL; gap->ga_maxlen = 0; gap->ga_len = 0; } void ga_init2(gap, itemsize, growsize) garray_T *gap; int itemsize; int growsize; { ga_init(gap); gap->ga_itemsize = itemsize; gap->ga_growsize = growsize; } /* * Make room in growing array "gap" for at least "n" items. * Return FAIL for failure, OK otherwise. */ int ga_grow(gap, n) garray_T *gap; int n; { size_t old_len; size_t new_len; char_u *pp; if (gap->ga_maxlen - gap->ga_len < n) { if (n < gap->ga_growsize) n = gap->ga_growsize; new_len = gap->ga_itemsize * (gap->ga_len + n); pp = (gap->ga_data == NULL) ? alloc((unsigned)new_len) : vim_realloc(gap->ga_data, new_len); if (pp == NULL) return FAIL; old_len = gap->ga_itemsize * gap->ga_maxlen; vim_memset(pp + old_len, 0, new_len - old_len); gap->ga_maxlen = gap->ga_len + n; gap->ga_data = pp; } return OK; } /* * For a growing array that contains a list of strings: concatenate all the * strings with a separating comma. * Returns NULL when out of memory. */ char_u * ga_concat_strings(gap) garray_T *gap; { int i; int len = 0; char_u *s; for (i = 0; i < gap->ga_len; ++i) len += (int)STRLEN(((char_u **)(gap->ga_data))[i]) + 1; s = alloc(len + 1); if (s != NULL) { *s = NUL; for (i = 0; i < gap->ga_len; ++i) { if (*s != NUL) STRCAT(s, ","); STRCAT(s, ((char_u **)(gap->ga_data))[i]); } } return s; } /* * Concatenate a string to a growarray which contains characters. * Note: Does NOT copy the NUL at the end! */ void ga_concat(gap, s) garray_T *gap; char_u *s; { int len = (int)STRLEN(s); if (ga_grow(gap, len) == OK) { mch_memmove((char *)gap->ga_data + gap->ga_len, s, (size_t)len); gap->ga_len += len; } } /* * Append one byte to a growarray which contains bytes. */ void ga_append(gap, c) garray_T *gap; int c; { if (ga_grow(gap, 1) == OK) { *((char *)gap->ga_data + gap->ga_len) = c; ++gap->ga_len; } } #if (defined(UNIX) && !defined(USE_SYSTEM)) || defined(WIN3264) /* * Append the text in "gap" below the cursor line and clear "gap". */ void append_ga_line(gap) garray_T *gap; { /* Remove trailing CR. */ if (gap->ga_len > 0 && !curbuf->b_p_bin && ((char_u *)gap->ga_data)[gap->ga_len - 1] == CAR) --gap->ga_len; ga_append(gap, NUL); ml_append(curwin->w_cursor.lnum++, gap->ga_data, 0, FALSE); gap->ga_len = 0; } #endif /************************************************************************ * functions that use lookup tables for various things, generally to do with * special key codes. */ /* * Some useful tables. */ static struct modmasktable { short mod_mask; /* Bit-mask for particular key modifier */ short mod_flag; /* Bit(s) for particular key modifier */ char_u name; /* Single letter name of modifier */ } mod_mask_table[] = { {MOD_MASK_ALT, MOD_MASK_ALT, (char_u)'M'}, {MOD_MASK_META, MOD_MASK_META, (char_u)'T'}, {MOD_MASK_CTRL, MOD_MASK_CTRL, (char_u)'C'}, {MOD_MASK_SHIFT, MOD_MASK_SHIFT, (char_u)'S'}, {MOD_MASK_MULTI_CLICK, MOD_MASK_2CLICK, (char_u)'2'}, {MOD_MASK_MULTI_CLICK, MOD_MASK_3CLICK, (char_u)'3'}, {MOD_MASK_MULTI_CLICK, MOD_MASK_4CLICK, (char_u)'4'}, #ifdef MACOS {MOD_MASK_CMD, MOD_MASK_CMD, (char_u)'D'}, #endif /* 'A' must be the last one */ {MOD_MASK_ALT, MOD_MASK_ALT, (char_u)'A'}, {0, 0, NUL} }; /* * Shifted key terminal codes and their unshifted equivalent. * Don't add mouse codes here, they are handled separately! */ #define MOD_KEYS_ENTRY_SIZE 5 static char_u modifier_keys_table[] = { /* mod mask with modifier without modifier */ MOD_MASK_SHIFT, '&', '9', '@', '1', /* begin */ MOD_MASK_SHIFT, '&', '0', '@', '2', /* cancel */ MOD_MASK_SHIFT, '*', '1', '@', '4', /* command */ MOD_MASK_SHIFT, '*', '2', '@', '5', /* copy */ MOD_MASK_SHIFT, '*', '3', '@', '6', /* create */ MOD_MASK_SHIFT, '*', '4', 'k', 'D', /* delete char */ MOD_MASK_SHIFT, '*', '5', 'k', 'L', /* delete line */ MOD_MASK_SHIFT, '*', '7', '@', '7', /* end */ MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_END, '@', '7', /* end */ MOD_MASK_SHIFT, '*', '9', '@', '9', /* exit */ MOD_MASK_SHIFT, '*', '0', '@', '0', /* find */ MOD_MASK_SHIFT, '#', '1', '%', '1', /* help */ MOD_MASK_SHIFT, '#', '2', 'k', 'h', /* home */ MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_HOME, 'k', 'h', /* home */ MOD_MASK_SHIFT, '#', '3', 'k', 'I', /* insert */ MOD_MASK_SHIFT, '#', '4', 'k', 'l', /* left arrow */ MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_LEFT, 'k', 'l', /* left arrow */ MOD_MASK_SHIFT, '%', 'a', '%', '3', /* message */ MOD_MASK_SHIFT, '%', 'b', '%', '4', /* move */ MOD_MASK_SHIFT, '%', 'c', '%', '5', /* next */ MOD_MASK_SHIFT, '%', 'd', '%', '7', /* options */ MOD_MASK_SHIFT, '%', 'e', '%', '8', /* previous */ MOD_MASK_SHIFT, '%', 'f', '%', '9', /* print */ MOD_MASK_SHIFT, '%', 'g', '%', '0', /* redo */ MOD_MASK_SHIFT, '%', 'h', '&', '3', /* replace */ MOD_MASK_SHIFT, '%', 'i', 'k', 'r', /* right arr. */ MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_RIGHT, 'k', 'r', /* right arr. */ MOD_MASK_SHIFT, '%', 'j', '&', '5', /* resume */ MOD_MASK_SHIFT, '!', '1', '&', '6', /* save */ MOD_MASK_SHIFT, '!', '2', '&', '7', /* suspend */ MOD_MASK_SHIFT, '!', '3', '&', '8', /* undo */ MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_UP, 'k', 'u', /* up arrow */ MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_DOWN, 'k', 'd', /* down arrow */ /* vt100 F1 */ MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF1, KS_EXTRA, (int)KE_XF1, MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF2, KS_EXTRA, (int)KE_XF2, MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF3, KS_EXTRA, (int)KE_XF3, MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF4, KS_EXTRA, (int)KE_XF4, MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F1, 'k', '1', /* F1 */ MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F2, 'k', '2', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F3, 'k', '3', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F4, 'k', '4', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F5, 'k', '5', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F6, 'k', '6', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F7, 'k', '7', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F8, 'k', '8', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F9, 'k', '9', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F10, 'k', ';', /* F10 */ MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F11, 'F', '1', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F12, 'F', '2', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F13, 'F', '3', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F14, 'F', '4', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F15, 'F', '5', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F16, 'F', '6', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F17, 'F', '7', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F18, 'F', '8', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F19, 'F', '9', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F20, 'F', 'A', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F21, 'F', 'B', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F22, 'F', 'C', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F23, 'F', 'D', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F24, 'F', 'E', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F25, 'F', 'F', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F26, 'F', 'G', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F27, 'F', 'H', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F28, 'F', 'I', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F29, 'F', 'J', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F30, 'F', 'K', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F31, 'F', 'L', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F32, 'F', 'M', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F33, 'F', 'N', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F34, 'F', 'O', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F35, 'F', 'P', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F36, 'F', 'Q', MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F37, 'F', 'R', /* TAB pseudo code*/ MOD_MASK_SHIFT, 'k', 'B', KS_EXTRA, (int)KE_TAB, NUL }; static struct key_name_entry { int key; /* Special key code or ascii value */ char_u *name; /* Name of key */ } key_names_table[] = { {' ', (char_u *)"Space"}, {TAB, (char_u *)"Tab"}, {K_TAB, (char_u *)"Tab"}, {NL, (char_u *)"NL"}, {NL, (char_u *)"NewLine"}, /* Alternative name */ {NL, (char_u *)"LineFeed"}, /* Alternative name */ {NL, (char_u *)"LF"}, /* Alternative name */ {CAR, (char_u *)"CR"}, {CAR, (char_u *)"Return"}, /* Alternative name */ {CAR, (char_u *)"Enter"}, /* Alternative name */ {K_BS, (char_u *)"BS"}, {K_BS, (char_u *)"BackSpace"}, /* Alternative name */ {ESC, (char_u *)"Esc"}, {CSI, (char_u *)"CSI"}, {K_CSI, (char_u *)"xCSI"}, {'|', (char_u *)"Bar"}, {'\\', (char_u *)"Bslash"}, {K_DEL, (char_u *)"Del"}, {K_DEL, (char_u *)"Delete"}, /* Alternative name */ {K_KDEL, (char_u *)"kDel"}, {K_UP, (char_u *)"Up"}, {K_DOWN, (char_u *)"Down"}, {K_LEFT, (char_u *)"Left"}, {K_RIGHT, (char_u *)"Right"}, {K_XUP, (char_u *)"xUp"}, {K_XDOWN, (char_u *)"xDown"}, {K_XLEFT, (char_u *)"xLeft"}, {K_XRIGHT, (char_u *)"xRight"}, {K_F1, (char_u *)"F1"}, {K_F2, (char_u *)"F2"}, {K_F3, (char_u *)"F3"}, {K_F4, (char_u *)"F4"}, {K_F5, (char_u *)"F5"}, {K_F6, (char_u *)"F6"}, {K_F7, (char_u *)"F7"}, {K_F8, (char_u *)"F8"}, {K_F9, (char_u *)"F9"}, {K_F10, (char_u *)"F10"}, {K_F11, (char_u *)"F11"}, {K_F12, (char_u *)"F12"}, {K_F13, (char_u *)"F13"}, {K_F14, (char_u *)"F14"}, {K_F15, (char_u *)"F15"}, {K_F16, (char_u *)"F16"}, {K_F17, (char_u *)"F17"}, {K_F18, (char_u *)"F18"}, {K_F19, (char_u *)"F19"}, {K_F20, (char_u *)"F20"}, {K_F21, (char_u *)"F21"}, {K_F22, (char_u *)"F22"}, {K_F23, (char_u *)"F23"}, {K_F24, (char_u *)"F24"}, {K_F25, (char_u *)"F25"}, {K_F26, (char_u *)"F26"}, {K_F27, (char_u *)"F27"}, {K_F28, (char_u *)"F28"}, {K_F29, (char_u *)"F29"}, {K_F30, (char_u *)"F30"}, {K_F31, (char_u *)"F31"}, {K_F32, (char_u *)"F32"}, {K_F33, (char_u *)"F33"}, {K_F34, (char_u *)"F34"}, {K_F35, (char_u *)"F35"}, {K_F36, (char_u *)"F36"}, {K_F37, (char_u *)"F37"}, {K_XF1, (char_u *)"xF1"}, {K_XF2, (char_u *)"xF2"}, {K_XF3, (char_u *)"xF3"}, {K_XF4, (char_u *)"xF4"}, {K_HELP, (char_u *)"Help"}, {K_UNDO, (char_u *)"Undo"}, {K_INS, (char_u *)"Insert"}, {K_INS, (char_u *)"Ins"}, /* Alternative name */ {K_KINS, (char_u *)"kInsert"}, {K_HOME, (char_u *)"Home"}, {K_KHOME, (char_u *)"kHome"}, {K_XHOME, (char_u *)"xHome"}, {K_ZHOME, (char_u *)"zHome"}, {K_END, (char_u *)"End"}, {K_KEND, (char_u *)"kEnd"}, {K_XEND, (char_u *)"xEnd"}, {K_ZEND, (char_u *)"zEnd"}, {K_PAGEUP, (char_u *)"PageUp"}, {K_PAGEDOWN, (char_u *)"PageDown"}, {K_KPAGEUP, (char_u *)"kPageUp"}, {K_KPAGEDOWN, (char_u *)"kPageDown"}, {K_KPLUS, (char_u *)"kPlus"}, {K_KMINUS, (char_u *)"kMinus"}, {K_KDIVIDE, (char_u *)"kDivide"}, {K_KMULTIPLY, (char_u *)"kMultiply"}, {K_KENTER, (char_u *)"kEnter"}, {K_KPOINT, (char_u *)"kPoint"}, {K_K0, (char_u *)"k0"}, {K_K1, (char_u *)"k1"}, {K_K2, (char_u *)"k2"}, {K_K3, (char_u *)"k3"}, {K_K4, (char_u *)"k4"}, {K_K5, (char_u *)"k5"}, {K_K6, (char_u *)"k6"}, {K_K7, (char_u *)"k7"}, {K_K8, (char_u *)"k8"}, {K_K9, (char_u *)"k9"}, {'<', (char_u *)"lt"}, {K_MOUSE, (char_u *)"Mouse"}, #ifdef FEAT_MOUSE_NET {K_NETTERM_MOUSE, (char_u *)"NetMouse"}, #endif #ifdef FEAT_MOUSE_DEC {K_DEC_MOUSE, (char_u *)"DecMouse"}, #endif #ifdef FEAT_MOUSE_JSB {K_JSBTERM_MOUSE, (char_u *)"JsbMouse"}, #endif #ifdef FEAT_MOUSE_PTERM {K_PTERM_MOUSE, (char_u *)"PtermMouse"}, #endif #ifdef FEAT_MOUSE_URXVT {K_URXVT_MOUSE, (char_u *)"UrxvtMouse"}, #endif {K_LEFTMOUSE, (char_u *)"LeftMouse"}, {K_LEFTMOUSE_NM, (char_u *)"LeftMouseNM"}, {K_LEFTDRAG, (char_u *)"LeftDrag"}, {K_LEFTRELEASE, (char_u *)"LeftRelease"}, {K_LEFTRELEASE_NM, (char_u *)"LeftReleaseNM"}, {K_MIDDLEMOUSE, (char_u *)"MiddleMouse"}, {K_MIDDLEDRAG, (char_u *)"MiddleDrag"}, {K_MIDDLERELEASE, (char_u *)"MiddleRelease"}, {K_RIGHTMOUSE, (char_u *)"RightMouse"}, {K_RIGHTDRAG, (char_u *)"RightDrag"}, {K_RIGHTRELEASE, (char_u *)"RightRelease"}, {K_MOUSEDOWN, (char_u *)"ScrollWheelUp"}, {K_MOUSEUP, (char_u *)"ScrollWheelDown"}, {K_MOUSELEFT, (char_u *)"ScrollWheelRight"}, {K_MOUSERIGHT, (char_u *)"ScrollWheelLeft"}, {K_MOUSEDOWN, (char_u *)"MouseDown"}, /* OBSOLETE: Use */ {K_MOUSEUP, (char_u *)"MouseUp"}, /* ScrollWheelXXX instead */ {K_X1MOUSE, (char_u *)"X1Mouse"}, {K_X1DRAG, (char_u *)"X1Drag"}, {K_X1RELEASE, (char_u *)"X1Release"}, {K_X2MOUSE, (char_u *)"X2Mouse"}, {K_X2DRAG, (char_u *)"X2Drag"}, {K_X2RELEASE, (char_u *)"X2Release"}, {K_DROP, (char_u *)"Drop"}, {K_ZERO, (char_u *)"Nul"}, #ifdef FEAT_EVAL {K_SNR, (char_u *)"SNR"}, #endif {K_PLUG, (char_u *)"Plug"}, {0, NULL} }; #define KEY_NAMES_TABLE_LEN (sizeof(key_names_table) / sizeof(struct key_name_entry)) #ifdef FEAT_MOUSE static struct mousetable { int pseudo_code; /* Code for pseudo mouse event */ int button; /* Which mouse button is it? */ int is_click; /* Is it a mouse button click event? */ int is_drag; /* Is it a mouse drag event? */ } mouse_table[] = { {(int)KE_LEFTMOUSE, MOUSE_LEFT, TRUE, FALSE}, #ifdef FEAT_GUI {(int)KE_LEFTMOUSE_NM, MOUSE_LEFT, TRUE, FALSE}, #endif {(int)KE_LEFTDRAG, MOUSE_LEFT, FALSE, TRUE}, {(int)KE_LEFTRELEASE, MOUSE_LEFT, FALSE, FALSE}, #ifdef FEAT_GUI {(int)KE_LEFTRELEASE_NM, MOUSE_LEFT, FALSE, FALSE}, #endif {(int)KE_MIDDLEMOUSE, MOUSE_MIDDLE, TRUE, FALSE}, {(int)KE_MIDDLEDRAG, MOUSE_MIDDLE, FALSE, TRUE}, {(int)KE_MIDDLERELEASE, MOUSE_MIDDLE, FALSE, FALSE}, {(int)KE_RIGHTMOUSE, MOUSE_RIGHT, TRUE, FALSE}, {(int)KE_RIGHTDRAG, MOUSE_RIGHT, FALSE, TRUE}, {(int)KE_RIGHTRELEASE, MOUSE_RIGHT, FALSE, FALSE}, {(int)KE_X1MOUSE, MOUSE_X1, TRUE, FALSE}, {(int)KE_X1DRAG, MOUSE_X1, FALSE, TRUE}, {(int)KE_X1RELEASE, MOUSE_X1, FALSE, FALSE}, {(int)KE_X2MOUSE, MOUSE_X2, TRUE, FALSE}, {(int)KE_X2DRAG, MOUSE_X2, FALSE, TRUE}, {(int)KE_X2RELEASE, MOUSE_X2, FALSE, FALSE}, /* DRAG without CLICK */ {(int)KE_IGNORE, MOUSE_RELEASE, FALSE, TRUE}, /* RELEASE without CLICK */ {(int)KE_IGNORE, MOUSE_RELEASE, FALSE, FALSE}, {0, 0, 0, 0}, }; #endif /* FEAT_MOUSE */ /* * Return the modifier mask bit (MOD_MASK_*) which corresponds to the given * modifier name ('S' for Shift, 'C' for Ctrl etc). */ int name_to_mod_mask(c) int c; { int i; c = TOUPPER_ASC(c); for (i = 0; mod_mask_table[i].mod_mask != 0; i++) if (c == mod_mask_table[i].name) return mod_mask_table[i].mod_flag; return 0; } /* * Check if if there is a special key code for "key" that includes the * modifiers specified. */ int simplify_key(key, modifiers) int key; int *modifiers; { int i; int key0; int key1; if (*modifiers & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT)) { /* TAB is a special case */ if (key == TAB && (*modifiers & MOD_MASK_SHIFT)) { *modifiers &= ~MOD_MASK_SHIFT; return K_S_TAB; } key0 = KEY2TERMCAP0(key); key1 = KEY2TERMCAP1(key); for (i = 0; modifier_keys_table[i] != NUL; i += MOD_KEYS_ENTRY_SIZE) if (key0 == modifier_keys_table[i + 3] && key1 == modifier_keys_table[i + 4] && (*modifiers & modifier_keys_table[i])) { *modifiers &= ~modifier_keys_table[i]; return TERMCAP2KEY(modifier_keys_table[i + 1], modifier_keys_table[i + 2]); } } return key; } /* * Change <xHome> to <Home>, <xUp> to <Up>, etc. */ int handle_x_keys(key) int key; { switch (key) { case K_XUP: return K_UP; case K_XDOWN: return K_DOWN; case K_XLEFT: return K_LEFT; case K_XRIGHT: return K_RIGHT; case K_XHOME: return K_HOME; case K_ZHOME: return K_HOME; case K_XEND: return K_END; case K_ZEND: return K_END; case K_XF1: return K_F1; case K_XF2: return K_F2; case K_XF3: return K_F3; case K_XF4: return K_F4; case K_S_XF1: return K_S_F1; case K_S_XF2: return K_S_F2; case K_S_XF3: return K_S_F3; case K_S_XF4: return K_S_F4; } return key; } /* * Return a string which contains the name of the given key when the given * modifiers are down. */ char_u * get_special_key_name(c, modifiers) int c; int modifiers; { static char_u string[MAX_KEY_NAME_LEN + 1]; int i, idx; int table_idx; char_u *s; string[0] = '<'; idx = 1; /* Key that stands for a normal character. */ if (IS_SPECIAL(c) && KEY2TERMCAP0(c) == KS_KEY) c = KEY2TERMCAP1(c); /* * Translate shifted special keys into unshifted keys and set modifier. * Same for CTRL and ALT modifiers. */ if (IS_SPECIAL(c)) { for (i = 0; modifier_keys_table[i] != 0; i += MOD_KEYS_ENTRY_SIZE) if ( KEY2TERMCAP0(c) == (int)modifier_keys_table[i + 1] && (int)KEY2TERMCAP1(c) == (int)modifier_keys_table[i + 2]) { modifiers |= modifier_keys_table[i]; c = TERMCAP2KEY(modifier_keys_table[i + 3], modifier_keys_table[i + 4]); break; } } /* try to find the key in the special key table */ table_idx = find_special_key_in_table(c); /* * When not a known special key, and not a printable character, try to * extract modifiers. */ if (c > 0 #ifdef FEAT_MBYTE && (*mb_char2len)(c) == 1 #endif ) { if (table_idx < 0 && (!vim_isprintc(c) || (c & 0x7f) == ' ') && (c & 0x80)) { c &= 0x7f; modifiers |= MOD_MASK_ALT; /* try again, to find the un-alted key in the special key table */ table_idx = find_special_key_in_table(c); } if (table_idx < 0 && !vim_isprintc(c) && c < ' ') { #ifdef EBCDIC c = CtrlChar(c); #else c += '@'; #endif modifiers |= MOD_MASK_CTRL; } } /* translate the modifier into a string */ for (i = 0; mod_mask_table[i].name != 'A'; i++) if ((modifiers & mod_mask_table[i].mod_mask) == mod_mask_table[i].mod_flag) { string[idx++] = mod_mask_table[i].name; string[idx++] = (char_u)'-'; } if (table_idx < 0) /* unknown special key, may output t_xx */ { if (IS_SPECIAL(c)) { string[idx++] = 't'; string[idx++] = '_'; string[idx++] = KEY2TERMCAP0(c); string[idx++] = KEY2TERMCAP1(c); } /* Not a special key, only modifiers, output directly */ else { #ifdef FEAT_MBYTE if (has_mbyte && (*mb_char2len)(c) > 1) idx += (*mb_char2bytes)(c, string + idx); else #endif if (vim_isprintc(c)) string[idx++] = c; else { s = transchar(c); while (*s) string[idx++] = *s++; } } } else /* use name of special key */ { STRCPY(string + idx, key_names_table[table_idx].name); idx = (int)STRLEN(string); } string[idx++] = '>'; string[idx] = NUL; return string; } /* * Try translating a <> name at (*srcp)[] to dst[]. * Return the number of characters added to dst[], zero for no match. * If there is a match, srcp is advanced to after the <> name. * dst[] must be big enough to hold the result (up to six characters)! */ int trans_special(srcp, dst, keycode) char_u **srcp; char_u *dst; int keycode; /* prefer key code, e.g. K_DEL instead of DEL */ { int modifiers = 0; int key; int dlen = 0; key = find_special_key(srcp, &modifiers, keycode, FALSE); if (key == 0) return 0; /* Put the appropriate modifier in a string */ if (modifiers != 0) { dst[dlen++] = K_SPECIAL; dst[dlen++] = KS_MODIFIER; dst[dlen++] = modifiers; } if (IS_SPECIAL(key)) { dst[dlen++] = K_SPECIAL; dst[dlen++] = KEY2TERMCAP0(key); dst[dlen++] = KEY2TERMCAP1(key); } #ifdef FEAT_MBYTE else if (has_mbyte && !keycode) dlen += (*mb_char2bytes)(key, dst + dlen); #endif else if (keycode) dlen = (int)(add_char2buf(key, dst + dlen) - dst); else dst[dlen++] = key; return dlen; } /* * Try translating a <> name at (*srcp)[], return the key and modifiers. * srcp is advanced to after the <> name. * returns 0 if there is no match. */ int find_special_key(srcp, modp, keycode, keep_x_key) char_u **srcp; int *modp; int keycode; /* prefer key code, e.g. K_DEL instead of DEL */ int keep_x_key; /* don't translate xHome to Home key */ { char_u *last_dash; char_u *end_of_name; char_u *src; char_u *bp; int modifiers; int bit; int key; unsigned long n; int l; src = *srcp; if (src[0] != '<') return 0; /* Find end of modifier list */ last_dash = src; for (bp = src + 1; *bp == '-' || vim_isIDc(*bp); bp++) { if (*bp == '-') { last_dash = bp; if (bp[1] != NUL) { #ifdef FEAT_MBYTE if (has_mbyte) l = mb_ptr2len(bp + 1); else #endif l = 1; if (bp[l + 1] == '>') bp += l; /* anything accepted, like <C-?> */ } } if (bp[0] == 't' && bp[1] == '_' && bp[2] && bp[3]) bp += 3; /* skip t_xx, xx may be '-' or '>' */ else if (STRNICMP(bp, "char-", 5) == 0) { vim_str2nr(bp + 5, NULL, &l, TRUE, TRUE, NULL, NULL); bp += l + 5; break; } } if (*bp == '>') /* found matching '>' */ { end_of_name = bp + 1; /* Which modifiers are given? */ modifiers = 0x0; for (bp = src + 1; bp < last_dash; bp++) { if (*bp != '-') { bit = name_to_mod_mask(*bp); if (bit == 0x0) break; /* Illegal modifier name */ modifiers |= bit; } } /* * Legal modifier name. */ if (bp >= last_dash) { if (STRNICMP(last_dash + 1, "char-", 5) == 0 && VIM_ISDIGIT(last_dash[6])) { /* <Char-123> or <Char-033> or <Char-0x33> */ vim_str2nr(last_dash + 6, NULL, NULL, TRUE, TRUE, NULL, &n); key = (int)n; } else { /* * Modifier with single letter, or special key name. */ #ifdef FEAT_MBYTE if (has_mbyte) l = mb_ptr2len(last_dash + 1); else #endif l = 1; if (modifiers != 0 && last_dash[l + 1] == '>') key = PTR2CHAR(last_dash + 1); else { key = get_special_key_code(last_dash + 1); if (!keep_x_key) key = handle_x_keys(key); } } /* * get_special_key_code() may return NUL for invalid * special key name. */ if (key != NUL) { /* * Only use a modifier when there is no special key code that * includes the modifier. */ key = simplify_key(key, &modifiers); if (!keycode) { /* don't want keycode, use single byte code */ if (key == K_BS) key = BS; else if (key == K_DEL || key == K_KDEL) key = DEL; } /* * Normal Key with modifier: Try to make a single byte code. */ if (!IS_SPECIAL(key)) key = extract_modifiers(key, &modifiers); *modp = modifiers; *srcp = end_of_name; return key; } } } return 0; } /* * Try to include modifiers in the key. * Changes "Shift-a" to 'A', "Alt-A" to 0xc0, etc. */ int extract_modifiers(key, modp) int key; int *modp; { int modifiers = *modp; #ifdef MACOS /* Command-key really special, No fancynest */ if (!(modifiers & MOD_MASK_CMD)) #endif if ((modifiers & MOD_MASK_SHIFT) && ASCII_ISALPHA(key)) { key = TOUPPER_ASC(key); modifiers &= ~MOD_MASK_SHIFT; } if ((modifiers & MOD_MASK_CTRL) #ifdef EBCDIC /* * TODO: EBCDIC Better use: * && (Ctrl_chr(key) || key == '?') * ??? */ && strchr("?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_", key) != NULL #else && ((key >= '?' && key <= '_') || ASCII_ISALPHA(key)) #endif ) { key = Ctrl_chr(key); modifiers &= ~MOD_MASK_CTRL; /* <C-@> is <Nul> */ if (key == 0) key = K_ZERO; } #ifdef MACOS /* Command-key really special, No fancynest */ if (!(modifiers & MOD_MASK_CMD)) #endif if ((modifiers & MOD_MASK_ALT) && key < 0x80 #ifdef FEAT_MBYTE && !enc_dbcs /* avoid creating a lead byte */ #endif ) { key |= 0x80; modifiers &= ~MOD_MASK_ALT; /* remove the META modifier */ } *modp = modifiers; return key; } /* * Try to find key "c" in the special key table. * Return the index when found, -1 when not found. */ int find_special_key_in_table(c) int c; { int i; for (i = 0; key_names_table[i].name != NULL; i++) if (c == key_names_table[i].key) break; if (key_names_table[i].name == NULL) i = -1; return i; } /* * Find the special key with the given name (the given string does not have to * end with NUL, the name is assumed to end before the first non-idchar). * If the name starts with "t_" the next two characters are interpreted as a * termcap name. * Return the key code, or 0 if not found. */ int get_special_key_code(name) char_u *name; { char_u *table_name; char_u string[3]; int i, j; /* * If it's <t_xx> we get the code for xx from the termcap */ if (name[0] == 't' && name[1] == '_' && name[2] != NUL && name[3] != NUL) { string[0] = name[2]; string[1] = name[3]; string[2] = NUL; if (add_termcap_entry(string, FALSE) == OK) return TERMCAP2KEY(name[2], name[3]); } else for (i = 0; key_names_table[i].name != NULL; i++) { table_name = key_names_table[i].name; for (j = 0; vim_isIDc(name[j]) && table_name[j] != NUL; j++) if (TOLOWER_ASC(table_name[j]) != TOLOWER_ASC(name[j])) break; if (!vim_isIDc(name[j]) && table_name[j] == NUL) return key_names_table[i].key; } return 0; } #if defined(FEAT_CMDL_COMPL) || defined(PROTO) char_u * get_key_name(i) int i; { if (i >= (int)KEY_NAMES_TABLE_LEN) return NULL; return key_names_table[i].name; } #endif #if defined(FEAT_MOUSE) || defined(PROTO) /* * Look up the given mouse code to return the relevant information in the other * arguments. Return which button is down or was released. */ int get_mouse_button(code, is_click, is_drag) int code; int *is_click; int *is_drag; { int i; for (i = 0; mouse_table[i].pseudo_code; i++) if (code == mouse_table[i].pseudo_code) { *is_click = mouse_table[i].is_click; *is_drag = mouse_table[i].is_drag; return mouse_table[i].button; } return 0; /* Shouldn't get here */ } /* * Return the appropriate pseudo mouse event token (KE_LEFTMOUSE etc) based on * the given information about which mouse button is down, and whether the * mouse was clicked, dragged or released. */ int get_pseudo_mouse_code(button, is_click, is_drag) int button; /* eg MOUSE_LEFT */ int is_click; int is_drag; { int i; for (i = 0; mouse_table[i].pseudo_code; i++) if (button == mouse_table[i].button && is_click == mouse_table[i].is_click && is_drag == mouse_table[i].is_drag) { #ifdef FEAT_GUI /* Trick: a non mappable left click and release has mouse_col -1 * or added MOUSE_COLOFF. Used for 'mousefocus' in * gui_mouse_moved() */ if (mouse_col < 0 || mouse_col > MOUSE_COLOFF) { if (mouse_col < 0) mouse_col = 0; else mouse_col -= MOUSE_COLOFF; if (mouse_table[i].pseudo_code == (int)KE_LEFTMOUSE) return (int)KE_LEFTMOUSE_NM; if (mouse_table[i].pseudo_code == (int)KE_LEFTRELEASE) return (int)KE_LEFTRELEASE_NM; } #endif return mouse_table[i].pseudo_code; } return (int)KE_IGNORE; /* not recognized, ignore it */ } #endif /* FEAT_MOUSE */ /* * Return the current end-of-line type: EOL_DOS, EOL_UNIX or EOL_MAC. */ int get_fileformat(buf) buf_T *buf; { int c = *buf->b_p_ff; if (buf->b_p_bin || c == 'u') return EOL_UNIX; if (c == 'm') return EOL_MAC; return EOL_DOS; } /* * Like get_fileformat(), but override 'fileformat' with "p" for "++opt=val" * argument. */ int get_fileformat_force(buf, eap) buf_T *buf; exarg_T *eap; /* can be NULL! */ { int c; if (eap != NULL && eap->force_ff != 0) c = eap->cmd[eap->force_ff]; else { if ((eap != NULL && eap->force_bin != 0) ? (eap->force_bin == FORCE_BIN) : buf->b_p_bin) return EOL_UNIX; c = *buf->b_p_ff; } if (c == 'u') return EOL_UNIX; if (c == 'm') return EOL_MAC; return EOL_DOS; } /* * Set the current end-of-line type to EOL_DOS, EOL_UNIX or EOL_MAC. * Sets both 'textmode' and 'fileformat'. * Note: Does _not_ set global value of 'textmode'! */ void set_fileformat(t, opt_flags) int t; int opt_flags; /* OPT_LOCAL and/or OPT_GLOBAL */ { char *p = NULL; switch (t) { case EOL_DOS: p = FF_DOS; curbuf->b_p_tx = TRUE; break; case EOL_UNIX: p = FF_UNIX; curbuf->b_p_tx = FALSE; break; case EOL_MAC: p = FF_MAC; curbuf->b_p_tx = FALSE; break; } if (p != NULL) set_string_option_direct((char_u *)"ff", -1, (char_u *)p, OPT_FREE | opt_flags, 0); #ifdef FEAT_WINDOWS /* This may cause the buffer to become (un)modified. */ check_status(curbuf); redraw_tabline = TRUE; #endif #ifdef FEAT_TITLE need_maketitle = TRUE; /* set window title later */ #endif } /* * Return the default fileformat from 'fileformats'. */ int default_fileformat() { switch (*p_ffs) { case 'm': return EOL_MAC; case 'd': return EOL_DOS; } return EOL_UNIX; } /* * Call shell. Calls mch_call_shell, with 'shellxquote' added. */ int call_shell(cmd, opt) char_u *cmd; int opt; { char_u *ncmd; int retval; #ifdef FEAT_PROFILE proftime_T wait_time; #endif if (p_verbose > 3) { verbose_enter(); smsg((char_u *)_("Calling shell to execute: \"%s\""), cmd == NULL ? p_sh : cmd); out_char('\n'); cursor_on(); verbose_leave(); } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) prof_child_enter(&wait_time); #endif if (*p_sh == NUL) { EMSG(_(e_shellempty)); retval = -1; } else { #ifdef FEAT_GUI_MSWIN /* Don't hide the pointer while executing a shell command. */ gui_mch_mousehide(FALSE); #endif #ifdef FEAT_GUI ++hold_gui_events; #endif /* The external command may update a tags file, clear cached tags. */ tag_freematch(); if (cmd == NULL || *p_sxq == NUL) retval = mch_call_shell(cmd, opt); else { char_u *ecmd = cmd; if (*p_sxe != NUL && STRCMP(p_sxq, "(") == 0) { ecmd = vim_strsave_escaped_ext(cmd, p_sxe, '^', FALSE); if (ecmd == NULL) ecmd = cmd; } ncmd = alloc((unsigned)(STRLEN(ecmd) + STRLEN(p_sxq) * 2 + 1)); if (ncmd != NULL) { STRCPY(ncmd, p_sxq); STRCAT(ncmd, ecmd); /* When 'shellxquote' is ( append ). * When 'shellxquote' is "( append )". */ STRCAT(ncmd, STRCMP(p_sxq, "(") == 0 ? (char_u *)")" : STRCMP(p_sxq, "\"(") == 0 ? (char_u *)")\"" : p_sxq); retval = mch_call_shell(ncmd, opt); vim_free(ncmd); } else retval = -1; if (ecmd != cmd) vim_free(ecmd); } #ifdef FEAT_GUI --hold_gui_events; #endif /* * Check the window size, in case it changed while executing the * external command. */ shell_resized_check(); } #ifdef FEAT_EVAL set_vim_var_nr(VV_SHELL_ERROR, (long)retval); # ifdef FEAT_PROFILE if (do_profiling == PROF_YES) prof_child_exit(&wait_time); # endif #endif return retval; } /* * VISUAL, SELECTMODE and OP_PENDING State are never set, they are equal to * NORMAL State with a condition. This function returns the real State. */ int get_real_state() { if (State & NORMAL) { #ifdef FEAT_VISUAL if (VIsual_active) { if (VIsual_select) return SELECTMODE; return VISUAL; } else #endif if (finish_op) return OP_PENDING; } return State; } #if defined(FEAT_MBYTE) || defined(PROTO) /* * Return TRUE if "p" points to just after a path separator. * Takes care of multi-byte characters. * "b" must point to the start of the file name */ int after_pathsep(b, p) char_u *b; char_u *p; { return p > b && vim_ispathsep(p[-1]) && (!has_mbyte || (*mb_head_off)(b, p - 1) == 0); } #endif /* * Return TRUE if file names "f1" and "f2" are in the same directory. * "f1" may be a short name, "f2" must be a full path. */ int same_directory(f1, f2) char_u *f1; char_u *f2; { char_u ffname[MAXPATHL]; char_u *t1; char_u *t2; /* safety check */ if (f1 == NULL || f2 == NULL) return FALSE; (void)vim_FullName(f1, ffname, MAXPATHL, FALSE); t1 = gettail_sep(ffname); t2 = gettail_sep(f2); return (t1 - ffname == t2 - f2 && pathcmp((char *)ffname, (char *)f2, (int)(t1 - ffname)) == 0); } #if defined(FEAT_SESSION) || defined(MSWIN) || defined(FEAT_GUI_MAC) \ || ((defined(FEAT_GUI_GTK)) \ && ( defined(FEAT_WINDOWS) || defined(FEAT_DND)) ) \ || defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG) \ || defined(PROTO) /* * Change to a file's directory. * Caller must call shorten_fnames()! * Return OK or FAIL. */ int vim_chdirfile(fname) char_u *fname; { char_u dir[MAXPATHL]; vim_strncpy(dir, fname, MAXPATHL - 1); *gettail_sep(dir) = NUL; return mch_chdir((char *)dir) == 0 ? OK : FAIL; } #endif #if defined(STAT_IGNORES_SLASH) || defined(PROTO) /* * Check if "name" ends in a slash and is not a directory. * Used for systems where stat() ignores a trailing slash on a file name. * The Vim code assumes a trailing slash is only ignored for a directory. */ int illegal_slash(name) char *name; { if (name[0] == NUL) return FALSE; /* no file name is not illegal */ if (name[strlen(name) - 1] != '/') return FALSE; /* no trailing slash */ if (mch_isdir((char_u *)name)) return FALSE; /* trailing slash for a directory */ return TRUE; } #endif #if defined(CURSOR_SHAPE) || defined(PROTO) /* * Handling of cursor and mouse pointer shapes in various modes. */ cursorentry_T shape_table[SHAPE_IDX_COUNT] = { /* The values will be filled in from the 'guicursor' and 'mouseshape' * defaults when Vim starts. * Adjust the SHAPE_IDX_ defines when making changes! */ {0, 0, 0, 700L, 400L, 250L, 0, 0, "n", SHAPE_CURSOR+SHAPE_MOUSE}, {0, 0, 0, 700L, 400L, 250L, 0, 0, "v", SHAPE_CURSOR+SHAPE_MOUSE}, {0, 0, 0, 700L, 400L, 250L, 0, 0, "i", SHAPE_CURSOR+SHAPE_MOUSE}, {0, 0, 0, 700L, 400L, 250L, 0, 0, "r", SHAPE_CURSOR+SHAPE_MOUSE}, {0, 0, 0, 700L, 400L, 250L, 0, 0, "c", SHAPE_CURSOR+SHAPE_MOUSE}, {0, 0, 0, 700L, 400L, 250L, 0, 0, "ci", SHAPE_CURSOR+SHAPE_MOUSE}, {0, 0, 0, 700L, 400L, 250L, 0, 0, "cr", SHAPE_CURSOR+SHAPE_MOUSE}, {0, 0, 0, 700L, 400L, 250L, 0, 0, "o", SHAPE_CURSOR+SHAPE_MOUSE}, {0, 0, 0, 700L, 400L, 250L, 0, 0, "ve", SHAPE_CURSOR+SHAPE_MOUSE}, {0, 0, 0, 0L, 0L, 0L, 0, 0, "e", SHAPE_MOUSE}, {0, 0, 0, 0L, 0L, 0L, 0, 0, "s", SHAPE_MOUSE}, {0, 0, 0, 0L, 0L, 0L, 0, 0, "sd", SHAPE_MOUSE}, {0, 0, 0, 0L, 0L, 0L, 0, 0, "vs", SHAPE_MOUSE}, {0, 0, 0, 0L, 0L, 0L, 0, 0, "vd", SHAPE_MOUSE}, {0, 0, 0, 0L, 0L, 0L, 0, 0, "m", SHAPE_MOUSE}, {0, 0, 0, 0L, 0L, 0L, 0, 0, "ml", SHAPE_MOUSE}, {0, 0, 0, 100L, 100L, 100L, 0, 0, "sm", SHAPE_CURSOR}, }; #ifdef FEAT_MOUSESHAPE /* * Table with names for mouse shapes. Keep in sync with all the tables for * mch_set_mouse_shape()!. */ static char * mshape_names[] = { "arrow", /* default, must be the first one */ "blank", /* hidden */ "beam", "updown", "udsizing", "leftright", "lrsizing", "busy", "no", "crosshair", "hand1", "hand2", "pencil", "question", "rightup-arrow", "up-arrow", NULL }; #endif /* * Parse the 'guicursor' option ("what" is SHAPE_CURSOR) or 'mouseshape' * ("what" is SHAPE_MOUSE). * Returns error message for an illegal option, NULL otherwise. */ char_u * parse_shape_opt(what) int what; { char_u *modep; char_u *colonp; char_u *commap; char_u *slashp; char_u *p, *endp; int idx = 0; /* init for GCC */ int all_idx; int len; int i; long n; int found_ve = FALSE; /* found "ve" flag */ int round; /* * First round: check for errors; second round: do it for real. */ for (round = 1; round <= 2; ++round) { /* * Repeat for all comma separated parts. */ #ifdef FEAT_MOUSESHAPE if (what == SHAPE_MOUSE) modep = p_mouseshape; else #endif modep = p_guicursor; while (*modep != NUL) { colonp = vim_strchr(modep, ':'); if (colonp == NULL) return (char_u *)N_("E545: Missing colon"); if (colonp == modep) return (char_u *)N_("E546: Illegal mode"); commap = vim_strchr(modep, ','); /* * Repeat for all mode's before the colon. * For the 'a' mode, we loop to handle all the modes. */ all_idx = -1; while (modep < colonp || all_idx >= 0) { if (all_idx < 0) { /* Find the mode. */ if (modep[1] == '-' || modep[1] == ':') len = 1; else len = 2; if (len == 1 && TOLOWER_ASC(modep[0]) == 'a') all_idx = SHAPE_IDX_COUNT - 1; else { for (idx = 0; idx < SHAPE_IDX_COUNT; ++idx) if (STRNICMP(modep, shape_table[idx].name, len) == 0) break; if (idx == SHAPE_IDX_COUNT || (shape_table[idx].used_for & what) == 0) return (char_u *)N_("E546: Illegal mode"); if (len == 2 && modep[0] == 'v' && modep[1] == 'e') found_ve = TRUE; } modep += len + 1; } if (all_idx >= 0) idx = all_idx--; else if (round == 2) { #ifdef FEAT_MOUSESHAPE if (what == SHAPE_MOUSE) { /* Set the default, for the missing parts */ shape_table[idx].mshape = 0; } else #endif { /* Set the defaults, for the missing parts */ shape_table[idx].shape = SHAPE_BLOCK; shape_table[idx].blinkwait = 700L; shape_table[idx].blinkon = 400L; shape_table[idx].blinkoff = 250L; } } /* Parse the part after the colon */ for (p = colonp + 1; *p && *p != ','; ) { #ifdef FEAT_MOUSESHAPE if (what == SHAPE_MOUSE) { for (i = 0; ; ++i) { if (mshape_names[i] == NULL) { if (!VIM_ISDIGIT(*p)) return (char_u *)N_("E547: Illegal mouseshape"); if (round == 2) shape_table[idx].mshape = getdigits(&p) + MSHAPE_NUMBERED; else (void)getdigits(&p); break; } len = (int)STRLEN(mshape_names[i]); if (STRNICMP(p, mshape_names[i], len) == 0) { if (round == 2) shape_table[idx].mshape = i; p += len; break; } } } else /* if (what == SHAPE_MOUSE) */ #endif { /* * First handle the ones with a number argument. */ i = *p; len = 0; if (STRNICMP(p, "ver", 3) == 0) len = 3; else if (STRNICMP(p, "hor", 3) == 0) len = 3; else if (STRNICMP(p, "blinkwait", 9) == 0) len = 9; else if (STRNICMP(p, "blinkon", 7) == 0) len = 7; else if (STRNICMP(p, "blinkoff", 8) == 0) len = 8; if (len != 0) { p += len; if (!VIM_ISDIGIT(*p)) return (char_u *)N_("E548: digit expected"); n = getdigits(&p); if (len == 3) /* "ver" or "hor" */ { if (n == 0) return (char_u *)N_("E549: Illegal percentage"); if (round == 2) { if (TOLOWER_ASC(i) == 'v') shape_table[idx].shape = SHAPE_VER; else shape_table[idx].shape = SHAPE_HOR; shape_table[idx].percentage = n; } } else if (round == 2) { if (len == 9) shape_table[idx].blinkwait = n; else if (len == 7) shape_table[idx].blinkon = n; else shape_table[idx].blinkoff = n; } } else if (STRNICMP(p, "block", 5) == 0) { if (round == 2) shape_table[idx].shape = SHAPE_BLOCK; p += 5; } else /* must be a highlight group name then */ { endp = vim_strchr(p, '-'); if (commap == NULL) /* last part */ { if (endp == NULL) endp = p + STRLEN(p); /* find end of part */ } else if (endp > commap || endp == NULL) endp = commap; slashp = vim_strchr(p, '/'); if (slashp != NULL && slashp < endp) { /* "group/langmap_group" */ i = syn_check_group(p, (int)(slashp - p)); p = slashp + 1; } if (round == 2) { shape_table[idx].id = syn_check_group(p, (int)(endp - p)); shape_table[idx].id_lm = shape_table[idx].id; if (slashp != NULL && slashp < endp) shape_table[idx].id = i; } p = endp; } } /* if (what != SHAPE_MOUSE) */ if (*p == '-') ++p; } } modep = p; if (*modep == ',') ++modep; } } /* If the 's' flag is not given, use the 'v' cursor for 's' */ if (!found_ve) { #ifdef FEAT_MOUSESHAPE if (what == SHAPE_MOUSE) { shape_table[SHAPE_IDX_VE].mshape = shape_table[SHAPE_IDX_V].mshape; } else #endif { shape_table[SHAPE_IDX_VE].shape = shape_table[SHAPE_IDX_V].shape; shape_table[SHAPE_IDX_VE].percentage = shape_table[SHAPE_IDX_V].percentage; shape_table[SHAPE_IDX_VE].blinkwait = shape_table[SHAPE_IDX_V].blinkwait; shape_table[SHAPE_IDX_VE].blinkon = shape_table[SHAPE_IDX_V].blinkon; shape_table[SHAPE_IDX_VE].blinkoff = shape_table[SHAPE_IDX_V].blinkoff; shape_table[SHAPE_IDX_VE].id = shape_table[SHAPE_IDX_V].id; shape_table[SHAPE_IDX_VE].id_lm = shape_table[SHAPE_IDX_V].id_lm; } } return NULL; } # if defined(MCH_CURSOR_SHAPE) || defined(FEAT_GUI) \ || defined(FEAT_MOUSESHAPE) || defined(PROTO) /* * Return the index into shape_table[] for the current mode. * When "mouse" is TRUE, consider indexes valid for the mouse pointer. */ int get_shape_idx(mouse) int mouse; { #ifdef FEAT_MOUSESHAPE if (mouse && (State == HITRETURN || State == ASKMORE)) { # ifdef FEAT_GUI int x, y; gui_mch_getmouse(&x, &y); if (Y_2_ROW(y) == Rows - 1) return SHAPE_IDX_MOREL; # endif return SHAPE_IDX_MORE; } if (mouse && drag_status_line) return SHAPE_IDX_SDRAG; # ifdef FEAT_VERTSPLIT if (mouse && drag_sep_line) return SHAPE_IDX_VDRAG; # endif #endif if (!mouse && State == SHOWMATCH) return SHAPE_IDX_SM; #ifdef FEAT_VREPLACE if (State & VREPLACE_FLAG) return SHAPE_IDX_R; #endif if (State & REPLACE_FLAG) return SHAPE_IDX_R; if (State & INSERT) return SHAPE_IDX_I; if (State & CMDLINE) { if (cmdline_at_end()) return SHAPE_IDX_C; if (cmdline_overstrike()) return SHAPE_IDX_CR; return SHAPE_IDX_CI; } if (finish_op) return SHAPE_IDX_O; #ifdef FEAT_VISUAL if (VIsual_active) { if (*p_sel == 'e') return SHAPE_IDX_VE; else return SHAPE_IDX_V; } #endif return SHAPE_IDX_N; } #endif # if defined(FEAT_MOUSESHAPE) || defined(PROTO) static int old_mouse_shape = 0; /* * Set the mouse shape: * If "shape" is -1, use shape depending on the current mode, * depending on the current state. * If "shape" is -2, only update the shape when it's CLINE or STATUS (used * when the mouse moves off the status or command line). */ void update_mouseshape(shape_idx) int shape_idx; { int new_mouse_shape; /* Only works in GUI mode. */ if (!gui.in_use || gui.starting) return; /* Postpone the updating when more is to come. Speeds up executing of * mappings. */ if (shape_idx == -1 && char_avail()) { postponed_mouseshape = TRUE; return; } /* When ignoring the mouse don't change shape on the statusline. */ if (*p_mouse == NUL && (shape_idx == SHAPE_IDX_CLINE || shape_idx == SHAPE_IDX_STATUS || shape_idx == SHAPE_IDX_VSEP)) shape_idx = -2; if (shape_idx == -2 && old_mouse_shape != shape_table[SHAPE_IDX_CLINE].mshape && old_mouse_shape != shape_table[SHAPE_IDX_STATUS].mshape && old_mouse_shape != shape_table[SHAPE_IDX_VSEP].mshape) return; if (shape_idx < 0) new_mouse_shape = shape_table[get_shape_idx(TRUE)].mshape; else new_mouse_shape = shape_table[shape_idx].mshape; if (new_mouse_shape != old_mouse_shape) { mch_set_mouse_shape(new_mouse_shape); old_mouse_shape = new_mouse_shape; } postponed_mouseshape = FALSE; } # endif #endif /* CURSOR_SHAPE */ #ifdef FEAT_CRYPT /* * Optional encryption support. * Mohsin Ahmed, mosh@sasi.com, 98-09-24 * Based on zip/crypt sources. * * NOTE FOR USA: Since 2000 exporting this code from the USA is allowed to * most countries. There are a few exceptions, but that still should not be a * problem since this code was originally created in Europe and India. * * Blowfish addition originally made by Mohsin Ahmed, * http://www.cs.albany.edu/~mosh 2010-03-14 * Based on blowfish by Bruce Schneier (http://www.schneier.com/blowfish.html) * and sha256 by Christophe Devine. */ /* from zip.h */ typedef unsigned short ush; /* unsigned 16-bit value */ typedef unsigned long ulg; /* unsigned 32-bit value */ static void make_crc_tab __ARGS((void)); static ulg crc_32_tab[256]; /* * Fill the CRC table. */ static void make_crc_tab() { ulg s,t,v; static int done = FALSE; if (done) return; for (t = 0; t < 256; t++) { v = t; for (s = 0; s < 8; s++) v = (v >> 1) ^ ((v & 1) * (ulg)0xedb88320L); crc_32_tab[t] = v; } done = TRUE; } #define CRC32(c, b) (crc_32_tab[((int)(c) ^ (b)) & 0xff] ^ ((c) >> 8)) static ulg keys[3]; /* keys defining the pseudo-random sequence */ /* * Return the next byte in the pseudo-random sequence. */ #define DECRYPT_BYTE_ZIP(t) { \ ush temp; \ \ temp = (ush)keys[2] | 2; \ t = (int)(((unsigned)(temp * (temp ^ 1)) >> 8) & 0xff); \ } /* * Update the encryption keys with the next byte of plain text. */ #define UPDATE_KEYS_ZIP(c) { \ keys[0] = CRC32(keys[0], (c)); \ keys[1] += keys[0] & 0xff; \ keys[1] = keys[1] * 134775813L + 1; \ keys[2] = CRC32(keys[2], (int)(keys[1] >> 24)); \ } static int crypt_busy = 0; static ulg saved_keys[3]; static int saved_crypt_method; /* * Return int value for crypt method string: * 0 for "zip", the old method. Also for any non-valid value. * 1 for "blowfish". */ int crypt_method_from_string(s) char_u *s; { return *s == 'b' ? 1 : 0; } /* * Get the crypt method for buffer "buf" as a number. */ int get_crypt_method(buf) buf_T *buf; { return crypt_method_from_string(*buf->b_p_cm == NUL ? p_cm : buf->b_p_cm); } /* * Set the crypt method for buffer "buf" to "method" using the int value as * returned by crypt_method_from_string(). */ void set_crypt_method(buf, method) buf_T *buf; int method; { free_string_option(buf->b_p_cm); buf->b_p_cm = vim_strsave((char_u *)(method == 0 ? "zip" : "blowfish")); } /* * Prepare for initializing encryption. If already doing encryption then save * the state. * Must always be called symmetrically with crypt_pop_state(). */ void crypt_push_state() { if (crypt_busy == 1) { /* save the state */ if (use_crypt_method == 0) { saved_keys[0] = keys[0]; saved_keys[1] = keys[1]; saved_keys[2] = keys[2]; } else bf_crypt_save(); saved_crypt_method = use_crypt_method; } else if (crypt_busy > 1) EMSG2(_(e_intern2), "crypt_push_state()"); ++crypt_busy; } /* * End encryption. If doing encryption before crypt_push_state() then restore * the saved state. * Must always be called symmetrically with crypt_push_state(). */ void crypt_pop_state() { --crypt_busy; if (crypt_busy == 1) { use_crypt_method = saved_crypt_method; if (use_crypt_method == 0) { keys[0] = saved_keys[0]; keys[1] = saved_keys[1]; keys[2] = saved_keys[2]; } else bf_crypt_restore(); } } /* * Encrypt "from[len]" into "to[len]". * "from" and "to" can be equal to encrypt in place. */ void crypt_encode(from, len, to) char_u *from; size_t len; char_u *to; { size_t i; int ztemp, t; if (use_crypt_method == 0) for (i = 0; i < len; ++i) { ztemp = from[i]; DECRYPT_BYTE_ZIP(t); UPDATE_KEYS_ZIP(ztemp); to[i] = t ^ ztemp; } else bf_crypt_encode(from, len, to); } /* * Decrypt "ptr[len]" in place. */ void crypt_decode(ptr, len) char_u *ptr; long len; { char_u *p; if (use_crypt_method == 0) for (p = ptr; p < ptr + len; ++p) { ush temp; temp = (ush)keys[2] | 2; temp = (int)(((unsigned)(temp * (temp ^ 1)) >> 8) & 0xff); UPDATE_KEYS_ZIP(*p ^= temp); } else bf_crypt_decode(ptr, len); } /* * Initialize the encryption keys and the random header according to * the given password. * If "passwd" is NULL or empty, don't do anything. */ void crypt_init_keys(passwd) char_u *passwd; /* password string with which to modify keys */ { if (passwd != NULL && *passwd != NUL) { if (use_crypt_method == 0) { char_u *p; make_crc_tab(); keys[0] = 305419896L; keys[1] = 591751049L; keys[2] = 878082192L; for (p = passwd; *p!= NUL; ++p) { UPDATE_KEYS_ZIP((int)*p); } } else bf_crypt_init_keys(passwd); } } /* * Free an allocated crypt key. Clear the text to make sure it doesn't stay * in memory anywhere. */ void free_crypt_key(key) char_u *key; { char_u *p; if (key != NULL) { for (p = key; *p != NUL; ++p) *p = 0; vim_free(key); } } /* * Ask the user for a crypt key. * When "store" is TRUE, the new key is stored in the 'key' option, and the * 'key' option value is returned: Don't free it. * When "store" is FALSE, the typed key is returned in allocated memory. * Returns NULL on failure. */ char_u * get_crypt_key(store, twice) int store; int twice; /* Ask for the key twice. */ { char_u *p1, *p2 = NULL; int round; for (round = 0; ; ++round) { cmdline_star = TRUE; cmdline_row = msg_row; p1 = getcmdline_prompt(NUL, round == 0 ? (char_u *)_("Enter encryption key: ") : (char_u *)_("Enter same key again: "), 0, EXPAND_NOTHING, NULL); cmdline_star = FALSE; if (p1 == NULL) break; if (round == twice) { if (p2 != NULL && STRCMP(p1, p2) != 0) { MSG(_("Keys don't match!")); free_crypt_key(p1); free_crypt_key(p2); p2 = NULL; round = -1; /* do it again */ continue; } if (store) { set_option_value((char_u *)"key", 0L, p1, OPT_LOCAL); free_crypt_key(p1); p1 = curbuf->b_p_key; } break; } p2 = p1; } /* since the user typed this, no need to wait for return */ if (msg_didout) msg_putchar('\n'); need_wait_return = FALSE; msg_didout = FALSE; free_crypt_key(p2); return p1; } #endif /* FEAT_CRYPT */ /* TODO: make some #ifdef for this */ /*--------[ file searching ]-------------------------------------------------*/ /* * File searching functions for 'path', 'tags' and 'cdpath' options. * External visible functions: * vim_findfile_init() creates/initialises the search context * vim_findfile_free_visited() free list of visited files/dirs of search * context * vim_findfile() find a file in the search context * vim_findfile_cleanup() cleanup/free search context created by * vim_findfile_init() * * All static functions and variables start with 'ff_' * * In general it works like this: * First you create yourself a search context by calling vim_findfile_init(). * It is possible to give a search context from a previous call to * vim_findfile_init(), so it can be reused. After this you call vim_findfile() * until you are satisfied with the result or it returns NULL. On every call it * returns the next file which matches the conditions given to * vim_findfile_init(). If it doesn't find a next file it returns NULL. * * It is possible to call vim_findfile_init() again to reinitialise your search * with some new parameters. Don't forget to pass your old search context to * it, so it can reuse it and especially reuse the list of already visited * directories. If you want to delete the list of already visited directories * simply call vim_findfile_free_visited(). * * When you are done call vim_findfile_cleanup() to free the search context. * * The function vim_findfile_init() has a long comment, which describes the * needed parameters. * * * * ATTENTION: * ========== * Also we use an allocated search context here, this functions are NOT * thread-safe!!!!! * * To minimize parameter passing (or because I'm to lazy), only the * external visible functions get a search context as a parameter. This is * then assigned to a static global, which is used throughout the local * functions. */ /* * type for the directory search stack */ typedef struct ff_stack { struct ff_stack *ffs_prev; /* the fix part (no wildcards) and the part containing the wildcards * of the search path */ char_u *ffs_fix_path; #ifdef FEAT_PATH_EXTRA char_u *ffs_wc_path; #endif /* files/dirs found in the above directory, matched by the first wildcard * of wc_part */ char_u **ffs_filearray; int ffs_filearray_size; char_u ffs_filearray_cur; /* needed for partly handled dirs */ /* to store status of partly handled directories * 0: we work on this directory for the first time * 1: this directory was partly searched in an earlier step */ int ffs_stage; /* How deep are we in the directory tree? * Counts backward from value of level parameter to vim_findfile_init */ int ffs_level; /* Did we already expand '**' to an empty string? */ int ffs_star_star_empty; } ff_stack_T; /* * type for already visited directories or files. */ typedef struct ff_visited { struct ff_visited *ffv_next; #ifdef FEAT_PATH_EXTRA /* Visited directories are different if the wildcard string are * different. So we have to save it. */ char_u *ffv_wc_path; #endif /* for unix use inode etc for comparison (needed because of links), else * use filename. */ #ifdef UNIX int ffv_dev_valid; /* ffv_dev and ffv_ino were set */ dev_t ffv_dev; /* device number */ ino_t ffv_ino; /* inode number */ #endif /* The memory for this struct is allocated according to the length of * ffv_fname. */ char_u ffv_fname[1]; /* actually longer */ } ff_visited_T; /* * We might have to manage several visited lists during a search. * This is especially needed for the tags option. If tags is set to: * "./++/tags,./++/TAGS,++/tags" (replace + with *) * So we have to do 3 searches: * 1) search from the current files directory downward for the file "tags" * 2) search from the current files directory downward for the file "TAGS" * 3) search from Vims current directory downwards for the file "tags" * As you can see, the first and the third search are for the same file, so for * the third search we can use the visited list of the first search. For the * second search we must start from a empty visited list. * The struct ff_visited_list_hdr is used to manage a linked list of already * visited lists. */ typedef struct ff_visited_list_hdr { struct ff_visited_list_hdr *ffvl_next; /* the filename the attached visited list is for */ char_u *ffvl_filename; ff_visited_T *ffvl_visited_list; } ff_visited_list_hdr_T; /* * '**' can be expanded to several directory levels. * Set the default maximum depth. */ #define FF_MAX_STAR_STAR_EXPAND ((char_u)30) /* * The search context: * ffsc_stack_ptr: the stack for the dirs to search * ffsc_visited_list: the currently active visited list * ffsc_dir_visited_list: the currently active visited list for search dirs * ffsc_visited_lists_list: the list of all visited lists * ffsc_dir_visited_lists_list: the list of all visited lists for search dirs * ffsc_file_to_search: the file to search for * ffsc_start_dir: the starting directory, if search path was relative * ffsc_fix_path: the fix part of the given path (without wildcards) * Needed for upward search. * ffsc_wc_path: the part of the given path containing wildcards * ffsc_level: how many levels of dirs to search downwards * ffsc_stopdirs_v: array of stop directories for upward search * ffsc_find_what: FINDFILE_BOTH, FINDFILE_DIR or FINDFILE_FILE * ffsc_tagfile: searching for tags file, don't use 'suffixesadd' */ typedef struct ff_search_ctx_T { ff_stack_T *ffsc_stack_ptr; ff_visited_list_hdr_T *ffsc_visited_list; ff_visited_list_hdr_T *ffsc_dir_visited_list; ff_visited_list_hdr_T *ffsc_visited_lists_list; ff_visited_list_hdr_T *ffsc_dir_visited_lists_list; char_u *ffsc_file_to_search; char_u *ffsc_start_dir; char_u *ffsc_fix_path; #ifdef FEAT_PATH_EXTRA char_u *ffsc_wc_path; int ffsc_level; char_u **ffsc_stopdirs_v; #endif int ffsc_find_what; int ffsc_tagfile; } ff_search_ctx_T; /* locally needed functions */ #ifdef FEAT_PATH_EXTRA static int ff_check_visited __ARGS((ff_visited_T **, char_u *, char_u *)); #else static int ff_check_visited __ARGS((ff_visited_T **, char_u *)); #endif static void vim_findfile_free_visited_list __ARGS((ff_visited_list_hdr_T **list_headp)); static void ff_free_visited_list __ARGS((ff_visited_T *vl)); static ff_visited_list_hdr_T* ff_get_visited_list __ARGS((char_u *, ff_visited_list_hdr_T **list_headp)); #ifdef FEAT_PATH_EXTRA static int ff_wc_equal __ARGS((char_u *s1, char_u *s2)); #endif static void ff_push __ARGS((ff_search_ctx_T *search_ctx, ff_stack_T *stack_ptr)); static ff_stack_T *ff_pop __ARGS((ff_search_ctx_T *search_ctx)); static void ff_clear __ARGS((ff_search_ctx_T *search_ctx)); static void ff_free_stack_element __ARGS((ff_stack_T *stack_ptr)); #ifdef FEAT_PATH_EXTRA static ff_stack_T *ff_create_stack_element __ARGS((char_u *, char_u *, int, int)); #else static ff_stack_T *ff_create_stack_element __ARGS((char_u *, int, int)); #endif #ifdef FEAT_PATH_EXTRA static int ff_path_in_stoplist __ARGS((char_u *, int, char_u **)); #endif static char_u e_pathtoolong[] = N_("E854: path too long for completion"); #if 0 /* * if someone likes findfirst/findnext, here are the functions * NOT TESTED!! */ static void *ff_fn_search_context = NULL; char_u * vim_findfirst(path, filename, level) char_u *path; char_u *filename; int level; { ff_fn_search_context = vim_findfile_init(path, filename, NULL, level, TRUE, FALSE, ff_fn_search_context, rel_fname); if (NULL == ff_fn_search_context) return NULL; else return vim_findnext() } char_u * vim_findnext() { char_u *ret = vim_findfile(ff_fn_search_context); if (NULL == ret) { vim_findfile_cleanup(ff_fn_search_context); ff_fn_search_context = NULL; } return ret; } #endif /* * Initialization routine for vim_findfile(). * * Returns the newly allocated search context or NULL if an error occurred. * * Don't forget to clean up by calling vim_findfile_cleanup() if you are done * with the search context. * * Find the file 'filename' in the directory 'path'. * The parameter 'path' may contain wildcards. If so only search 'level' * directories deep. The parameter 'level' is the absolute maximum and is * not related to restricts given to the '**' wildcard. If 'level' is 100 * and you use '**200' vim_findfile() will stop after 100 levels. * * 'filename' cannot contain wildcards! It is used as-is, no backslashes to * escape special characters. * * If 'stopdirs' is not NULL and nothing is found downward, the search is * restarted on the next higher directory level. This is repeated until the * start-directory of a search is contained in 'stopdirs'. 'stopdirs' has the * format ";*<dirname>*\(;<dirname>\)*;\=$". * * If the 'path' is relative, the starting dir for the search is either VIM's * current dir or if the path starts with "./" the current files dir. * If the 'path' is absolute, the starting dir is that part of the path before * the first wildcard. * * Upward search is only done on the starting dir. * * If 'free_visited' is TRUE the list of already visited files/directories is * cleared. Set this to FALSE if you just want to search from another * directory, but want to be sure that no directory from a previous search is * searched again. This is useful if you search for a file at different places. * The list of visited files/dirs can also be cleared with the function * vim_findfile_free_visited(). * * Set the parameter 'find_what' to FINDFILE_DIR if you want to search for * directories only, FINDFILE_FILE for files only, FINDFILE_BOTH for both. * * A search context returned by a previous call to vim_findfile_init() can be * passed in the parameter "search_ctx_arg". This context is reused and * reinitialized with the new parameters. The list of already visited * directories from this context is only deleted if the parameter * "free_visited" is true. Be aware that the passed "search_ctx_arg" is freed * if the reinitialization fails. * * If you don't have a search context from a previous call "search_ctx_arg" * must be NULL. * * This function silently ignores a few errors, vim_findfile() will have * limited functionality then. */ void * vim_findfile_init(path, filename, stopdirs, level, free_visited, find_what, search_ctx_arg, tagfile, rel_fname) char_u *path; char_u *filename; char_u *stopdirs UNUSED; int level; int free_visited; int find_what; void *search_ctx_arg; int tagfile; /* expanding names of tags files */ char_u *rel_fname; /* file name to use for "." */ { #ifdef FEAT_PATH_EXTRA char_u *wc_part; #endif ff_stack_T *sptr; ff_search_ctx_T *search_ctx; /* If a search context is given by the caller, reuse it, else allocate a * new one. */ if (search_ctx_arg != NULL) search_ctx = search_ctx_arg; else { search_ctx = (ff_search_ctx_T*)alloc((unsigned)sizeof(ff_search_ctx_T)); if (search_ctx == NULL) goto error_return; vim_memset(search_ctx, 0, sizeof(ff_search_ctx_T)); } search_ctx->ffsc_find_what = find_what; search_ctx->ffsc_tagfile = tagfile; /* clear the search context, but NOT the visited lists */ ff_clear(search_ctx); /* clear visited list if wanted */ if (free_visited == TRUE) vim_findfile_free_visited(search_ctx); else { /* Reuse old visited lists. Get the visited list for the given * filename. If no list for the current filename exists, creates a new * one. */ search_ctx->ffsc_visited_list = ff_get_visited_list(filename, &search_ctx->ffsc_visited_lists_list); if (search_ctx->ffsc_visited_list == NULL) goto error_return; search_ctx->ffsc_dir_visited_list = ff_get_visited_list(filename, &search_ctx->ffsc_dir_visited_lists_list); if (search_ctx->ffsc_dir_visited_list == NULL) goto error_return; } if (ff_expand_buffer == NULL) { ff_expand_buffer = (char_u*)alloc(MAXPATHL); if (ff_expand_buffer == NULL) goto error_return; } /* Store information on starting dir now if path is relative. * If path is absolute, we do that later. */ if (path[0] == '.' && (vim_ispathsep(path[1]) || path[1] == NUL) && (!tagfile || vim_strchr(p_cpo, CPO_DOTTAG) == NULL) && rel_fname != NULL) { int len = (int)(gettail(rel_fname) - rel_fname); if (!vim_isAbsName(rel_fname) && len + 1 < MAXPATHL) { /* Make the start dir an absolute path name. */ vim_strncpy(ff_expand_buffer, rel_fname, len); search_ctx->ffsc_start_dir = FullName_save(ff_expand_buffer, FALSE); } else search_ctx->ffsc_start_dir = vim_strnsave(rel_fname, len); if (search_ctx->ffsc_start_dir == NULL) goto error_return; if (*++path != NUL) ++path; } else if (*path == NUL || !vim_isAbsName(path)) { #ifdef BACKSLASH_IN_FILENAME /* "c:dir" needs "c:" to be expanded, otherwise use current dir */ if (*path != NUL && path[1] == ':') { char_u drive[3]; drive[0] = path[0]; drive[1] = ':'; drive[2] = NUL; if (vim_FullName(drive, ff_expand_buffer, MAXPATHL, TRUE) == FAIL) goto error_return; path += 2; } else #endif if (mch_dirname(ff_expand_buffer, MAXPATHL) == FAIL) goto error_return; search_ctx->ffsc_start_dir = vim_strsave(ff_expand_buffer); if (search_ctx->ffsc_start_dir == NULL) goto error_return; #ifdef BACKSLASH_IN_FILENAME /* A path that starts with "/dir" is relative to the drive, not to the * directory (but not for "//machine/dir"). Only use the drive name. */ if ((*path == '/' || *path == '\\') && path[1] != path[0] && search_ctx->ffsc_start_dir[1] == ':') search_ctx->ffsc_start_dir[2] = NUL; #endif } #ifdef FEAT_PATH_EXTRA /* * If stopdirs are given, split them into an array of pointers. * If this fails (mem allocation), there is no upward search at all or a * stop directory is not recognized -> continue silently. * If stopdirs just contains a ";" or is empty, * search_ctx->ffsc_stopdirs_v will only contain a NULL pointer. This * is handled as unlimited upward search. See function * ff_path_in_stoplist() for details. */ if (stopdirs != NULL) { char_u *walker = stopdirs; int dircount; while (*walker == ';') walker++; dircount = 1; search_ctx->ffsc_stopdirs_v = (char_u **)alloc((unsigned)sizeof(char_u *)); if (search_ctx->ffsc_stopdirs_v != NULL) { do { char_u *helper; void *ptr; helper = walker; ptr = vim_realloc(search_ctx->ffsc_stopdirs_v, (dircount + 1) * sizeof(char_u *)); if (ptr) search_ctx->ffsc_stopdirs_v = ptr; else /* ignore, keep what we have and continue */ break; walker = vim_strchr(walker, ';'); if (walker) { search_ctx->ffsc_stopdirs_v[dircount-1] = vim_strnsave(helper, (int)(walker - helper)); walker++; } else /* this might be "", which means ascent till top * of directory tree. */ search_ctx->ffsc_stopdirs_v[dircount-1] = vim_strsave(helper); dircount++; } while (walker != NULL); search_ctx->ffsc_stopdirs_v[dircount-1] = NULL; } } #endif #ifdef FEAT_PATH_EXTRA search_ctx->ffsc_level = level; /* split into: * -fix path * -wildcard_stuff (might be NULL) */ wc_part = vim_strchr(path, '*'); if (wc_part != NULL) { int llevel; int len; char *errpt; /* save the fix part of the path */ search_ctx->ffsc_fix_path = vim_strnsave(path, (int)(wc_part - path)); /* * copy wc_path and add restricts to the '**' wildcard. * The octet after a '**' is used as a (binary) counter. * So '**3' is transposed to '**^C' ('^C' is ASCII value 3) * or '**76' is transposed to '**N'( 'N' is ASCII value 76). * For EBCDIC you get different character values. * If no restrict is given after '**' the default is used. * Due to this technique the path looks awful if you print it as a * string. */ len = 0; while (*wc_part != NUL) { if (len + 5 >= MAXPATHL) { EMSG(_(e_pathtoolong)); break; } if (STRNCMP(wc_part, "**", 2) == 0) { ff_expand_buffer[len++] = *wc_part++; ff_expand_buffer[len++] = *wc_part++; llevel = strtol((char *)wc_part, &errpt, 10); if ((char_u *)errpt != wc_part && llevel > 0 && llevel < 255) ff_expand_buffer[len++] = llevel; else if ((char_u *)errpt != wc_part && llevel == 0) /* restrict is 0 -> remove already added '**' */ len -= 2; else ff_expand_buffer[len++] = FF_MAX_STAR_STAR_EXPAND; wc_part = (char_u *)errpt; if (*wc_part != NUL && !vim_ispathsep(*wc_part)) { EMSG2(_("E343: Invalid path: '**[number]' must be at the end of the path or be followed by '%s'."), PATHSEPSTR); goto error_return; } } else ff_expand_buffer[len++] = *wc_part++; } ff_expand_buffer[len] = NUL; search_ctx->ffsc_wc_path = vim_strsave(ff_expand_buffer); if (search_ctx->ffsc_wc_path == NULL) goto error_return; } else #endif search_ctx->ffsc_fix_path = vim_strsave(path); if (search_ctx->ffsc_start_dir == NULL) { /* store the fix part as startdir. * This is needed if the parameter path is fully qualified. */ search_ctx->ffsc_start_dir = vim_strsave(search_ctx->ffsc_fix_path); if (search_ctx->ffsc_start_dir == NULL) goto error_return; search_ctx->ffsc_fix_path[0] = NUL; } /* create an absolute path */ if (STRLEN(search_ctx->ffsc_start_dir) + STRLEN(search_ctx->ffsc_fix_path) + 3 >= MAXPATHL) { EMSG(_(e_pathtoolong)); goto error_return; } STRCPY(ff_expand_buffer, search_ctx->ffsc_start_dir); add_pathsep(ff_expand_buffer); STRCAT(ff_expand_buffer, search_ctx->ffsc_fix_path); add_pathsep(ff_expand_buffer); sptr = ff_create_stack_element(ff_expand_buffer, #ifdef FEAT_PATH_EXTRA search_ctx->ffsc_wc_path, #endif level, 0); if (sptr == NULL) goto error_return; ff_push(search_ctx, sptr); search_ctx->ffsc_file_to_search = vim_strsave(filename); if (search_ctx->ffsc_file_to_search == NULL) goto error_return; return search_ctx; error_return: /* * We clear the search context now! * Even when the caller gave us a (perhaps valid) context we free it here, * as we might have already destroyed it. */ vim_findfile_cleanup(search_ctx); return NULL; } #if defined(FEAT_PATH_EXTRA) || defined(PROTO) /* * Get the stopdir string. Check that ';' is not escaped. */ char_u * vim_findfile_stopdir(buf) char_u *buf; { char_u *r_ptr = buf; while (*r_ptr != NUL && *r_ptr != ';') { if (r_ptr[0] == '\\' && r_ptr[1] == ';') { /* Overwrite the escape char, * use STRLEN(r_ptr) to move the trailing '\0'. */ STRMOVE(r_ptr, r_ptr + 1); r_ptr++; } r_ptr++; } if (*r_ptr == ';') { *r_ptr = 0; r_ptr++; } else if (*r_ptr == NUL) r_ptr = NULL; return r_ptr; } #endif /* * Clean up the given search context. Can handle a NULL pointer. */ void vim_findfile_cleanup(ctx) void *ctx; { if (ctx == NULL) return; vim_findfile_free_visited(ctx); ff_clear(ctx); vim_free(ctx); } /* * Find a file in a search context. * The search context was created with vim_findfile_init() above. * Return a pointer to an allocated file name or NULL if nothing found. * To get all matching files call this function until you get NULL. * * If the passed search_context is NULL, NULL is returned. * * The search algorithm is depth first. To change this replace the * stack with a list (don't forget to leave partly searched directories on the * top of the list). */ char_u * vim_findfile(search_ctx_arg) void *search_ctx_arg; { char_u *file_path; #ifdef FEAT_PATH_EXTRA char_u *rest_of_wildcards; char_u *path_end = NULL; #endif ff_stack_T *stackp; #if defined(FEAT_SEARCHPATH) || defined(FEAT_PATH_EXTRA) int len; #endif int i; char_u *p; #ifdef FEAT_SEARCHPATH char_u *suf; #endif ff_search_ctx_T *search_ctx; if (search_ctx_arg == NULL) return NULL; search_ctx = (ff_search_ctx_T *)search_ctx_arg; /* * filepath is used as buffer for various actions and as the storage to * return a found filename. */ if ((file_path = alloc((int)MAXPATHL)) == NULL) return NULL; #ifdef FEAT_PATH_EXTRA /* store the end of the start dir -- needed for upward search */ if (search_ctx->ffsc_start_dir != NULL) path_end = &search_ctx->ffsc_start_dir[ STRLEN(search_ctx->ffsc_start_dir)]; #endif #ifdef FEAT_PATH_EXTRA /* upward search loop */ for (;;) { #endif /* downward search loop */ for (;;) { /* check if user user wants to stop the search*/ ui_breakcheck(); if (got_int) break; /* get directory to work on from stack */ stackp = ff_pop(search_ctx); if (stackp == NULL) break; /* * TODO: decide if we leave this test in * * GOOD: don't search a directory(-tree) twice. * BAD: - check linked list for every new directory entered. * - check for double files also done below * * Here we check if we already searched this directory. * We already searched a directory if: * 1) The directory is the same. * 2) We would use the same wildcard string. * * Good if you have links on same directory via several ways * or you have selfreferences in directories (e.g. SuSE Linux 6.3: * /etc/rc.d/init.d is linked to /etc/rc.d -> endless loop) * * This check is only needed for directories we work on for the * first time (hence stackp->ff_filearray == NULL) */ if (stackp->ffs_filearray == NULL && ff_check_visited(&search_ctx->ffsc_dir_visited_list ->ffvl_visited_list, stackp->ffs_fix_path #ifdef FEAT_PATH_EXTRA , stackp->ffs_wc_path #endif ) == FAIL) { #ifdef FF_VERBOSE if (p_verbose >= 5) { verbose_enter_scroll(); smsg((char_u *)"Already Searched: %s (%s)", stackp->ffs_fix_path, stackp->ffs_wc_path); /* don't overwrite this either */ msg_puts((char_u *)"\n"); verbose_leave_scroll(); } #endif ff_free_stack_element(stackp); continue; } #ifdef FF_VERBOSE else if (p_verbose >= 5) { verbose_enter_scroll(); smsg((char_u *)"Searching: %s (%s)", stackp->ffs_fix_path, stackp->ffs_wc_path); /* don't overwrite this either */ msg_puts((char_u *)"\n"); verbose_leave_scroll(); } #endif /* check depth */ if (stackp->ffs_level <= 0) { ff_free_stack_element(stackp); continue; } file_path[0] = NUL; /* * If no filearray till now expand wildcards * The function expand_wildcards() can handle an array of paths * and all possible expands are returned in one array. We use this * to handle the expansion of '**' into an empty string. */ if (stackp->ffs_filearray == NULL) { char_u *dirptrs[2]; /* we use filepath to build the path expand_wildcards() should * expand. */ dirptrs[0] = file_path; dirptrs[1] = NULL; /* if we have a start dir copy it in */ if (!vim_isAbsName(stackp->ffs_fix_path) && search_ctx->ffsc_start_dir) { STRCPY(file_path, search_ctx->ffsc_start_dir); add_pathsep(file_path); } /* append the fix part of the search path */ STRCAT(file_path, stackp->ffs_fix_path); add_pathsep(file_path); #ifdef FEAT_PATH_EXTRA rest_of_wildcards = stackp->ffs_wc_path; if (*rest_of_wildcards != NUL) { len = (int)STRLEN(file_path); if (STRNCMP(rest_of_wildcards, "**", 2) == 0) { /* pointer to the restrict byte * The restrict byte is not a character! */ p = rest_of_wildcards + 2; if (*p > 0) { (*p)--; file_path[len++] = '*'; } if (*p == 0) { /* remove '**<numb> from wildcards */ STRMOVE(rest_of_wildcards, rest_of_wildcards + 3); } else rest_of_wildcards += 3; if (stackp->ffs_star_star_empty == 0) { /* if not done before, expand '**' to empty */ stackp->ffs_star_star_empty = 1; dirptrs[1] = stackp->ffs_fix_path; } } /* * Here we copy until the next path separator or the end of * the path. If we stop at a path separator, there is * still something else left. This is handled below by * pushing every directory returned from expand_wildcards() * on the stack again for further search. */ while (*rest_of_wildcards && !vim_ispathsep(*rest_of_wildcards)) file_path[len++] = *rest_of_wildcards++; file_path[len] = NUL; if (vim_ispathsep(*rest_of_wildcards)) rest_of_wildcards++; } #endif /* * Expand wildcards like "*" and "$VAR". * If the path is a URL don't try this. */ if (path_with_url(dirptrs[0])) { stackp->ffs_filearray = (char_u **) alloc((unsigned)sizeof(char *)); if (stackp->ffs_filearray != NULL && (stackp->ffs_filearray[0] = vim_strsave(dirptrs[0])) != NULL) stackp->ffs_filearray_size = 1; else stackp->ffs_filearray_size = 0; } else /* Add EW_NOTWILD because the expanded path may contain * wildcard characters that are to be taken literally. * This is a bit of a hack. */ expand_wildcards((dirptrs[1] == NULL) ? 1 : 2, dirptrs, &stackp->ffs_filearray_size, &stackp->ffs_filearray, EW_DIR|EW_ADDSLASH|EW_SILENT|EW_NOTWILD); stackp->ffs_filearray_cur = 0; stackp->ffs_stage = 0; } #ifdef FEAT_PATH_EXTRA else rest_of_wildcards = &stackp->ffs_wc_path[ STRLEN(stackp->ffs_wc_path)]; #endif if (stackp->ffs_stage == 0) { /* this is the first time we work on this directory */ #ifdef FEAT_PATH_EXTRA if (*rest_of_wildcards == NUL) #endif { /* * we don't have further wildcards to expand, so we have to * check for the final file now */ for (i = stackp->ffs_filearray_cur; i < stackp->ffs_filearray_size; ++i) { if (!path_with_url(stackp->ffs_filearray[i]) && !mch_isdir(stackp->ffs_filearray[i])) continue; /* not a directory */ /* prepare the filename to be checked for existence * below */ STRCPY(file_path, stackp->ffs_filearray[i]); add_pathsep(file_path); STRCAT(file_path, search_ctx->ffsc_file_to_search); /* * Try without extra suffix and then with suffixes * from 'suffixesadd'. */ #ifdef FEAT_SEARCHPATH len = (int)STRLEN(file_path); if (search_ctx->ffsc_tagfile) suf = (char_u *)""; else suf = curbuf->b_p_sua; for (;;) #endif { /* if file exists and we didn't already find it */ if ((path_with_url(file_path) || (mch_getperm(file_path) >= 0 && (search_ctx->ffsc_find_what == FINDFILE_BOTH || ((search_ctx->ffsc_find_what == FINDFILE_DIR) == mch_isdir(file_path))))) #ifndef FF_VERBOSE && (ff_check_visited( &search_ctx->ffsc_visited_list->ffvl_visited_list, file_path #ifdef FEAT_PATH_EXTRA , (char_u *)"" #endif ) == OK) #endif ) { #ifdef FF_VERBOSE if (ff_check_visited( &search_ctx->ffsc_visited_list->ffvl_visited_list, file_path #ifdef FEAT_PATH_EXTRA , (char_u *)"" #endif ) == FAIL) { if (p_verbose >= 5) { verbose_enter_scroll(); smsg((char_u *)"Already: %s", file_path); /* don't overwrite this either */ msg_puts((char_u *)"\n"); verbose_leave_scroll(); } continue; } #endif /* push dir to examine rest of subdirs later */ stackp->ffs_filearray_cur = i + 1; ff_push(search_ctx, stackp); if (!path_with_url(file_path)) simplify_filename(file_path); if (mch_dirname(ff_expand_buffer, MAXPATHL) == OK) { p = shorten_fname(file_path, ff_expand_buffer); if (p != NULL) STRMOVE(file_path, p); } #ifdef FF_VERBOSE if (p_verbose >= 5) { verbose_enter_scroll(); smsg((char_u *)"HIT: %s", file_path); /* don't overwrite this either */ msg_puts((char_u *)"\n"); verbose_leave_scroll(); } #endif return file_path; } #ifdef FEAT_SEARCHPATH /* Not found or found already, try next suffix. */ if (*suf == NUL) break; copy_option_part(&suf, file_path + len, MAXPATHL - len, ","); #endif } } } #ifdef FEAT_PATH_EXTRA else { /* * still wildcards left, push the directories for further * search */ for (i = stackp->ffs_filearray_cur; i < stackp->ffs_filearray_size; ++i) { if (!mch_isdir(stackp->ffs_filearray[i])) continue; /* not a directory */ ff_push(search_ctx, ff_create_stack_element( stackp->ffs_filearray[i], rest_of_wildcards, stackp->ffs_level - 1, 0)); } } #endif stackp->ffs_filearray_cur = 0; stackp->ffs_stage = 1; } #ifdef FEAT_PATH_EXTRA /* * if wildcards contains '**' we have to descent till we reach the * leaves of the directory tree. */ if (STRNCMP(stackp->ffs_wc_path, "**", 2) == 0) { for (i = stackp->ffs_filearray_cur; i < stackp->ffs_filearray_size; ++i) { if (fnamecmp(stackp->ffs_filearray[i], stackp->ffs_fix_path) == 0) continue; /* don't repush same directory */ if (!mch_isdir(stackp->ffs_filearray[i])) continue; /* not a directory */ ff_push(search_ctx, ff_create_stack_element(stackp->ffs_filearray[i], stackp->ffs_wc_path, stackp->ffs_level - 1, 1)); } } #endif /* we are done with the current directory */ ff_free_stack_element(stackp); } #ifdef FEAT_PATH_EXTRA /* If we reached this, we didn't find anything downwards. * Let's check if we should do an upward search. */ if (search_ctx->ffsc_start_dir && search_ctx->ffsc_stopdirs_v != NULL && !got_int) { ff_stack_T *sptr; /* is the last starting directory in the stop list? */ if (ff_path_in_stoplist(search_ctx->ffsc_start_dir, (int)(path_end - search_ctx->ffsc_start_dir), search_ctx->ffsc_stopdirs_v) == TRUE) break; /* cut of last dir */ while (path_end > search_ctx->ffsc_start_dir && vim_ispathsep(*path_end)) path_end--; while (path_end > search_ctx->ffsc_start_dir && !vim_ispathsep(path_end[-1])) path_end--; *path_end = 0; path_end--; if (*search_ctx->ffsc_start_dir == 0) break; STRCPY(file_path, search_ctx->ffsc_start_dir); add_pathsep(file_path); STRCAT(file_path, search_ctx->ffsc_fix_path); /* create a new stack entry */ sptr = ff_create_stack_element(file_path, search_ctx->ffsc_wc_path, search_ctx->ffsc_level, 0); if (sptr == NULL) break; ff_push(search_ctx, sptr); } else break; } #endif vim_free(file_path); return NULL; } /* * Free the list of lists of visited files and directories * Can handle it if the passed search_context is NULL; */ void vim_findfile_free_visited(search_ctx_arg) void *search_ctx_arg; { ff_search_ctx_T *search_ctx; if (search_ctx_arg == NULL) return; search_ctx = (ff_search_ctx_T *)search_ctx_arg; vim_findfile_free_visited_list(&search_ctx->ffsc_visited_lists_list); vim_findfile_free_visited_list(&search_ctx->ffsc_dir_visited_lists_list); } static void vim_findfile_free_visited_list(list_headp) ff_visited_list_hdr_T **list_headp; { ff_visited_list_hdr_T *vp; while (*list_headp != NULL) { vp = (*list_headp)->ffvl_next; ff_free_visited_list((*list_headp)->ffvl_visited_list); vim_free((*list_headp)->ffvl_filename); vim_free(*list_headp); *list_headp = vp; } *list_headp = NULL; } static void ff_free_visited_list(vl) ff_visited_T *vl; { ff_visited_T *vp; while (vl != NULL) { vp = vl->ffv_next; #ifdef FEAT_PATH_EXTRA vim_free(vl->ffv_wc_path); #endif vim_free(vl); vl = vp; } vl = NULL; } /* * Returns the already visited list for the given filename. If none is found it * allocates a new one. */ static ff_visited_list_hdr_T* ff_get_visited_list(filename, list_headp) char_u *filename; ff_visited_list_hdr_T **list_headp; { ff_visited_list_hdr_T *retptr = NULL; /* check if a visited list for the given filename exists */ if (*list_headp != NULL) { retptr = *list_headp; while (retptr != NULL) { if (fnamecmp(filename, retptr->ffvl_filename) == 0) { #ifdef FF_VERBOSE if (p_verbose >= 5) { verbose_enter_scroll(); smsg((char_u *)"ff_get_visited_list: FOUND list for %s", filename); /* don't overwrite this either */ msg_puts((char_u *)"\n"); verbose_leave_scroll(); } #endif return retptr; } retptr = retptr->ffvl_next; } } #ifdef FF_VERBOSE if (p_verbose >= 5) { verbose_enter_scroll(); smsg((char_u *)"ff_get_visited_list: new list for %s", filename); /* don't overwrite this either */ msg_puts((char_u *)"\n"); verbose_leave_scroll(); } #endif /* * if we reach this we didn't find a list and we have to allocate new list */ retptr = (ff_visited_list_hdr_T*)alloc((unsigned)sizeof(*retptr)); if (retptr == NULL) return NULL; retptr->ffvl_visited_list = NULL; retptr->ffvl_filename = vim_strsave(filename); if (retptr->ffvl_filename == NULL) { vim_free(retptr); return NULL; } retptr->ffvl_next = *list_headp; *list_headp = retptr; return retptr; } #ifdef FEAT_PATH_EXTRA /* * check if two wildcard paths are equal. Returns TRUE or FALSE. * They are equal if: * - both paths are NULL * - they have the same length * - char by char comparison is OK * - the only differences are in the counters behind a '**', so * '**\20' is equal to '**\24' */ static int ff_wc_equal(s1, s2) char_u *s1; char_u *s2; { int i; if (s1 == s2) return TRUE; if (s1 == NULL || s2 == NULL) return FALSE; if (STRLEN(s1) != STRLEN(s2)) return FAIL; for (i = 0; s1[i] != NUL && s2[i] != NUL; i++) { if (s1[i] != s2[i] #ifdef CASE_INSENSITIVE_FILENAME && TOUPPER_LOC(s1[i]) != TOUPPER_LOC(s2[i]) #endif ) { if (i >= 2) if (s1[i-1] == '*' && s1[i-2] == '*') continue; else return FAIL; else return FAIL; } } return TRUE; } #endif /* * maintains the list of already visited files and dirs * returns FAIL if the given file/dir is already in the list * returns OK if it is newly added * * TODO: What to do on memory allocation problems? * -> return TRUE - Better the file is found several times instead of * never. */ static int ff_check_visited(visited_list, fname #ifdef FEAT_PATH_EXTRA , wc_path #endif ) ff_visited_T **visited_list; char_u *fname; #ifdef FEAT_PATH_EXTRA char_u *wc_path; #endif { ff_visited_T *vp; #ifdef UNIX struct stat st; int url = FALSE; #endif /* For an URL we only compare the name, otherwise we compare the * device/inode (unix) or the full path name (not Unix). */ if (path_with_url(fname)) { vim_strncpy(ff_expand_buffer, fname, MAXPATHL - 1); #ifdef UNIX url = TRUE; #endif } else { ff_expand_buffer[0] = NUL; #ifdef UNIX if (mch_stat((char *)fname, &st) < 0) #else if (vim_FullName(fname, ff_expand_buffer, MAXPATHL, TRUE) == FAIL) #endif return FAIL; } /* check against list of already visited files */ for (vp = *visited_list; vp != NULL; vp = vp->ffv_next) { if ( #ifdef UNIX !url ? (vp->ffv_dev_valid && vp->ffv_dev == st.st_dev && vp->ffv_ino == st.st_ino) : #endif fnamecmp(vp->ffv_fname, ff_expand_buffer) == 0 ) { #ifdef FEAT_PATH_EXTRA /* are the wildcard parts equal */ if (ff_wc_equal(vp->ffv_wc_path, wc_path) == TRUE) #endif /* already visited */ return FAIL; } } /* * New file/dir. Add it to the list of visited files/dirs. */ vp = (ff_visited_T *)alloc((unsigned)(sizeof(ff_visited_T) + STRLEN(ff_expand_buffer))); if (vp != NULL) { #ifdef UNIX if (!url) { vp->ffv_dev_valid = TRUE; vp->ffv_ino = st.st_ino; vp->ffv_dev = st.st_dev; vp->ffv_fname[0] = NUL; } else { vp->ffv_dev_valid = FALSE; #endif STRCPY(vp->ffv_fname, ff_expand_buffer); #ifdef UNIX } #endif #ifdef FEAT_PATH_EXTRA if (wc_path != NULL) vp->ffv_wc_path = vim_strsave(wc_path); else vp->ffv_wc_path = NULL; #endif vp->ffv_next = *visited_list; *visited_list = vp; } return OK; } /* * create stack element from given path pieces */ static ff_stack_T * ff_create_stack_element(fix_part, #ifdef FEAT_PATH_EXTRA wc_part, #endif level, star_star_empty) char_u *fix_part; #ifdef FEAT_PATH_EXTRA char_u *wc_part; #endif int level; int star_star_empty; { ff_stack_T *new; new = (ff_stack_T *)alloc((unsigned)sizeof(ff_stack_T)); if (new == NULL) return NULL; new->ffs_prev = NULL; new->ffs_filearray = NULL; new->ffs_filearray_size = 0; new->ffs_filearray_cur = 0; new->ffs_stage = 0; new->ffs_level = level; new->ffs_star_star_empty = star_star_empty;; /* the following saves NULL pointer checks in vim_findfile */ if (fix_part == NULL) fix_part = (char_u *)""; new->ffs_fix_path = vim_strsave(fix_part); #ifdef FEAT_PATH_EXTRA if (wc_part == NULL) wc_part = (char_u *)""; new->ffs_wc_path = vim_strsave(wc_part); #endif if (new->ffs_fix_path == NULL #ifdef FEAT_PATH_EXTRA || new->ffs_wc_path == NULL #endif ) { ff_free_stack_element(new); new = NULL; } return new; } /* * Push a dir on the directory stack. */ static void ff_push(search_ctx, stack_ptr) ff_search_ctx_T *search_ctx; ff_stack_T *stack_ptr; { /* check for NULL pointer, not to return an error to the user, but * to prevent a crash */ if (stack_ptr != NULL) { stack_ptr->ffs_prev = search_ctx->ffsc_stack_ptr; search_ctx->ffsc_stack_ptr = stack_ptr; } } /* * Pop a dir from the directory stack. * Returns NULL if stack is empty. */ static ff_stack_T * ff_pop(search_ctx) ff_search_ctx_T *search_ctx; { ff_stack_T *sptr; sptr = search_ctx->ffsc_stack_ptr; if (search_ctx->ffsc_stack_ptr != NULL) search_ctx->ffsc_stack_ptr = search_ctx->ffsc_stack_ptr->ffs_prev; return sptr; } /* * free the given stack element */ static void ff_free_stack_element(stack_ptr) ff_stack_T *stack_ptr; { /* vim_free handles possible NULL pointers */ vim_free(stack_ptr->ffs_fix_path); #ifdef FEAT_PATH_EXTRA vim_free(stack_ptr->ffs_wc_path); #endif if (stack_ptr->ffs_filearray != NULL) FreeWild(stack_ptr->ffs_filearray_size, stack_ptr->ffs_filearray); vim_free(stack_ptr); } /* * Clear the search context, but NOT the visited list. */ static void ff_clear(search_ctx) ff_search_ctx_T *search_ctx; { ff_stack_T *sptr; /* clear up stack */ while ((sptr = ff_pop(search_ctx)) != NULL) ff_free_stack_element(sptr); vim_free(search_ctx->ffsc_file_to_search); vim_free(search_ctx->ffsc_start_dir); vim_free(search_ctx->ffsc_fix_path); #ifdef FEAT_PATH_EXTRA vim_free(search_ctx->ffsc_wc_path); #endif #ifdef FEAT_PATH_EXTRA if (search_ctx->ffsc_stopdirs_v != NULL) { int i = 0; while (search_ctx->ffsc_stopdirs_v[i] != NULL) { vim_free(search_ctx->ffsc_stopdirs_v[i]); i++; } vim_free(search_ctx->ffsc_stopdirs_v); } search_ctx->ffsc_stopdirs_v = NULL; #endif /* reset everything */ search_ctx->ffsc_file_to_search = NULL; search_ctx->ffsc_start_dir = NULL; search_ctx->ffsc_fix_path = NULL; #ifdef FEAT_PATH_EXTRA search_ctx->ffsc_wc_path = NULL; search_ctx->ffsc_level = 0; #endif } #ifdef FEAT_PATH_EXTRA /* * check if the given path is in the stopdirs * returns TRUE if yes else FALSE */ static int ff_path_in_stoplist(path, path_len, stopdirs_v) char_u *path; int path_len; char_u **stopdirs_v; { int i = 0; /* eat up trailing path separators, except the first */ while (path_len > 1 && vim_ispathsep(path[path_len - 1])) path_len--; /* if no path consider it as match */ if (path_len == 0) return TRUE; for (i = 0; stopdirs_v[i] != NULL; i++) { if ((int)STRLEN(stopdirs_v[i]) > path_len) { /* match for parent directory. So '/home' also matches * '/home/rks'. Check for PATHSEP in stopdirs_v[i], else * '/home/r' would also match '/home/rks' */ if (fnamencmp(stopdirs_v[i], path, path_len) == 0 && vim_ispathsep(stopdirs_v[i][path_len])) return TRUE; } else { if (fnamecmp(stopdirs_v[i], path) == 0) return TRUE; } } return FALSE; } #endif #if defined(FEAT_SEARCHPATH) || defined(PROTO) /* * Find the file name "ptr[len]" in the path. Also finds directory names. * * On the first call set the parameter 'first' to TRUE to initialize * the search. For repeating calls to FALSE. * * Repeating calls will return other files called 'ptr[len]' from the path. * * Only on the first call 'ptr' and 'len' are used. For repeating calls they * don't need valid values. * * If nothing found on the first call the option FNAME_MESS will issue the * message: * 'Can't find file "<file>" in path' * On repeating calls: * 'No more file "<file>" found in path' * * options: * FNAME_MESS give error message when not found * * Uses NameBuff[]! * * Returns an allocated string for the file name. NULL for error. * */ char_u * find_file_in_path(ptr, len, options, first, rel_fname) char_u *ptr; /* file name */ int len; /* length of file name */ int options; int first; /* use count'th matching file name */ char_u *rel_fname; /* file name searching relative to */ { return find_file_in_path_option(ptr, len, options, first, *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path, FINDFILE_BOTH, rel_fname, curbuf->b_p_sua); } static char_u *ff_file_to_find = NULL; static void *fdip_search_ctx = NULL; #if defined(EXITFREE) static void free_findfile() { vim_free(ff_file_to_find); vim_findfile_cleanup(fdip_search_ctx); } #endif /* * Find the directory name "ptr[len]" in the path. * * options: * FNAME_MESS give error message when not found * * Uses NameBuff[]! * * Returns an allocated string for the file name. NULL for error. */ char_u * find_directory_in_path(ptr, len, options, rel_fname) char_u *ptr; /* file name */ int len; /* length of file name */ int options; char_u *rel_fname; /* file name searching relative to */ { return find_file_in_path_option(ptr, len, options, TRUE, p_cdpath, FINDFILE_DIR, rel_fname, (char_u *)""); } char_u * find_file_in_path_option(ptr, len, options, first, path_option, find_what, rel_fname, suffixes) char_u *ptr; /* file name */ int len; /* length of file name */ int options; int first; /* use count'th matching file name */ char_u *path_option; /* p_path or p_cdpath */ int find_what; /* FINDFILE_FILE, _DIR or _BOTH */ char_u *rel_fname; /* file name we are looking relative to. */ char_u *suffixes; /* list of suffixes, 'suffixesadd' option */ { static char_u *dir; static int did_findfile_init = FALSE; char_u save_char; char_u *file_name = NULL; char_u *buf = NULL; int rel_to_curdir; #ifdef AMIGA struct Process *proc = (struct Process *)FindTask(0L); APTR save_winptr = proc->pr_WindowPtr; /* Avoid a requester here for a volume that doesn't exist. */ proc->pr_WindowPtr = (APTR)-1L; #endif if (first == TRUE) { /* copy file name into NameBuff, expanding environment variables */ save_char = ptr[len]; ptr[len] = NUL; expand_env(ptr, NameBuff, MAXPATHL); ptr[len] = save_char; vim_free(ff_file_to_find); ff_file_to_find = vim_strsave(NameBuff); if (ff_file_to_find == NULL) /* out of memory */ { file_name = NULL; goto theend; } } rel_to_curdir = (ff_file_to_find[0] == '.' && (ff_file_to_find[1] == NUL || vim_ispathsep(ff_file_to_find[1]) || (ff_file_to_find[1] == '.' && (ff_file_to_find[2] == NUL || vim_ispathsep(ff_file_to_find[2]))))); if (vim_isAbsName(ff_file_to_find) /* "..", "../path", "." and "./path": don't use the path_option */ || rel_to_curdir #if defined(MSWIN) || defined(MSDOS) || defined(OS2) /* handle "\tmp" as absolute path */ || vim_ispathsep(ff_file_to_find[0]) /* handle "c:name" as absolute path */ || (ff_file_to_find[0] != NUL && ff_file_to_find[1] == ':') #endif #ifdef AMIGA /* handle ":tmp" as absolute path */ || ff_file_to_find[0] == ':' #endif ) { /* * Absolute path, no need to use "path_option". * If this is not a first call, return NULL. We already returned a * filename on the first call. */ if (first == TRUE) { int l; int run; if (path_with_url(ff_file_to_find)) { file_name = vim_strsave(ff_file_to_find); goto theend; } /* When FNAME_REL flag given first use the directory of the file. * Otherwise or when this fails use the current directory. */ for (run = 1; run <= 2; ++run) { l = (int)STRLEN(ff_file_to_find); if (run == 1 && rel_to_curdir && (options & FNAME_REL) && rel_fname != NULL && STRLEN(rel_fname) + l < MAXPATHL) { STRCPY(NameBuff, rel_fname); STRCPY(gettail(NameBuff), ff_file_to_find); l = (int)STRLEN(NameBuff); } else { STRCPY(NameBuff, ff_file_to_find); run = 2; } /* When the file doesn't exist, try adding parts of * 'suffixesadd'. */ buf = suffixes; for (;;) { if ( #ifdef DJGPP /* "C:" by itself will fail for mch_getperm(), * assume it's always valid. */ (find_what != FINDFILE_FILE && NameBuff[0] != NUL && NameBuff[1] == ':' && NameBuff[2] == NUL) || #endif (mch_getperm(NameBuff) >= 0 && (find_what == FINDFILE_BOTH || ((find_what == FINDFILE_DIR) == mch_isdir(NameBuff))))) { file_name = vim_strsave(NameBuff); goto theend; } if (*buf == NUL) break; copy_option_part(&buf, NameBuff + l, MAXPATHL - l, ","); } } } } else { /* * Loop over all paths in the 'path' or 'cdpath' option. * When "first" is set, first setup to the start of the option. * Otherwise continue to find the next match. */ if (first == TRUE) { /* vim_findfile_free_visited can handle a possible NULL pointer */ vim_findfile_free_visited(fdip_search_ctx); dir = path_option; did_findfile_init = FALSE; } for (;;) { if (did_findfile_init) { file_name = vim_findfile(fdip_search_ctx); if (file_name != NULL) break; did_findfile_init = FALSE; } else { char_u *r_ptr; if (dir == NULL || *dir == NUL) { /* We searched all paths of the option, now we can * free the search context. */ vim_findfile_cleanup(fdip_search_ctx); fdip_search_ctx = NULL; break; } if ((buf = alloc((int)(MAXPATHL))) == NULL) break; /* copy next path */ buf[0] = 0; copy_option_part(&dir, buf, MAXPATHL, " ,"); #ifdef FEAT_PATH_EXTRA /* get the stopdir string */ r_ptr = vim_findfile_stopdir(buf); #else r_ptr = NULL; #endif fdip_search_ctx = vim_findfile_init(buf, ff_file_to_find, r_ptr, 100, FALSE, find_what, fdip_search_ctx, FALSE, rel_fname); if (fdip_search_ctx != NULL) did_findfile_init = TRUE; vim_free(buf); } } } if (file_name == NULL && (options & FNAME_MESS)) { if (first == TRUE) { if (find_what == FINDFILE_DIR) EMSG2(_("E344: Can't find directory \"%s\" in cdpath"), ff_file_to_find); else EMSG2(_("E345: Can't find file \"%s\" in path"), ff_file_to_find); } else { if (find_what == FINDFILE_DIR) EMSG2(_("E346: No more directory \"%s\" found in cdpath"), ff_file_to_find); else EMSG2(_("E347: No more file \"%s\" found in path"), ff_file_to_find); } } theend: #ifdef AMIGA proc->pr_WindowPtr = save_winptr; #endif return file_name; } #endif /* FEAT_SEARCHPATH */ /* * Change directory to "new_dir". If FEAT_SEARCHPATH is defined, search * 'cdpath' for relative directory names, otherwise just mch_chdir(). */ int vim_chdir(new_dir) char_u *new_dir; { #ifndef FEAT_SEARCHPATH return mch_chdir((char *)new_dir); #else char_u *dir_name; int r; dir_name = find_directory_in_path(new_dir, (int)STRLEN(new_dir), FNAME_MESS, curbuf->b_ffname); if (dir_name == NULL) return -1; r = mch_chdir((char *)dir_name); vim_free(dir_name); return r; #endif } /* * Get user name from machine-specific function. * Returns the user name in "buf[len]". * Some systems are quite slow in obtaining the user name (Windows NT), thus * cache the result. * Returns OK or FAIL. */ int get_user_name(buf, len) char_u *buf; int len; { if (username == NULL) { if (mch_get_user_name(buf, len) == FAIL) return FAIL; username = vim_strsave(buf); } else vim_strncpy(buf, username, len - 1); return OK; } #ifndef HAVE_QSORT /* * Our own qsort(), for systems that don't have it. * It's simple and slow. From the K&R C book. */ void qsort(base, elm_count, elm_size, cmp) void *base; size_t elm_count; size_t elm_size; int (*cmp) __ARGS((const void *, const void *)); { char_u *buf; char_u *p1; char_u *p2; int i, j; int gap; buf = alloc((unsigned)elm_size); if (buf == NULL) return; for (gap = elm_count / 2; gap > 0; gap /= 2) for (i = gap; i < elm_count; ++i) for (j = i - gap; j >= 0; j -= gap) { /* Compare the elements. */ p1 = (char_u *)base + j * elm_size; p2 = (char_u *)base + (j + gap) * elm_size; if ((*cmp)((void *)p1, (void *)p2) <= 0) break; /* Exchange the elements. */ mch_memmove(buf, p1, elm_size); mch_memmove(p1, p2, elm_size); mch_memmove(p2, buf, elm_size); } vim_free(buf); } #endif /* * Sort an array of strings. */ static int #ifdef __BORLANDC__ _RTLENTRYF #endif sort_compare __ARGS((const void *s1, const void *s2)); static int #ifdef __BORLANDC__ _RTLENTRYF #endif sort_compare(s1, s2) const void *s1; const void *s2; { return STRCMP(*(char **)s1, *(char **)s2); } void sort_strings(files, count) char_u **files; int count; { qsort((void *)files, (size_t)count, sizeof(char_u *), sort_compare); } #if !defined(NO_EXPANDPATH) || defined(PROTO) /* * Compare path "p[]" to "q[]". * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]" * Return value like strcmp(p, q), but consider path separators. */ int pathcmp(p, q, maxlen) const char *p, *q; int maxlen; { int i; const char *s = NULL; for (i = 0; maxlen < 0 || i < maxlen; ++i) { /* End of "p": check if "q" also ends or just has a slash. */ if (p[i] == NUL) { if (q[i] == NUL) /* full match */ return 0; s = q; break; } /* End of "q": check if "p" just has a slash. */ if (q[i] == NUL) { s = p; break; } if ( #ifdef CASE_INSENSITIVE_FILENAME TOUPPER_LOC(p[i]) != TOUPPER_LOC(q[i]) #else p[i] != q[i] #endif #ifdef BACKSLASH_IN_FILENAME /* consider '/' and '\\' to be equal */ && !((p[i] == '/' && q[i] == '\\') || (p[i] == '\\' && q[i] == '/')) #endif ) { if (vim_ispathsep(p[i])) return -1; if (vim_ispathsep(q[i])) return 1; return ((char_u *)p)[i] - ((char_u *)q)[i]; /* no match */ } } if (s == NULL) /* "i" ran into "maxlen" */ return 0; /* ignore a trailing slash, but not "//" or ":/" */ if (s[i + 1] == NUL && i > 0 && !after_pathsep((char_u *)s, (char_u *)s + i) #ifdef BACKSLASH_IN_FILENAME && (s[i] == '/' || s[i] == '\\') #else && s[i] == '/' #endif ) return 0; /* match with trailing slash */ if (s == q) return -1; /* no match */ return 1; } #endif /* * The putenv() implementation below comes from the "screen" program. * Included with permission from Juergen Weigert. * See pty.c for the copyright notice. */ /* * putenv -- put value into environment * * Usage: i = putenv (string) * int i; * char *string; * * where string is of the form <name>=<value>. * Putenv returns 0 normally, -1 on error (not enough core for malloc). * * Putenv may need to add a new name into the environment, or to * associate a value longer than the current value with a particular * name. So, to make life simpler, putenv() copies your entire * environment into the heap (i.e. malloc()) from the stack * (i.e. where it resides when your process is initiated) the first * time you call it. * * (history removed, not very interesting. See the "screen" sources.) */ #if !defined(HAVE_SETENV) && !defined(HAVE_PUTENV) #define EXTRASIZE 5 /* increment to add to env. size */ static int envsize = -1; /* current size of environment */ #ifndef MACOS_CLASSIC extern #endif char **environ; /* the global which is your env. */ static int findenv __ARGS((char *name)); /* look for a name in the env. */ static int newenv __ARGS((void)); /* copy env. from stack to heap */ static int moreenv __ARGS((void)); /* incr. size of env. */ int putenv(string) const char *string; { int i; char *p; if (envsize < 0) { /* first time putenv called */ if (newenv() < 0) /* copy env. to heap */ return -1; } i = findenv((char *)string); /* look for name in environment */ if (i < 0) { /* name must be added */ for (i = 0; environ[i]; i++); if (i >= (envsize - 1)) { /* need new slot */ if (moreenv() < 0) return -1; } p = (char *)alloc((unsigned)(strlen(string) + 1)); if (p == NULL) /* not enough core */ return -1; environ[i + 1] = 0; /* new end of env. */ } else { /* name already in env. */ p = vim_realloc(environ[i], strlen(string) + 1); if (p == NULL) return -1; } sprintf(p, "%s", string); /* copy into env. */ environ[i] = p; return 0; } static int findenv(name) char *name; { char *namechar, *envchar; int i, found; found = 0; for (i = 0; environ[i] && !found; i++) { envchar = environ[i]; namechar = name; while (*namechar && *namechar != '=' && (*namechar == *envchar)) { namechar++; envchar++; } found = ((*namechar == '\0' || *namechar == '=') && *envchar == '='); } return found ? i - 1 : -1; } static int newenv() { char **env, *elem; int i, esize; #ifdef MACOS /* for Mac a new, empty environment is created */ i = 0; #else for (i = 0; environ[i]; i++) ; #endif esize = i + EXTRASIZE + 1; env = (char **)alloc((unsigned)(esize * sizeof (elem))); if (env == NULL) return -1; #ifndef MACOS for (i = 0; environ[i]; i++) { elem = (char *)alloc((unsigned)(strlen(environ[i]) + 1)); if (elem == NULL) return -1; env[i] = elem; strcpy(elem, environ[i]); } #endif env[i] = 0; environ = env; envsize = esize; return 0; } static int moreenv() { int esize; char **env; esize = envsize + EXTRASIZE; env = (char **)vim_realloc((char *)environ, esize * sizeof (*env)); if (env == 0) return -1; environ = env; envsize = esize; return 0; } # ifdef USE_VIMPTY_GETENV char_u * vimpty_getenv(string) const char_u *string; { int i; char_u *p; if (envsize < 0) return NULL; i = findenv((char *)string); if (i < 0) return NULL; p = vim_strchr((char_u *)environ[i], '='); return (p + 1); } # endif #endif /* !defined(HAVE_SETENV) && !defined(HAVE_PUTENV) */ #if defined(FEAT_EVAL) || defined(FEAT_SPELL) || defined(PROTO) /* * Return 0 for not writable, 1 for writable file, 2 for a dir which we have * rights to write into. */ int filewritable(fname) char_u *fname; { int retval = 0; #if defined(UNIX) || defined(VMS) int perm = 0; #endif #if defined(UNIX) || defined(VMS) perm = mch_getperm(fname); #endif #ifndef MACOS_CLASSIC /* TODO: get either mch_writable or mch_access */ if ( # ifdef WIN3264 mch_writable(fname) && # else # if defined(UNIX) || defined(VMS) (perm & 0222) && # endif # endif mch_access((char *)fname, W_OK) == 0 ) #endif { ++retval; if (mch_isdir(fname)) ++retval; } return retval; } #endif /* * Print an error message with one or two "%s" and one or two string arguments. * This is not in message.c to avoid a warning for prototypes. */ int emsg3(s, a1, a2) char_u *s, *a1, *a2; { if (emsg_not_now()) return TRUE; /* no error messages at the moment */ #ifdef HAVE_STDARG_H vim_snprintf((char *)IObuff, IOSIZE, (char *)s, a1, a2); #else vim_snprintf((char *)IObuff, IOSIZE, (char *)s, (long_u)a1, (long_u)a2); #endif return emsg(IObuff); } /* * Print an error message with one "%ld" and one long int argument. * This is not in message.c to avoid a warning for prototypes. */ int emsgn(s, n) char_u *s; long n; { if (emsg_not_now()) return TRUE; /* no error messages at the moment */ vim_snprintf((char *)IObuff, IOSIZE, (char *)s, n); return emsg(IObuff); } #if defined(FEAT_SPELL) || defined(FEAT_PERSISTENT_UNDO) || defined(PROTO) /* * Read 2 bytes from "fd" and turn them into an int, MSB first. */ int get2c(fd) FILE *fd; { int n; n = getc(fd); n = (n << 8) + getc(fd); return n; } /* * Read 3 bytes from "fd" and turn them into an int, MSB first. */ int get3c(fd) FILE *fd; { int n; n = getc(fd); n = (n << 8) + getc(fd); n = (n << 8) + getc(fd); return n; } /* * Read 4 bytes from "fd" and turn them into an int, MSB first. */ int get4c(fd) FILE *fd; { int n; n = getc(fd); n = (n << 8) + getc(fd); n = (n << 8) + getc(fd); n = (n << 8) + getc(fd); return n; } /* * Read 8 bytes from "fd" and turn them into a time_t, MSB first. */ time_t get8ctime(fd) FILE *fd; { time_t n = 0; int i; for (i = 0; i < 8; ++i) n = (n << 8) + getc(fd); return n; } /* * Read a string of length "cnt" from "fd" into allocated memory. * Returns NULL when out of memory or unable to read that many bytes. */ char_u * read_string(fd, cnt) FILE *fd; int cnt; { char_u *str; int i; int c; /* allocate memory */ str = alloc((unsigned)cnt + 1); if (str != NULL) { /* Read the string. Quit when running into the EOF. */ for (i = 0; i < cnt; ++i) { c = getc(fd); if (c == EOF) { vim_free(str); return NULL; } str[i] = c; } str[i] = NUL; } return str; } /* * Write a number to file "fd", MSB first, in "len" bytes. */ int put_bytes(fd, nr, len) FILE *fd; long_u nr; int len; { int i; for (i = len - 1; i >= 0; --i) if (putc((int)(nr >> (i * 8)), fd) == EOF) return FAIL; return OK; } #ifdef _MSC_VER # if (_MSC_VER <= 1200) /* This line is required for VC6 without the service pack. Also see the * matching #pragma below. */ # pragma optimize("", off) # endif #endif /* * Write time_t to file "fd" in 8 bytes. */ void put_time(fd, the_time) FILE *fd; time_t the_time; { int c; int i; time_t wtime = the_time; /* time_t can be up to 8 bytes in size, more than long_u, thus we * can't use put_bytes() here. * Another problem is that ">>" may do an arithmetic shift that keeps the * sign. This happens for large values of wtime. A cast to long_u may * truncate if time_t is 8 bytes. So only use a cast when it is 4 bytes, * it's safe to assume that long_u is 4 bytes or more and when using 8 * bytes the top bit won't be set. */ for (i = 7; i >= 0; --i) { if (i + 1 > (int)sizeof(time_t)) /* ">>" doesn't work well when shifting more bits than avail */ putc(0, fd); else { #if defined(SIZEOF_TIME_T) && SIZEOF_TIME_T > 4 c = (int)(wtime >> (i * 8)); #else c = (int)((long_u)wtime >> (i * 8)); #endif putc(c, fd); } } } #ifdef _MSC_VER # if (_MSC_VER <= 1200) # pragma optimize("", on) # endif #endif #endif #if (defined(FEAT_MBYTE) && defined(FEAT_QUICKFIX)) \ || defined(FEAT_SPELL) || defined(PROTO) /* * Return TRUE if string "s" contains a non-ASCII character (128 or higher). * When "s" is NULL FALSE is returned. */ int has_non_ascii(s) char_u *s; { char_u *p; if (s != NULL) for (p = s; *p != NUL; ++p) if (*p >= 128) return TRUE; return FALSE; } #endif
zyz2011-vim
src/misc2.c
C
gpl2
155,405
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * spell.c: code for spell checking * * The spell checking mechanism uses a tree (aka trie). Each node in the tree * has a list of bytes that can appear (siblings). For each byte there is a * pointer to the node with the byte that follows in the word (child). * * A NUL byte is used where the word may end. The bytes are sorted, so that * binary searching can be used and the NUL bytes are at the start. The * number of possible bytes is stored before the list of bytes. * * The tree uses two arrays: "byts" stores the characters, "idxs" stores * either the next index or flags. The tree starts at index 0. For example, * to lookup "vi" this sequence is followed: * i = 0 * len = byts[i] * n = where "v" appears in byts[i + 1] to byts[i + len] * i = idxs[n] * len = byts[i] * n = where "i" appears in byts[i + 1] to byts[i + len] * i = idxs[n] * len = byts[i] * find that byts[i + 1] is 0, idxs[i + 1] has flags for "vi". * * There are two word trees: one with case-folded words and one with words in * original case. The second one is only used for keep-case words and is * usually small. * * There is one additional tree for when not all prefixes are applied when * generating the .spl file. This tree stores all the possible prefixes, as * if they were words. At each word (prefix) end the prefix nr is stored, the * following word must support this prefix nr. And the condition nr is * stored, used to lookup the condition that the word must match with. * * Thanks to Olaf Seibert for providing an example implementation of this tree * and the compression mechanism. * LZ trie ideas: * http://www.irb.hr/hr/home/ristov/papers/RistovLZtrieRevision1.pdf * More papers: http://www-igm.univ-mlv.fr/~laporte/publi_en.html * * Matching involves checking the caps type: Onecap ALLCAP KeepCap. * * Why doesn't Vim use aspell/ispell/myspell/etc.? * See ":help develop-spell". */ /* Use SPELL_PRINTTREE for debugging: dump the word tree after adding a word. * Only use it for small word lists! */ #if 0 # define SPELL_PRINTTREE #endif /* Use DEBUG_TRIEWALK to print the changes made in suggest_trie_walk() for a * specific word. */ #if 0 # define DEBUG_TRIEWALK #endif /* * Use this to adjust the score after finding suggestions, based on the * suggested word sounding like the bad word. This is much faster than doing * it for every possible suggestion. * Disadvantage: When "the" is typed as "hte" it sounds quite different ("@" * vs "ht") and goes down in the list. * Used when 'spellsuggest' is set to "best". */ #define RESCORE(word_score, sound_score) ((3 * word_score + sound_score) / 4) /* * Do the opposite: based on a maximum end score and a known sound score, * compute the maximum word score that can be used. */ #define MAXSCORE(word_score, sound_score) ((4 * word_score - sound_score) / 3) /* * Vim spell file format: <HEADER> * <SECTIONS> * <LWORDTREE> * <KWORDTREE> * <PREFIXTREE> * * <HEADER>: <fileID> <versionnr> * * <fileID> 8 bytes "VIMspell" * <versionnr> 1 byte VIMSPELLVERSION * * * Sections make it possible to add information to the .spl file without * making it incompatible with previous versions. There are two kinds of * sections: * 1. Not essential for correct spell checking. E.g. for making suggestions. * These are skipped when not supported. * 2. Optional information, but essential for spell checking when present. * E.g. conditions for affixes. When this section is present but not * supported an error message is given. * * <SECTIONS>: <section> ... <sectionend> * * <section>: <sectionID> <sectionflags> <sectionlen> (section contents) * * <sectionID> 1 byte number from 0 to 254 identifying the section * * <sectionflags> 1 byte SNF_REQUIRED: this section is required for correct * spell checking * * <sectionlen> 4 bytes length of section contents, MSB first * * <sectionend> 1 byte SN_END * * * sectionID == SN_INFO: <infotext> * <infotext> N bytes free format text with spell file info (version, * website, etc) * * sectionID == SN_REGION: <regionname> ... * <regionname> 2 bytes Up to 8 region names: ca, au, etc. Lower case. * First <regionname> is region 1. * * sectionID == SN_CHARFLAGS: <charflagslen> <charflags> * <folcharslen> <folchars> * <charflagslen> 1 byte Number of bytes in <charflags> (should be 128). * <charflags> N bytes List of flags (first one is for character 128): * 0x01 word character CF_WORD * 0x02 upper-case character CF_UPPER * <folcharslen> 2 bytes Number of bytes in <folchars>. * <folchars> N bytes Folded characters, first one is for character 128. * * sectionID == SN_MIDWORD: <midword> * <midword> N bytes Characters that are word characters only when used * in the middle of a word. * * sectionID == SN_PREFCOND: <prefcondcnt> <prefcond> ... * <prefcondcnt> 2 bytes Number of <prefcond> items following. * <prefcond> : <condlen> <condstr> * <condlen> 1 byte Length of <condstr>. * <condstr> N bytes Condition for the prefix. * * sectionID == SN_REP: <repcount> <rep> ... * <repcount> 2 bytes number of <rep> items, MSB first. * <rep> : <repfromlen> <repfrom> <reptolen> <repto> * <repfromlen> 1 byte length of <repfrom> * <repfrom> N bytes "from" part of replacement * <reptolen> 1 byte length of <repto> * <repto> N bytes "to" part of replacement * * sectionID == SN_REPSAL: <repcount> <rep> ... * just like SN_REP but for soundfolded words * * sectionID == SN_SAL: <salflags> <salcount> <sal> ... * <salflags> 1 byte flags for soundsalike conversion: * SAL_F0LLOWUP * SAL_COLLAPSE * SAL_REM_ACCENTS * <salcount> 2 bytes number of <sal> items following * <sal> : <salfromlen> <salfrom> <saltolen> <salto> * <salfromlen> 1 byte length of <salfrom> * <salfrom> N bytes "from" part of soundsalike * <saltolen> 1 byte length of <salto> * <salto> N bytes "to" part of soundsalike * * sectionID == SN_SOFO: <sofofromlen> <sofofrom> <sofotolen> <sofoto> * <sofofromlen> 2 bytes length of <sofofrom> * <sofofrom> N bytes "from" part of soundfold * <sofotolen> 2 bytes length of <sofoto> * <sofoto> N bytes "to" part of soundfold * * sectionID == SN_SUGFILE: <timestamp> * <timestamp> 8 bytes time in seconds that must match with .sug file * * sectionID == SN_NOSPLITSUGS: nothing * * sectionID == SN_WORDS: <word> ... * <word> N bytes NUL terminated common word * * sectionID == SN_MAP: <mapstr> * <mapstr> N bytes String with sequences of similar characters, * separated by slashes. * * sectionID == SN_COMPOUND: <compmax> <compminlen> <compsylmax> <compoptions> * <comppatcount> <comppattern> ... <compflags> * <compmax> 1 byte Maximum nr of words in compound word. * <compminlen> 1 byte Minimal word length for compounding. * <compsylmax> 1 byte Maximum nr of syllables in compound word. * <compoptions> 2 bytes COMP_ flags. * <comppatcount> 2 bytes number of <comppattern> following * <compflags> N bytes Flags from COMPOUNDRULE items, separated by * slashes. * * <comppattern>: <comppatlen> <comppattext> * <comppatlen> 1 byte length of <comppattext> * <comppattext> N bytes end or begin chars from CHECKCOMPOUNDPATTERN * * sectionID == SN_NOBREAK: (empty, its presence is what matters) * * sectionID == SN_SYLLABLE: <syllable> * <syllable> N bytes String from SYLLABLE item. * * <LWORDTREE>: <wordtree> * * <KWORDTREE>: <wordtree> * * <PREFIXTREE>: <wordtree> * * * <wordtree>: <nodecount> <nodedata> ... * * <nodecount> 4 bytes Number of nodes following. MSB first. * * <nodedata>: <siblingcount> <sibling> ... * * <siblingcount> 1 byte Number of siblings in this node. The siblings * follow in sorted order. * * <sibling>: <byte> [ <nodeidx> <xbyte> * | <flags> [<flags2>] [<region>] [<affixID>] * | [<pflags>] <affixID> <prefcondnr> ] * * <byte> 1 byte Byte value of the sibling. Special cases: * BY_NOFLAGS: End of word without flags and for all * regions. * For PREFIXTREE <affixID> and * <prefcondnr> follow. * BY_FLAGS: End of word, <flags> follow. * For PREFIXTREE <pflags>, <affixID> * and <prefcondnr> follow. * BY_FLAGS2: End of word, <flags> and <flags2> * follow. Not used in PREFIXTREE. * BY_INDEX: Child of sibling is shared, <nodeidx> * and <xbyte> follow. * * <nodeidx> 3 bytes Index of child for this sibling, MSB first. * * <xbyte> 1 byte byte value of the sibling. * * <flags> 1 byte bitmask of: * WF_ALLCAP word must have only capitals * WF_ONECAP first char of word must be capital * WF_KEEPCAP keep-case word * WF_FIXCAP keep-case word, all caps not allowed * WF_RARE rare word * WF_BANNED bad word * WF_REGION <region> follows * WF_AFX <affixID> follows * * <flags2> 1 byte Bitmask of: * WF_HAS_AFF >> 8 word includes affix * WF_NEEDCOMP >> 8 word only valid in compound * WF_NOSUGGEST >> 8 word not used for suggestions * WF_COMPROOT >> 8 word already a compound * WF_NOCOMPBEF >> 8 no compounding before this word * WF_NOCOMPAFT >> 8 no compounding after this word * * <pflags> 1 byte bitmask of: * WFP_RARE rare prefix * WFP_NC non-combining prefix * WFP_UP letter after prefix made upper case * * <region> 1 byte Bitmask for regions in which word is valid. When * omitted it's valid in all regions. * Lowest bit is for region 1. * * <affixID> 1 byte ID of affix that can be used with this word. In * PREFIXTREE used for the required prefix ID. * * <prefcondnr> 2 bytes Prefix condition number, index in <prefcond> list * from HEADER. * * All text characters are in 'encoding', but stored as single bytes. */ /* * Vim .sug file format: <SUGHEADER> * <SUGWORDTREE> * <SUGTABLE> * * <SUGHEADER>: <fileID> <versionnr> <timestamp> * * <fileID> 6 bytes "VIMsug" * <versionnr> 1 byte VIMSUGVERSION * <timestamp> 8 bytes timestamp that must match with .spl file * * * <SUGWORDTREE>: <wordtree> (see above, no flags or region used) * * * <SUGTABLE>: <sugwcount> <sugline> ... * * <sugwcount> 4 bytes number of <sugline> following * * <sugline>: <sugnr> ... NUL * * <sugnr>: X bytes word number that results in this soundfolded word, * stored as an offset to the previous number in as * few bytes as possible, see offset2bytes()) */ #include "vim.h" #if defined(FEAT_SPELL) || defined(PROTO) #ifndef UNIX /* it's in os_unix.h for Unix */ # include <time.h> /* for time_t */ #endif #define MAXWLEN 250 /* Assume max. word len is this many bytes. Some places assume a word length fits in a byte, thus it can't be above 255. */ /* Type used for indexes in the word tree need to be at least 4 bytes. If int * is 8 bytes we could use something smaller, but what? */ #if SIZEOF_INT > 3 typedef int idx_T; #else typedef long idx_T; #endif #ifdef VMS # define SPL_FNAME_TMPL "%s_%s.spl" # define SPL_FNAME_ADD "_add." # define SPL_FNAME_ASCII "_ascii." #else # define SPL_FNAME_TMPL "%s.%s.spl" # define SPL_FNAME_ADD ".add." # define SPL_FNAME_ASCII ".ascii." #endif /* Flags used for a word. Only the lowest byte can be used, the region byte * comes above it. */ #define WF_REGION 0x01 /* region byte follows */ #define WF_ONECAP 0x02 /* word with one capital (or all capitals) */ #define WF_ALLCAP 0x04 /* word must be all capitals */ #define WF_RARE 0x08 /* rare word */ #define WF_BANNED 0x10 /* bad word */ #define WF_AFX 0x20 /* affix ID follows */ #define WF_FIXCAP 0x40 /* keep-case word, allcap not allowed */ #define WF_KEEPCAP 0x80 /* keep-case word */ /* for <flags2>, shifted up one byte to be used in wn_flags */ #define WF_HAS_AFF 0x0100 /* word includes affix */ #define WF_NEEDCOMP 0x0200 /* word only valid in compound */ #define WF_NOSUGGEST 0x0400 /* word not to be suggested */ #define WF_COMPROOT 0x0800 /* already compounded word, COMPOUNDROOT */ #define WF_NOCOMPBEF 0x1000 /* no compounding before this word */ #define WF_NOCOMPAFT 0x2000 /* no compounding after this word */ /* only used for su_badflags */ #define WF_MIXCAP 0x20 /* mix of upper and lower case: macaRONI */ #define WF_CAPMASK (WF_ONECAP | WF_ALLCAP | WF_KEEPCAP | WF_FIXCAP) /* flags for <pflags> */ #define WFP_RARE 0x01 /* rare prefix */ #define WFP_NC 0x02 /* prefix is not combining */ #define WFP_UP 0x04 /* to-upper prefix */ #define WFP_COMPPERMIT 0x08 /* prefix with COMPOUNDPERMITFLAG */ #define WFP_COMPFORBID 0x10 /* prefix with COMPOUNDFORBIDFLAG */ /* Flags for postponed prefixes in "sl_pidxs". Must be above affixID (one * byte) and prefcondnr (two bytes). */ #define WF_RAREPFX (WFP_RARE << 24) /* rare postponed prefix */ #define WF_PFX_NC (WFP_NC << 24) /* non-combining postponed prefix */ #define WF_PFX_UP (WFP_UP << 24) /* to-upper postponed prefix */ #define WF_PFX_COMPPERMIT (WFP_COMPPERMIT << 24) /* postponed prefix with * COMPOUNDPERMITFLAG */ #define WF_PFX_COMPFORBID (WFP_COMPFORBID << 24) /* postponed prefix with * COMPOUNDFORBIDFLAG */ /* flags for <compoptions> */ #define COMP_CHECKDUP 1 /* CHECKCOMPOUNDDUP */ #define COMP_CHECKREP 2 /* CHECKCOMPOUNDREP */ #define COMP_CHECKCASE 4 /* CHECKCOMPOUNDCASE */ #define COMP_CHECKTRIPLE 8 /* CHECKCOMPOUNDTRIPLE */ /* Special byte values for <byte>. Some are only used in the tree for * postponed prefixes, some only in the other trees. This is a bit messy... */ #define BY_NOFLAGS 0 /* end of word without flags or region; for * postponed prefix: no <pflags> */ #define BY_INDEX 1 /* child is shared, index follows */ #define BY_FLAGS 2 /* end of word, <flags> byte follows; for * postponed prefix: <pflags> follows */ #define BY_FLAGS2 3 /* end of word, <flags> and <flags2> bytes * follow; never used in prefix tree */ #define BY_SPECIAL BY_FLAGS2 /* highest special byte value */ /* Info from "REP", "REPSAL" and "SAL" entries in ".aff" file used in si_rep, * si_repsal, sl_rep, and si_sal. Not for sl_sal! * One replacement: from "ft_from" to "ft_to". */ typedef struct fromto_S { char_u *ft_from; char_u *ft_to; } fromto_T; /* Info from "SAL" entries in ".aff" file used in sl_sal. * The info is split for quick processing by spell_soundfold(). * Note that "sm_oneof" and "sm_rules" point into sm_lead. */ typedef struct salitem_S { char_u *sm_lead; /* leading letters */ int sm_leadlen; /* length of "sm_lead" */ char_u *sm_oneof; /* letters from () or NULL */ char_u *sm_rules; /* rules like ^, $, priority */ char_u *sm_to; /* replacement. */ #ifdef FEAT_MBYTE int *sm_lead_w; /* wide character copy of "sm_lead" */ int *sm_oneof_w; /* wide character copy of "sm_oneof" */ int *sm_to_w; /* wide character copy of "sm_to" */ #endif } salitem_T; #ifdef FEAT_MBYTE typedef int salfirst_T; #else typedef short salfirst_T; #endif /* Values for SP_*ERROR are negative, positive values are used by * read_cnt_string(). */ #define SP_TRUNCERROR -1 /* spell file truncated error */ #define SP_FORMERROR -2 /* format error in spell file */ #define SP_OTHERERROR -3 /* other error while reading spell file */ /* * Structure used to store words and other info for one language, loaded from * a .spl file. * The main access is through the tree in "sl_fbyts/sl_fidxs", storing the * case-folded words. "sl_kbyts/sl_kidxs" is for keep-case words. * * The "byts" array stores the possible bytes in each tree node, preceded by * the number of possible bytes, sorted on byte value: * <len> <byte1> <byte2> ... * The "idxs" array stores the index of the child node corresponding to the * byte in "byts". * Exception: when the byte is zero, the word may end here and "idxs" holds * the flags, region mask and affixID for the word. There may be several * zeros in sequence for alternative flag/region/affixID combinations. */ typedef struct slang_S slang_T; struct slang_S { slang_T *sl_next; /* next language */ char_u *sl_name; /* language name "en", "en.rare", "nl", etc. */ char_u *sl_fname; /* name of .spl file */ int sl_add; /* TRUE if it's a .add file. */ char_u *sl_fbyts; /* case-folded word bytes */ idx_T *sl_fidxs; /* case-folded word indexes */ char_u *sl_kbyts; /* keep-case word bytes */ idx_T *sl_kidxs; /* keep-case word indexes */ char_u *sl_pbyts; /* prefix tree word bytes */ idx_T *sl_pidxs; /* prefix tree word indexes */ char_u *sl_info; /* infotext string or NULL */ char_u sl_regions[17]; /* table with up to 8 region names plus NUL */ char_u *sl_midword; /* MIDWORD string or NULL */ hashtab_T sl_wordcount; /* hashtable with word count, wordcount_T */ int sl_compmax; /* COMPOUNDWORDMAX (default: MAXWLEN) */ int sl_compminlen; /* COMPOUNDMIN (default: 0) */ int sl_compsylmax; /* COMPOUNDSYLMAX (default: MAXWLEN) */ int sl_compoptions; /* COMP_* flags */ garray_T sl_comppat; /* CHECKCOMPOUNDPATTERN items */ regprog_T *sl_compprog; /* COMPOUNDRULE turned into a regexp progrm * (NULL when no compounding) */ char_u *sl_comprules; /* all COMPOUNDRULE concatenated (or NULL) */ char_u *sl_compstartflags; /* flags for first compound word */ char_u *sl_compallflags; /* all flags for compound words */ char_u sl_nobreak; /* When TRUE: no spaces between words */ char_u *sl_syllable; /* SYLLABLE repeatable chars or NULL */ garray_T sl_syl_items; /* syllable items */ int sl_prefixcnt; /* number of items in "sl_prefprog" */ regprog_T **sl_prefprog; /* table with regprogs for prefixes */ garray_T sl_rep; /* list of fromto_T entries from REP lines */ short sl_rep_first[256]; /* indexes where byte first appears, -1 if there is none */ garray_T sl_sal; /* list of salitem_T entries from SAL lines */ salfirst_T sl_sal_first[256]; /* indexes where byte first appears, -1 if there is none */ int sl_followup; /* SAL followup */ int sl_collapse; /* SAL collapse_result */ int sl_rem_accents; /* SAL remove_accents */ int sl_sofo; /* SOFOFROM and SOFOTO instead of SAL items: * "sl_sal_first" maps chars, when has_mbyte * "sl_sal" is a list of wide char lists. */ garray_T sl_repsal; /* list of fromto_T entries from REPSAL lines */ short sl_repsal_first[256]; /* sl_rep_first for REPSAL lines */ int sl_nosplitsugs; /* don't suggest splitting a word */ /* Info from the .sug file. Loaded on demand. */ time_t sl_sugtime; /* timestamp for .sug file */ char_u *sl_sbyts; /* soundfolded word bytes */ idx_T *sl_sidxs; /* soundfolded word indexes */ buf_T *sl_sugbuf; /* buffer with word number table */ int sl_sugloaded; /* TRUE when .sug file was loaded or failed to load */ int sl_has_map; /* TRUE if there is a MAP line */ #ifdef FEAT_MBYTE hashtab_T sl_map_hash; /* MAP for multi-byte chars */ int sl_map_array[256]; /* MAP for first 256 chars */ #else char_u sl_map_array[256]; /* MAP for first 256 chars */ #endif hashtab_T sl_sounddone; /* table with soundfolded words that have handled, see add_sound_suggest() */ }; /* First language that is loaded, start of the linked list of loaded * languages. */ static slang_T *first_lang = NULL; /* Flags used in .spl file for soundsalike flags. */ #define SAL_F0LLOWUP 1 #define SAL_COLLAPSE 2 #define SAL_REM_ACCENTS 4 /* * Structure used in "b_langp", filled from 'spelllang'. */ typedef struct langp_S { slang_T *lp_slang; /* info for this language */ slang_T *lp_sallang; /* language used for sound folding or NULL */ slang_T *lp_replang; /* language used for REP items or NULL */ int lp_region; /* bitmask for region or REGION_ALL */ } langp_T; #define LANGP_ENTRY(ga, i) (((langp_T *)(ga).ga_data) + (i)) #define REGION_ALL 0xff /* word valid in all regions */ #define VIMSPELLMAGIC "VIMspell" /* string at start of Vim spell file */ #define VIMSPELLMAGICL 8 #define VIMSPELLVERSION 50 #define VIMSUGMAGIC "VIMsug" /* string at start of Vim .sug file */ #define VIMSUGMAGICL 6 #define VIMSUGVERSION 1 /* Section IDs. Only renumber them when VIMSPELLVERSION changes! */ #define SN_REGION 0 /* <regionname> section */ #define SN_CHARFLAGS 1 /* charflags section */ #define SN_MIDWORD 2 /* <midword> section */ #define SN_PREFCOND 3 /* <prefcond> section */ #define SN_REP 4 /* REP items section */ #define SN_SAL 5 /* SAL items section */ #define SN_SOFO 6 /* soundfolding section */ #define SN_MAP 7 /* MAP items section */ #define SN_COMPOUND 8 /* compound words section */ #define SN_SYLLABLE 9 /* syllable section */ #define SN_NOBREAK 10 /* NOBREAK section */ #define SN_SUGFILE 11 /* timestamp for .sug file */ #define SN_REPSAL 12 /* REPSAL items section */ #define SN_WORDS 13 /* common words */ #define SN_NOSPLITSUGS 14 /* don't split word for suggestions */ #define SN_INFO 15 /* info section */ #define SN_END 255 /* end of sections */ #define SNF_REQUIRED 1 /* <sectionflags>: required section */ /* Result values. Lower number is accepted over higher one. */ #define SP_BANNED -1 #define SP_OK 0 #define SP_RARE 1 #define SP_LOCAL 2 #define SP_BAD 3 /* file used for "zG" and "zW" */ static char_u *int_wordlist = NULL; typedef struct wordcount_S { short_u wc_count; /* nr of times word was seen */ char_u wc_word[1]; /* word, actually longer */ } wordcount_T; static wordcount_T dumwc; #define WC_KEY_OFF (unsigned)(dumwc.wc_word - (char_u *)&dumwc) #define HI2WC(hi) ((wordcount_T *)((hi)->hi_key - WC_KEY_OFF)) #define MAXWORDCOUNT 0xffff /* * Information used when looking for suggestions. */ typedef struct suginfo_S { garray_T su_ga; /* suggestions, contains "suggest_T" */ int su_maxcount; /* max. number of suggestions displayed */ int su_maxscore; /* maximum score for adding to su_ga */ int su_sfmaxscore; /* idem, for when doing soundfold words */ garray_T su_sga; /* like su_ga, sound-folded scoring */ char_u *su_badptr; /* start of bad word in line */ int su_badlen; /* length of detected bad word in line */ int su_badflags; /* caps flags for bad word */ char_u su_badword[MAXWLEN]; /* bad word truncated at su_badlen */ char_u su_fbadword[MAXWLEN]; /* su_badword case-folded */ char_u su_sal_badword[MAXWLEN]; /* su_badword soundfolded */ hashtab_T su_banned; /* table with banned words */ slang_T *su_sallang; /* default language for sound folding */ } suginfo_T; /* One word suggestion. Used in "si_ga". */ typedef struct suggest_S { char_u *st_word; /* suggested word, allocated string */ int st_wordlen; /* STRLEN(st_word) */ int st_orglen; /* length of replaced text */ int st_score; /* lower is better */ int st_altscore; /* used when st_score compares equal */ int st_salscore; /* st_score is for soundalike */ int st_had_bonus; /* bonus already included in score */ slang_T *st_slang; /* language used for sound folding */ } suggest_T; #define SUG(ga, i) (((suggest_T *)(ga).ga_data)[i]) /* TRUE if a word appears in the list of banned words. */ #define WAS_BANNED(su, word) (!HASHITEM_EMPTY(hash_find(&su->su_banned, word))) /* Number of suggestions kept when cleaning up. We need to keep more than * what is displayed, because when rescore_suggestions() is called the score * may change and wrong suggestions may be removed later. */ #define SUG_CLEAN_COUNT(su) ((su)->su_maxcount < 130 ? 150 : (su)->su_maxcount + 20) /* Threshold for sorting and cleaning up suggestions. Don't want to keep lots * of suggestions that are not going to be displayed. */ #define SUG_MAX_COUNT(su) (SUG_CLEAN_COUNT(su) + 50) /* score for various changes */ #define SCORE_SPLIT 149 /* split bad word */ #define SCORE_SPLIT_NO 249 /* split bad word with NOSPLITSUGS */ #define SCORE_ICASE 52 /* slightly different case */ #define SCORE_REGION 200 /* word is for different region */ #define SCORE_RARE 180 /* rare word */ #define SCORE_SWAP 75 /* swap two characters */ #define SCORE_SWAP3 110 /* swap two characters in three */ #define SCORE_REP 65 /* REP replacement */ #define SCORE_SUBST 93 /* substitute a character */ #define SCORE_SIMILAR 33 /* substitute a similar character */ #define SCORE_SUBCOMP 33 /* substitute a composing character */ #define SCORE_DEL 94 /* delete a character */ #define SCORE_DELDUP 66 /* delete a duplicated character */ #define SCORE_DELCOMP 28 /* delete a composing character */ #define SCORE_INS 96 /* insert a character */ #define SCORE_INSDUP 67 /* insert a duplicate character */ #define SCORE_INSCOMP 30 /* insert a composing character */ #define SCORE_NONWORD 103 /* change non-word to word char */ #define SCORE_FILE 30 /* suggestion from a file */ #define SCORE_MAXINIT 350 /* Initial maximum score: higher == slower. * 350 allows for about three changes. */ #define SCORE_COMMON1 30 /* subtracted for words seen before */ #define SCORE_COMMON2 40 /* subtracted for words often seen */ #define SCORE_COMMON3 50 /* subtracted for words very often seen */ #define SCORE_THRES2 10 /* word count threshold for COMMON2 */ #define SCORE_THRES3 100 /* word count threshold for COMMON3 */ /* When trying changed soundfold words it becomes slow when trying more than * two changes. With less then two changes it's slightly faster but we miss a * few good suggestions. In rare cases we need to try three of four changes. */ #define SCORE_SFMAX1 200 /* maximum score for first try */ #define SCORE_SFMAX2 300 /* maximum score for second try */ #define SCORE_SFMAX3 400 /* maximum score for third try */ #define SCORE_BIG SCORE_INS * 3 /* big difference */ #define SCORE_MAXMAX 999999 /* accept any score */ #define SCORE_LIMITMAX 350 /* for spell_edit_score_limit() */ /* for spell_edit_score_limit() we need to know the minimum value of * SCORE_ICASE, SCORE_SWAP, SCORE_DEL, SCORE_SIMILAR and SCORE_INS */ #define SCORE_EDIT_MIN SCORE_SIMILAR /* * Structure to store info for word matching. */ typedef struct matchinf_S { langp_T *mi_lp; /* info for language and region */ /* pointers to original text to be checked */ char_u *mi_word; /* start of word being checked */ char_u *mi_end; /* end of matching word so far */ char_u *mi_fend; /* next char to be added to mi_fword */ char_u *mi_cend; /* char after what was used for mi_capflags */ /* case-folded text */ char_u mi_fword[MAXWLEN + 1]; /* mi_word case-folded */ int mi_fwordlen; /* nr of valid bytes in mi_fword */ /* for when checking word after a prefix */ int mi_prefarridx; /* index in sl_pidxs with list of affixID/condition */ int mi_prefcnt; /* number of entries at mi_prefarridx */ int mi_prefixlen; /* byte length of prefix */ #ifdef FEAT_MBYTE int mi_cprefixlen; /* byte length of prefix in original case */ #else # define mi_cprefixlen mi_prefixlen /* it's the same value */ #endif /* for when checking a compound word */ int mi_compoff; /* start of following word offset */ char_u mi_compflags[MAXWLEN]; /* flags for compound words used */ int mi_complen; /* nr of compound words used */ int mi_compextra; /* nr of COMPOUNDROOT words */ /* others */ int mi_result; /* result so far: SP_BAD, SP_OK, etc. */ int mi_capflags; /* WF_ONECAP WF_ALLCAP WF_KEEPCAP */ win_T *mi_win; /* buffer being checked */ /* for NOBREAK */ int mi_result2; /* "mi_resul" without following word */ char_u *mi_end2; /* "mi_end" without following word */ } matchinf_T; /* * The tables used for recognizing word characters according to spelling. * These are only used for the first 256 characters of 'encoding'. */ typedef struct spelltab_S { char_u st_isw[256]; /* flags: is word char */ char_u st_isu[256]; /* flags: is uppercase char */ char_u st_fold[256]; /* chars: folded case */ char_u st_upper[256]; /* chars: upper case */ } spelltab_T; static spelltab_T spelltab; static int did_set_spelltab; #define CF_WORD 0x01 #define CF_UPPER 0x02 static void clear_spell_chartab __ARGS((spelltab_T *sp)); static int set_spell_finish __ARGS((spelltab_T *new_st)); static int spell_iswordp __ARGS((char_u *p, win_T *wp)); static int spell_iswordp_nmw __ARGS((char_u *p)); #ifdef FEAT_MBYTE static int spell_mb_isword_class __ARGS((int cl)); static int spell_iswordp_w __ARGS((int *p, win_T *wp)); #endif static int write_spell_prefcond __ARGS((FILE *fd, garray_T *gap)); /* * For finding suggestions: At each node in the tree these states are tried: */ typedef enum { STATE_START = 0, /* At start of node check for NUL bytes (goodword * ends); if badword ends there is a match, otherwise * try splitting word. */ STATE_NOPREFIX, /* try without prefix */ STATE_SPLITUNDO, /* Undo splitting. */ STATE_ENDNUL, /* Past NUL bytes at start of the node. */ STATE_PLAIN, /* Use each byte of the node. */ STATE_DEL, /* Delete a byte from the bad word. */ STATE_INS_PREP, /* Prepare for inserting bytes. */ STATE_INS, /* Insert a byte in the bad word. */ STATE_SWAP, /* Swap two bytes. */ STATE_UNSWAP, /* Undo swap two characters. */ STATE_SWAP3, /* Swap two characters over three. */ STATE_UNSWAP3, /* Undo Swap two characters over three. */ STATE_UNROT3L, /* Undo rotate three characters left */ STATE_UNROT3R, /* Undo rotate three characters right */ STATE_REP_INI, /* Prepare for using REP items. */ STATE_REP, /* Use matching REP items from the .aff file. */ STATE_REP_UNDO, /* Undo a REP item replacement. */ STATE_FINAL /* End of this node. */ } state_T; /* * Struct to keep the state at each level in suggest_try_change(). */ typedef struct trystate_S { state_T ts_state; /* state at this level, STATE_ */ int ts_score; /* score */ idx_T ts_arridx; /* index in tree array, start of node */ short ts_curi; /* index in list of child nodes */ char_u ts_fidx; /* index in fword[], case-folded bad word */ char_u ts_fidxtry; /* ts_fidx at which bytes may be changed */ char_u ts_twordlen; /* valid length of tword[] */ char_u ts_prefixdepth; /* stack depth for end of prefix or * PFD_PREFIXTREE or PFD_NOPREFIX */ char_u ts_flags; /* TSF_ flags */ #ifdef FEAT_MBYTE char_u ts_tcharlen; /* number of bytes in tword character */ char_u ts_tcharidx; /* current byte index in tword character */ char_u ts_isdiff; /* DIFF_ values */ char_u ts_fcharstart; /* index in fword where badword char started */ #endif char_u ts_prewordlen; /* length of word in "preword[]" */ char_u ts_splitoff; /* index in "tword" after last split */ char_u ts_splitfidx; /* "ts_fidx" at word split */ char_u ts_complen; /* nr of compound words used */ char_u ts_compsplit; /* index for "compflags" where word was spit */ char_u ts_save_badflags; /* su_badflags saved here */ char_u ts_delidx; /* index in fword for char that was deleted, valid when "ts_flags" has TSF_DIDDEL */ } trystate_T; /* values for ts_isdiff */ #define DIFF_NONE 0 /* no different byte (yet) */ #define DIFF_YES 1 /* different byte found */ #define DIFF_INSERT 2 /* inserting character */ /* values for ts_flags */ #define TSF_PREFIXOK 1 /* already checked that prefix is OK */ #define TSF_DIDSPLIT 2 /* tried split at this point */ #define TSF_DIDDEL 4 /* did a delete, "ts_delidx" has index */ /* special values ts_prefixdepth */ #define PFD_NOPREFIX 0xff /* not using prefixes */ #define PFD_PREFIXTREE 0xfe /* walking through the prefix tree */ #define PFD_NOTSPECIAL 0xfd /* highest value that's not special */ /* mode values for find_word */ #define FIND_FOLDWORD 0 /* find word case-folded */ #define FIND_KEEPWORD 1 /* find keep-case word */ #define FIND_PREFIX 2 /* find word after prefix */ #define FIND_COMPOUND 3 /* find case-folded compound word */ #define FIND_KEEPCOMPOUND 4 /* find keep-case compound word */ static slang_T *slang_alloc __ARGS((char_u *lang)); static void slang_free __ARGS((slang_T *lp)); static void slang_clear __ARGS((slang_T *lp)); static void slang_clear_sug __ARGS((slang_T *lp)); static void find_word __ARGS((matchinf_T *mip, int mode)); static int match_checkcompoundpattern __ARGS((char_u *ptr, int wlen, garray_T *gap)); static int can_compound __ARGS((slang_T *slang, char_u *word, char_u *flags)); static int can_be_compound __ARGS((trystate_T *sp, slang_T *slang, char_u *compflags, int flag)); static int match_compoundrule __ARGS((slang_T *slang, char_u *compflags)); static int valid_word_prefix __ARGS((int totprefcnt, int arridx, int flags, char_u *word, slang_T *slang, int cond_req)); static void find_prefix __ARGS((matchinf_T *mip, int mode)); static int fold_more __ARGS((matchinf_T *mip)); static int spell_valid_case __ARGS((int wordflags, int treeflags)); static int no_spell_checking __ARGS((win_T *wp)); static void spell_load_lang __ARGS((char_u *lang)); static char_u *spell_enc __ARGS((void)); static void int_wordlist_spl __ARGS((char_u *fname)); static void spell_load_cb __ARGS((char_u *fname, void *cookie)); static slang_T *spell_load_file __ARGS((char_u *fname, char_u *lang, slang_T *old_lp, int silent)); static char_u *read_cnt_string __ARGS((FILE *fd, int cnt_bytes, int *lenp)); static int read_region_section __ARGS((FILE *fd, slang_T *slang, int len)); static int read_charflags_section __ARGS((FILE *fd)); static int read_prefcond_section __ARGS((FILE *fd, slang_T *lp)); static int read_rep_section __ARGS((FILE *fd, garray_T *gap, short *first)); static int read_sal_section __ARGS((FILE *fd, slang_T *slang)); static int read_words_section __ARGS((FILE *fd, slang_T *lp, int len)); static void count_common_word __ARGS((slang_T *lp, char_u *word, int len, int count)); static int score_wordcount_adj __ARGS((slang_T *slang, int score, char_u *word, int split)); static int read_sofo_section __ARGS((FILE *fd, slang_T *slang)); static int read_compound __ARGS((FILE *fd, slang_T *slang, int len)); static int byte_in_str __ARGS((char_u *str, int byte)); static int init_syl_tab __ARGS((slang_T *slang)); static int count_syllables __ARGS((slang_T *slang, char_u *word)); static int set_sofo __ARGS((slang_T *lp, char_u *from, char_u *to)); static void set_sal_first __ARGS((slang_T *lp)); #ifdef FEAT_MBYTE static int *mb_str2wide __ARGS((char_u *s)); #endif static int spell_read_tree __ARGS((FILE *fd, char_u **bytsp, idx_T **idxsp, int prefixtree, int prefixcnt)); static idx_T read_tree_node __ARGS((FILE *fd, char_u *byts, idx_T *idxs, int maxidx, idx_T startidx, int prefixtree, int maxprefcondnr)); static void clear_midword __ARGS((win_T *buf)); static void use_midword __ARGS((slang_T *lp, win_T *buf)); static int find_region __ARGS((char_u *rp, char_u *region)); static int captype __ARGS((char_u *word, char_u *end)); static int badword_captype __ARGS((char_u *word, char_u *end)); static void spell_reload_one __ARGS((char_u *fname, int added_word)); static void set_spell_charflags __ARGS((char_u *flags, int cnt, char_u *upp)); static int set_spell_chartab __ARGS((char_u *fol, char_u *low, char_u *upp)); static int spell_casefold __ARGS((char_u *p, int len, char_u *buf, int buflen)); static int check_need_cap __ARGS((linenr_T lnum, colnr_T col)); static void spell_find_suggest __ARGS((char_u *badptr, int badlen, suginfo_T *su, int maxcount, int banbadword, int need_cap, int interactive)); #ifdef FEAT_EVAL static void spell_suggest_expr __ARGS((suginfo_T *su, char_u *expr)); #endif static void spell_suggest_file __ARGS((suginfo_T *su, char_u *fname)); static void spell_suggest_intern __ARGS((suginfo_T *su, int interactive)); static void suggest_load_files __ARGS((void)); static void tree_count_words __ARGS((char_u *byts, idx_T *idxs)); static void spell_find_cleanup __ARGS((suginfo_T *su)); static void onecap_copy __ARGS((char_u *word, char_u *wcopy, int upper)); static void allcap_copy __ARGS((char_u *word, char_u *wcopy)); static void suggest_try_special __ARGS((suginfo_T *su)); static void suggest_try_change __ARGS((suginfo_T *su)); static void suggest_trie_walk __ARGS((suginfo_T *su, langp_T *lp, char_u *fword, int soundfold)); static void go_deeper __ARGS((trystate_T *stack, int depth, int score_add)); #ifdef FEAT_MBYTE static int nofold_len __ARGS((char_u *fword, int flen, char_u *word)); #endif static void find_keepcap_word __ARGS((slang_T *slang, char_u *fword, char_u *kword)); static void score_comp_sal __ARGS((suginfo_T *su)); static void score_combine __ARGS((suginfo_T *su)); static int stp_sal_score __ARGS((suggest_T *stp, suginfo_T *su, slang_T *slang, char_u *badsound)); static void suggest_try_soundalike_prep __ARGS((void)); static void suggest_try_soundalike __ARGS((suginfo_T *su)); static void suggest_try_soundalike_finish __ARGS((void)); static void add_sound_suggest __ARGS((suginfo_T *su, char_u *goodword, int score, langp_T *lp)); static int soundfold_find __ARGS((slang_T *slang, char_u *word)); static void make_case_word __ARGS((char_u *fword, char_u *cword, int flags)); static void set_map_str __ARGS((slang_T *lp, char_u *map)); static int similar_chars __ARGS((slang_T *slang, int c1, int c2)); static void add_suggestion __ARGS((suginfo_T *su, garray_T *gap, char_u *goodword, int badlen, int score, int altscore, int had_bonus, slang_T *slang, int maxsf)); static void check_suggestions __ARGS((suginfo_T *su, garray_T *gap)); static void add_banned __ARGS((suginfo_T *su, char_u *word)); static void rescore_suggestions __ARGS((suginfo_T *su)); static void rescore_one __ARGS((suginfo_T *su, suggest_T *stp)); static int cleanup_suggestions __ARGS((garray_T *gap, int maxscore, int keep)); static void spell_soundfold __ARGS((slang_T *slang, char_u *inword, int folded, char_u *res)); static void spell_soundfold_sofo __ARGS((slang_T *slang, char_u *inword, char_u *res)); static void spell_soundfold_sal __ARGS((slang_T *slang, char_u *inword, char_u *res)); #ifdef FEAT_MBYTE static void spell_soundfold_wsal __ARGS((slang_T *slang, char_u *inword, char_u *res)); #endif static int soundalike_score __ARGS((char_u *goodsound, char_u *badsound)); static int spell_edit_score __ARGS((slang_T *slang, char_u *badword, char_u *goodword)); static int spell_edit_score_limit __ARGS((slang_T *slang, char_u *badword, char_u *goodword, int limit)); #ifdef FEAT_MBYTE static int spell_edit_score_limit_w __ARGS((slang_T *slang, char_u *badword, char_u *goodword, int limit)); #endif static void dump_word __ARGS((slang_T *slang, char_u *word, char_u *pat, int *dir, int round, int flags, linenr_T lnum)); static linenr_T dump_prefixes __ARGS((slang_T *slang, char_u *word, char_u *pat, int *dir, int round, int flags, linenr_T startlnum)); static buf_T *open_spellbuf __ARGS((void)); static void close_spellbuf __ARGS((buf_T *buf)); /* * Use our own character-case definitions, because the current locale may * differ from what the .spl file uses. * These must not be called with negative number! */ #ifndef FEAT_MBYTE /* Non-multi-byte implementation. */ # define SPELL_TOFOLD(c) ((c) < 256 ? (int)spelltab.st_fold[c] : (c)) # define SPELL_TOUPPER(c) ((c) < 256 ? (int)spelltab.st_upper[c] : (c)) # define SPELL_ISUPPER(c) ((c) < 256 ? spelltab.st_isu[c] : FALSE) #else # if defined(HAVE_WCHAR_H) # include <wchar.h> /* for towupper() and towlower() */ # endif /* Multi-byte implementation. For Unicode we can call utf_*(), but don't do * that for ASCII, because we don't want to use 'casemap' here. Otherwise use * the "w" library function for characters above 255 if available. */ # ifdef HAVE_TOWLOWER # define SPELL_TOFOLD(c) (enc_utf8 && (c) >= 128 ? utf_fold(c) \ : (c) < 256 ? (int)spelltab.st_fold[c] : (int)towlower(c)) # else # define SPELL_TOFOLD(c) (enc_utf8 && (c) >= 128 ? utf_fold(c) \ : (c) < 256 ? (int)spelltab.st_fold[c] : (c)) # endif # ifdef HAVE_TOWUPPER # define SPELL_TOUPPER(c) (enc_utf8 && (c) >= 128 ? utf_toupper(c) \ : (c) < 256 ? (int)spelltab.st_upper[c] : (int)towupper(c)) # else # define SPELL_TOUPPER(c) (enc_utf8 && (c) >= 128 ? utf_toupper(c) \ : (c) < 256 ? (int)spelltab.st_upper[c] : (c)) # endif # ifdef HAVE_ISWUPPER # define SPELL_ISUPPER(c) (enc_utf8 && (c) >= 128 ? utf_isupper(c) \ : (c) < 256 ? spelltab.st_isu[c] : iswupper(c)) # else # define SPELL_ISUPPER(c) (enc_utf8 && (c) >= 128 ? utf_isupper(c) \ : (c) < 256 ? spelltab.st_isu[c] : (FALSE)) # endif #endif static char *e_format = N_("E759: Format error in spell file"); static char *e_spell_trunc = N_("E758: Truncated spell file"); static char *e_afftrailing = N_("Trailing text in %s line %d: %s"); static char *e_affname = N_("Affix name too long in %s line %d: %s"); static char *e_affform = N_("E761: Format error in affix file FOL, LOW or UPP"); static char *e_affrange = N_("E762: Character in FOL, LOW or UPP is out of range"); static char *msg_compressing = N_("Compressing word tree..."); /* Remember what "z?" replaced. */ static char_u *repl_from = NULL; static char_u *repl_to = NULL; /* * Main spell-checking function. * "ptr" points to a character that could be the start of a word. * "*attrp" is set to the highlight index for a badly spelled word. For a * non-word or when it's OK it remains unchanged. * This must only be called when 'spelllang' is not empty. * * "capcol" is used to check for a Capitalised word after the end of a * sentence. If it's zero then perform the check. Return the column where to * check next, or -1 when no sentence end was found. If it's NULL then don't * worry. * * Returns the length of the word in bytes, also when it's OK, so that the * caller can skip over the word. */ int spell_check(wp, ptr, attrp, capcol, docount) win_T *wp; /* current window */ char_u *ptr; hlf_T *attrp; int *capcol; /* column to check for Capital */ int docount; /* count good words */ { matchinf_T mi; /* Most things are put in "mi" so that it can be passed to functions quickly. */ int nrlen = 0; /* found a number first */ int c; int wrongcaplen = 0; int lpi; int count_word = docount; /* A word never starts at a space or a control character. Return quickly * then, skipping over the character. */ if (*ptr <= ' ') return 1; /* Return here when loading language files failed. */ if (wp->w_s->b_langp.ga_len == 0) return 1; vim_memset(&mi, 0, sizeof(matchinf_T)); /* A number is always OK. Also skip hexadecimal numbers 0xFF99 and * 0X99FF. But always do check spelling to find "3GPP" and "11 * julifeest". */ if (*ptr >= '0' && *ptr <= '9') { if (*ptr == '0' && (ptr[1] == 'x' || ptr[1] == 'X')) mi.mi_end = skiphex(ptr + 2); else mi.mi_end = skipdigits(ptr); nrlen = (int)(mi.mi_end - ptr); } /* Find the normal end of the word (until the next non-word character). */ mi.mi_word = ptr; mi.mi_fend = ptr; if (spell_iswordp(mi.mi_fend, wp)) { do { mb_ptr_adv(mi.mi_fend); } while (*mi.mi_fend != NUL && spell_iswordp(mi.mi_fend, wp)); if (capcol != NULL && *capcol == 0 && wp->w_s->b_cap_prog != NULL) { /* Check word starting with capital letter. */ c = PTR2CHAR(ptr); if (!SPELL_ISUPPER(c)) wrongcaplen = (int)(mi.mi_fend - ptr); } } if (capcol != NULL) *capcol = -1; /* We always use the characters up to the next non-word character, * also for bad words. */ mi.mi_end = mi.mi_fend; /* Check caps type later. */ mi.mi_capflags = 0; mi.mi_cend = NULL; mi.mi_win = wp; /* case-fold the word with one non-word character, so that we can check * for the word end. */ if (*mi.mi_fend != NUL) mb_ptr_adv(mi.mi_fend); (void)spell_casefold(ptr, (int)(mi.mi_fend - ptr), mi.mi_fword, MAXWLEN + 1); mi.mi_fwordlen = (int)STRLEN(mi.mi_fword); /* The word is bad unless we recognize it. */ mi.mi_result = SP_BAD; mi.mi_result2 = SP_BAD; /* * Loop over the languages specified in 'spelllang'. * We check them all, because a word may be matched longer in another * language. */ for (lpi = 0; lpi < wp->w_s->b_langp.ga_len; ++lpi) { mi.mi_lp = LANGP_ENTRY(wp->w_s->b_langp, lpi); /* If reloading fails the language is still in the list but everything * has been cleared. */ if (mi.mi_lp->lp_slang->sl_fidxs == NULL) continue; /* Check for a matching word in case-folded words. */ find_word(&mi, FIND_FOLDWORD); /* Check for a matching word in keep-case words. */ find_word(&mi, FIND_KEEPWORD); /* Check for matching prefixes. */ find_prefix(&mi, FIND_FOLDWORD); /* For a NOBREAK language, may want to use a word without a following * word as a backup. */ if (mi.mi_lp->lp_slang->sl_nobreak && mi.mi_result == SP_BAD && mi.mi_result2 != SP_BAD) { mi.mi_result = mi.mi_result2; mi.mi_end = mi.mi_end2; } /* Count the word in the first language where it's found to be OK. */ if (count_word && mi.mi_result == SP_OK) { count_common_word(mi.mi_lp->lp_slang, ptr, (int)(mi.mi_end - ptr), 1); count_word = FALSE; } } if (mi.mi_result != SP_OK) { /* If we found a number skip over it. Allows for "42nd". Do flag * rare and local words, e.g., "3GPP". */ if (nrlen > 0) { if (mi.mi_result == SP_BAD || mi.mi_result == SP_BANNED) return nrlen; } /* When we are at a non-word character there is no error, just * skip over the character (try looking for a word after it). */ else if (!spell_iswordp_nmw(ptr)) { if (capcol != NULL && wp->w_s->b_cap_prog != NULL) { regmatch_T regmatch; /* Check for end of sentence. */ regmatch.regprog = wp->w_s->b_cap_prog; regmatch.rm_ic = FALSE; if (vim_regexec(&regmatch, ptr, 0)) *capcol = (int)(regmatch.endp[0] - ptr); } #ifdef FEAT_MBYTE if (has_mbyte) return (*mb_ptr2len)(ptr); #endif return 1; } else if (mi.mi_end == ptr) /* Always include at least one character. Required for when there * is a mixup in "midword". */ mb_ptr_adv(mi.mi_end); else if (mi.mi_result == SP_BAD && LANGP_ENTRY(wp->w_s->b_langp, 0)->lp_slang->sl_nobreak) { char_u *p, *fp; int save_result = mi.mi_result; /* First language in 'spelllang' is NOBREAK. Find first position * at which any word would be valid. */ mi.mi_lp = LANGP_ENTRY(wp->w_s->b_langp, 0); if (mi.mi_lp->lp_slang->sl_fidxs != NULL) { p = mi.mi_word; fp = mi.mi_fword; for (;;) { mb_ptr_adv(p); mb_ptr_adv(fp); if (p >= mi.mi_end) break; mi.mi_compoff = (int)(fp - mi.mi_fword); find_word(&mi, FIND_COMPOUND); if (mi.mi_result != SP_BAD) { mi.mi_end = p; break; } } mi.mi_result = save_result; } } if (mi.mi_result == SP_BAD || mi.mi_result == SP_BANNED) *attrp = HLF_SPB; else if (mi.mi_result == SP_RARE) *attrp = HLF_SPR; else *attrp = HLF_SPL; } if (wrongcaplen > 0 && (mi.mi_result == SP_OK || mi.mi_result == SP_RARE)) { /* Report SpellCap only when the word isn't badly spelled. */ *attrp = HLF_SPC; return wrongcaplen; } return (int)(mi.mi_end - ptr); } /* * Check if the word at "mip->mi_word" is in the tree. * When "mode" is FIND_FOLDWORD check in fold-case word tree. * When "mode" is FIND_KEEPWORD check in keep-case word tree. * When "mode" is FIND_PREFIX check for word after prefix in fold-case word * tree. * * For a match mip->mi_result is updated. */ static void find_word(mip, mode) matchinf_T *mip; int mode; { idx_T arridx = 0; int endlen[MAXWLEN]; /* length at possible word endings */ idx_T endidx[MAXWLEN]; /* possible word endings */ int endidxcnt = 0; int len; int wlen = 0; int flen; int c; char_u *ptr; idx_T lo, hi, m; #ifdef FEAT_MBYTE char_u *s; #endif char_u *p; int res = SP_BAD; slang_T *slang = mip->mi_lp->lp_slang; unsigned flags; char_u *byts; idx_T *idxs; int word_ends; int prefix_found; int nobreak_result; if (mode == FIND_KEEPWORD || mode == FIND_KEEPCOMPOUND) { /* Check for word with matching case in keep-case tree. */ ptr = mip->mi_word; flen = 9999; /* no case folding, always enough bytes */ byts = slang->sl_kbyts; idxs = slang->sl_kidxs; if (mode == FIND_KEEPCOMPOUND) /* Skip over the previously found word(s). */ wlen += mip->mi_compoff; } else { /* Check for case-folded in case-folded tree. */ ptr = mip->mi_fword; flen = mip->mi_fwordlen; /* available case-folded bytes */ byts = slang->sl_fbyts; idxs = slang->sl_fidxs; if (mode == FIND_PREFIX) { /* Skip over the prefix. */ wlen = mip->mi_prefixlen; flen -= mip->mi_prefixlen; } else if (mode == FIND_COMPOUND) { /* Skip over the previously found word(s). */ wlen = mip->mi_compoff; flen -= mip->mi_compoff; } } if (byts == NULL) return; /* array is empty */ /* * Repeat advancing in the tree until: * - there is a byte that doesn't match, * - we reach the end of the tree, * - or we reach the end of the line. */ for (;;) { if (flen <= 0 && *mip->mi_fend != NUL) flen = fold_more(mip); len = byts[arridx++]; /* If the first possible byte is a zero the word could end here. * Remember this index, we first check for the longest word. */ if (byts[arridx] == 0) { if (endidxcnt == MAXWLEN) { /* Must be a corrupted spell file. */ EMSG(_(e_format)); return; } endlen[endidxcnt] = wlen; endidx[endidxcnt++] = arridx++; --len; /* Skip over the zeros, there can be several flag/region * combinations. */ while (len > 0 && byts[arridx] == 0) { ++arridx; --len; } if (len == 0) break; /* no children, word must end here */ } /* Stop looking at end of the line. */ if (ptr[wlen] == NUL) break; /* Perform a binary search in the list of accepted bytes. */ c = ptr[wlen]; if (c == TAB) /* <Tab> is handled like <Space> */ c = ' '; lo = arridx; hi = arridx + len - 1; while (lo < hi) { m = (lo + hi) / 2; if (byts[m] > c) hi = m - 1; else if (byts[m] < c) lo = m + 1; else { lo = hi = m; break; } } /* Stop if there is no matching byte. */ if (hi < lo || byts[lo] != c) break; /* Continue at the child (if there is one). */ arridx = idxs[lo]; ++wlen; --flen; /* One space in the good word may stand for several spaces in the * checked word. */ if (c == ' ') { for (;;) { if (flen <= 0 && *mip->mi_fend != NUL) flen = fold_more(mip); if (ptr[wlen] != ' ' && ptr[wlen] != TAB) break; ++wlen; --flen; } } } /* * Verify that one of the possible endings is valid. Try the longest * first. */ while (endidxcnt > 0) { --endidxcnt; arridx = endidx[endidxcnt]; wlen = endlen[endidxcnt]; #ifdef FEAT_MBYTE if ((*mb_head_off)(ptr, ptr + wlen) > 0) continue; /* not at first byte of character */ #endif if (spell_iswordp(ptr + wlen, mip->mi_win)) { if (slang->sl_compprog == NULL && !slang->sl_nobreak) continue; /* next char is a word character */ word_ends = FALSE; } else word_ends = TRUE; /* The prefix flag is before compound flags. Once a valid prefix flag * has been found we try compound flags. */ prefix_found = FALSE; #ifdef FEAT_MBYTE if (mode != FIND_KEEPWORD && has_mbyte) { /* Compute byte length in original word, length may change * when folding case. This can be slow, take a shortcut when the * case-folded word is equal to the keep-case word. */ p = mip->mi_word; if (STRNCMP(ptr, p, wlen) != 0) { for (s = ptr; s < ptr + wlen; mb_ptr_adv(s)) mb_ptr_adv(p); wlen = (int)(p - mip->mi_word); } } #endif /* Check flags and region. For FIND_PREFIX check the condition and * prefix ID. * Repeat this if there are more flags/region alternatives until there * is a match. */ res = SP_BAD; for (len = byts[arridx - 1]; len > 0 && byts[arridx] == 0; --len, ++arridx) { flags = idxs[arridx]; /* For the fold-case tree check that the case of the checked word * matches with what the word in the tree requires. * For keep-case tree the case is always right. For prefixes we * don't bother to check. */ if (mode == FIND_FOLDWORD) { if (mip->mi_cend != mip->mi_word + wlen) { /* mi_capflags was set for a different word length, need * to do it again. */ mip->mi_cend = mip->mi_word + wlen; mip->mi_capflags = captype(mip->mi_word, mip->mi_cend); } if (mip->mi_capflags == WF_KEEPCAP || !spell_valid_case(mip->mi_capflags, flags)) continue; } /* When mode is FIND_PREFIX the word must support the prefix: * check the prefix ID and the condition. Do that for the list at * mip->mi_prefarridx that find_prefix() filled. */ else if (mode == FIND_PREFIX && !prefix_found) { c = valid_word_prefix(mip->mi_prefcnt, mip->mi_prefarridx, flags, mip->mi_word + mip->mi_cprefixlen, slang, FALSE); if (c == 0) continue; /* Use the WF_RARE flag for a rare prefix. */ if (c & WF_RAREPFX) flags |= WF_RARE; prefix_found = TRUE; } if (slang->sl_nobreak) { if ((mode == FIND_COMPOUND || mode == FIND_KEEPCOMPOUND) && (flags & WF_BANNED) == 0) { /* NOBREAK: found a valid following word. That's all we * need to know, so return. */ mip->mi_result = SP_OK; break; } } else if ((mode == FIND_COMPOUND || mode == FIND_KEEPCOMPOUND || !word_ends)) { /* If there is no compound flag or the word is shorter than * COMPOUNDMIN reject it quickly. * Makes you wonder why someone puts a compound flag on a word * that's too short... Myspell compatibility requires this * anyway. */ if (((unsigned)flags >> 24) == 0 || wlen - mip->mi_compoff < slang->sl_compminlen) continue; #ifdef FEAT_MBYTE /* For multi-byte chars check character length against * COMPOUNDMIN. */ if (has_mbyte && slang->sl_compminlen > 0 && mb_charlen_len(mip->mi_word + mip->mi_compoff, wlen - mip->mi_compoff) < slang->sl_compminlen) continue; #endif /* Limit the number of compound words to COMPOUNDWORDMAX if no * maximum for syllables is specified. */ if (!word_ends && mip->mi_complen + mip->mi_compextra + 2 > slang->sl_compmax && slang->sl_compsylmax == MAXWLEN) continue; /* Don't allow compounding on a side where an affix was added, * unless COMPOUNDPERMITFLAG was used. */ if (mip->mi_complen > 0 && (flags & WF_NOCOMPBEF)) continue; if (!word_ends && (flags & WF_NOCOMPAFT)) continue; /* Quickly check if compounding is possible with this flag. */ if (!byte_in_str(mip->mi_complen == 0 ? slang->sl_compstartflags : slang->sl_compallflags, ((unsigned)flags >> 24))) continue; /* If there is a match with a CHECKCOMPOUNDPATTERN rule * discard the compound word. */ if (match_checkcompoundpattern(ptr, wlen, &slang->sl_comppat)) continue; if (mode == FIND_COMPOUND) { int capflags; /* Need to check the caps type of the appended compound * word. */ #ifdef FEAT_MBYTE if (has_mbyte && STRNCMP(ptr, mip->mi_word, mip->mi_compoff) != 0) { /* case folding may have changed the length */ p = mip->mi_word; for (s = ptr; s < ptr + mip->mi_compoff; mb_ptr_adv(s)) mb_ptr_adv(p); } else #endif p = mip->mi_word + mip->mi_compoff; capflags = captype(p, mip->mi_word + wlen); if (capflags == WF_KEEPCAP || (capflags == WF_ALLCAP && (flags & WF_FIXCAP) != 0)) continue; if (capflags != WF_ALLCAP) { /* When the character before the word is a word * character we do not accept a Onecap word. We do * accept a no-caps word, even when the dictionary * word specifies ONECAP. */ mb_ptr_back(mip->mi_word, p); if (spell_iswordp_nmw(p) ? capflags == WF_ONECAP : (flags & WF_ONECAP) != 0 && capflags != WF_ONECAP) continue; } } /* If the word ends the sequence of compound flags of the * words must match with one of the COMPOUNDRULE items and * the number of syllables must not be too large. */ mip->mi_compflags[mip->mi_complen] = ((unsigned)flags >> 24); mip->mi_compflags[mip->mi_complen + 1] = NUL; if (word_ends) { char_u fword[MAXWLEN]; if (slang->sl_compsylmax < MAXWLEN) { /* "fword" is only needed for checking syllables. */ if (ptr == mip->mi_word) (void)spell_casefold(ptr, wlen, fword, MAXWLEN); else vim_strncpy(fword, ptr, endlen[endidxcnt]); } if (!can_compound(slang, fword, mip->mi_compflags)) continue; } else if (slang->sl_comprules != NULL && !match_compoundrule(slang, mip->mi_compflags)) /* The compound flags collected so far do not match any * COMPOUNDRULE, discard the compounded word. */ continue; } /* Check NEEDCOMPOUND: can't use word without compounding. */ else if (flags & WF_NEEDCOMP) continue; nobreak_result = SP_OK; if (!word_ends) { int save_result = mip->mi_result; char_u *save_end = mip->mi_end; langp_T *save_lp = mip->mi_lp; int lpi; /* Check that a valid word follows. If there is one and we * are compounding, it will set "mi_result", thus we are * always finished here. For NOBREAK we only check that a * valid word follows. * Recursive! */ if (slang->sl_nobreak) mip->mi_result = SP_BAD; /* Find following word in case-folded tree. */ mip->mi_compoff = endlen[endidxcnt]; #ifdef FEAT_MBYTE if (has_mbyte && mode == FIND_KEEPWORD) { /* Compute byte length in case-folded word from "wlen": * byte length in keep-case word. Length may change when * folding case. This can be slow, take a shortcut when * the case-folded word is equal to the keep-case word. */ p = mip->mi_fword; if (STRNCMP(ptr, p, wlen) != 0) { for (s = ptr; s < ptr + wlen; mb_ptr_adv(s)) mb_ptr_adv(p); mip->mi_compoff = (int)(p - mip->mi_fword); } } #endif c = mip->mi_compoff; ++mip->mi_complen; if (flags & WF_COMPROOT) ++mip->mi_compextra; /* For NOBREAK we need to try all NOBREAK languages, at least * to find the ".add" file(s). */ for (lpi = 0; lpi < mip->mi_win->w_s->b_langp.ga_len; ++lpi) { if (slang->sl_nobreak) { mip->mi_lp = LANGP_ENTRY(mip->mi_win->w_s->b_langp, lpi); if (mip->mi_lp->lp_slang->sl_fidxs == NULL || !mip->mi_lp->lp_slang->sl_nobreak) continue; } find_word(mip, FIND_COMPOUND); /* When NOBREAK any word that matches is OK. Otherwise we * need to find the longest match, thus try with keep-case * and prefix too. */ if (!slang->sl_nobreak || mip->mi_result == SP_BAD) { /* Find following word in keep-case tree. */ mip->mi_compoff = wlen; find_word(mip, FIND_KEEPCOMPOUND); #if 0 /* Disabled, a prefix must not appear halfway a compound word, unless the COMPOUNDPERMITFLAG is used and then it can't be a postponed prefix. */ if (!slang->sl_nobreak || mip->mi_result == SP_BAD) { /* Check for following word with prefix. */ mip->mi_compoff = c; find_prefix(mip, FIND_COMPOUND); } #endif } if (!slang->sl_nobreak) break; } --mip->mi_complen; if (flags & WF_COMPROOT) --mip->mi_compextra; mip->mi_lp = save_lp; if (slang->sl_nobreak) { nobreak_result = mip->mi_result; mip->mi_result = save_result; mip->mi_end = save_end; } else { if (mip->mi_result == SP_OK) break; continue; } } if (flags & WF_BANNED) res = SP_BANNED; else if (flags & WF_REGION) { /* Check region. */ if ((mip->mi_lp->lp_region & (flags >> 16)) != 0) res = SP_OK; else res = SP_LOCAL; } else if (flags & WF_RARE) res = SP_RARE; else res = SP_OK; /* Always use the longest match and the best result. For NOBREAK * we separately keep the longest match without a following good * word as a fall-back. */ if (nobreak_result == SP_BAD) { if (mip->mi_result2 > res) { mip->mi_result2 = res; mip->mi_end2 = mip->mi_word + wlen; } else if (mip->mi_result2 == res && mip->mi_end2 < mip->mi_word + wlen) mip->mi_end2 = mip->mi_word + wlen; } else if (mip->mi_result > res) { mip->mi_result = res; mip->mi_end = mip->mi_word + wlen; } else if (mip->mi_result == res && mip->mi_end < mip->mi_word + wlen) mip->mi_end = mip->mi_word + wlen; if (mip->mi_result == SP_OK) break; } if (mip->mi_result == SP_OK) break; } } /* * Return TRUE if there is a match between the word ptr[wlen] and * CHECKCOMPOUNDPATTERN rules, assuming that we will concatenate with another * word. * A match means that the first part of CHECKCOMPOUNDPATTERN matches at the * end of ptr[wlen] and the second part matches after it. */ static int match_checkcompoundpattern(ptr, wlen, gap) char_u *ptr; int wlen; garray_T *gap; /* &sl_comppat */ { int i; char_u *p; int len; for (i = 0; i + 1 < gap->ga_len; i += 2) { p = ((char_u **)gap->ga_data)[i + 1]; if (STRNCMP(ptr + wlen, p, STRLEN(p)) == 0) { /* Second part matches at start of following compound word, now * check if first part matches at end of previous word. */ p = ((char_u **)gap->ga_data)[i]; len = (int)STRLEN(p); if (len <= wlen && STRNCMP(ptr + wlen - len, p, len) == 0) return TRUE; } } return FALSE; } /* * Return TRUE if "flags" is a valid sequence of compound flags and "word" * does not have too many syllables. */ static int can_compound(slang, word, flags) slang_T *slang; char_u *word; char_u *flags; { regmatch_T regmatch; #ifdef FEAT_MBYTE char_u uflags[MAXWLEN * 2]; int i; #endif char_u *p; if (slang->sl_compprog == NULL) return FALSE; #ifdef FEAT_MBYTE if (enc_utf8) { /* Need to convert the single byte flags to utf8 characters. */ p = uflags; for (i = 0; flags[i] != NUL; ++i) p += mb_char2bytes(flags[i], p); *p = NUL; p = uflags; } else #endif p = flags; regmatch.regprog = slang->sl_compprog; regmatch.rm_ic = FALSE; if (!vim_regexec(&regmatch, p, 0)) return FALSE; /* Count the number of syllables. This may be slow, do it last. If there * are too many syllables AND the number of compound words is above * COMPOUNDWORDMAX then compounding is not allowed. */ if (slang->sl_compsylmax < MAXWLEN && count_syllables(slang, word) > slang->sl_compsylmax) return (int)STRLEN(flags) < slang->sl_compmax; return TRUE; } /* * Return TRUE when the sequence of flags in "compflags" plus "flag" can * possibly form a valid compounded word. This also checks the COMPOUNDRULE * lines if they don't contain wildcards. */ static int can_be_compound(sp, slang, compflags, flag) trystate_T *sp; slang_T *slang; char_u *compflags; int flag; { /* If the flag doesn't appear in sl_compstartflags or sl_compallflags * then it can't possibly compound. */ if (!byte_in_str(sp->ts_complen == sp->ts_compsplit ? slang->sl_compstartflags : slang->sl_compallflags, flag)) return FALSE; /* If there are no wildcards, we can check if the flags collected so far * possibly can form a match with COMPOUNDRULE patterns. This only * makes sense when we have two or more words. */ if (slang->sl_comprules != NULL && sp->ts_complen > sp->ts_compsplit) { int v; compflags[sp->ts_complen] = flag; compflags[sp->ts_complen + 1] = NUL; v = match_compoundrule(slang, compflags + sp->ts_compsplit); compflags[sp->ts_complen] = NUL; return v; } return TRUE; } /* * Return TRUE if the compound flags in compflags[] match the start of any * compound rule. This is used to stop trying a compound if the flags * collected so far can't possibly match any compound rule. * Caller must check that slang->sl_comprules is not NULL. */ static int match_compoundrule(slang, compflags) slang_T *slang; char_u *compflags; { char_u *p; int i; int c; /* loop over all the COMPOUNDRULE entries */ for (p = slang->sl_comprules; *p != NUL; ++p) { /* loop over the flags in the compound word we have made, match * them against the current rule entry */ for (i = 0; ; ++i) { c = compflags[i]; if (c == NUL) /* found a rule that matches for the flags we have so far */ return TRUE; if (*p == '/' || *p == NUL) break; /* end of rule, it's too short */ if (*p == '[') { int match = FALSE; /* compare against all the flags in [] */ ++p; while (*p != ']' && *p != NUL) if (*p++ == c) match = TRUE; if (!match) break; /* none matches */ } else if (*p != c) break; /* flag of word doesn't match flag in pattern */ ++p; } /* Skip to the next "/", where the next pattern starts. */ p = vim_strchr(p, '/'); if (p == NULL) break; } /* Checked all the rules and none of them match the flags, so there * can't possibly be a compound starting with these flags. */ return FALSE; } /* * Return non-zero if the prefix indicated by "arridx" matches with the prefix * ID in "flags" for the word "word". * The WF_RAREPFX flag is included in the return value for a rare prefix. */ static int valid_word_prefix(totprefcnt, arridx, flags, word, slang, cond_req) int totprefcnt; /* nr of prefix IDs */ int arridx; /* idx in sl_pidxs[] */ int flags; char_u *word; slang_T *slang; int cond_req; /* only use prefixes with a condition */ { int prefcnt; int pidx; regprog_T *rp; regmatch_T regmatch; int prefid; prefid = (unsigned)flags >> 24; for (prefcnt = totprefcnt - 1; prefcnt >= 0; --prefcnt) { pidx = slang->sl_pidxs[arridx + prefcnt]; /* Check the prefix ID. */ if (prefid != (pidx & 0xff)) continue; /* Check if the prefix doesn't combine and the word already has a * suffix. */ if ((flags & WF_HAS_AFF) && (pidx & WF_PFX_NC)) continue; /* Check the condition, if there is one. The condition index is * stored in the two bytes above the prefix ID byte. */ rp = slang->sl_prefprog[((unsigned)pidx >> 8) & 0xffff]; if (rp != NULL) { regmatch.regprog = rp; regmatch.rm_ic = FALSE; if (!vim_regexec(&regmatch, word, 0)) continue; } else if (cond_req) continue; /* It's a match! Return the WF_ flags. */ return pidx; } return 0; } /* * Check if the word at "mip->mi_word" has a matching prefix. * If it does, then check the following word. * * If "mode" is "FIND_COMPOUND" then do the same after another word, find a * prefix in a compound word. * * For a match mip->mi_result is updated. */ static void find_prefix(mip, mode) matchinf_T *mip; int mode; { idx_T arridx = 0; int len; int wlen = 0; int flen; int c; char_u *ptr; idx_T lo, hi, m; slang_T *slang = mip->mi_lp->lp_slang; char_u *byts; idx_T *idxs; byts = slang->sl_pbyts; if (byts == NULL) return; /* array is empty */ /* We use the case-folded word here, since prefixes are always * case-folded. */ ptr = mip->mi_fword; flen = mip->mi_fwordlen; /* available case-folded bytes */ if (mode == FIND_COMPOUND) { /* Skip over the previously found word(s). */ ptr += mip->mi_compoff; flen -= mip->mi_compoff; } idxs = slang->sl_pidxs; /* * Repeat advancing in the tree until: * - there is a byte that doesn't match, * - we reach the end of the tree, * - or we reach the end of the line. */ for (;;) { if (flen == 0 && *mip->mi_fend != NUL) flen = fold_more(mip); len = byts[arridx++]; /* If the first possible byte is a zero the prefix could end here. * Check if the following word matches and supports the prefix. */ if (byts[arridx] == 0) { /* There can be several prefixes with different conditions. We * try them all, since we don't know which one will give the * longest match. The word is the same each time, pass the list * of possible prefixes to find_word(). */ mip->mi_prefarridx = arridx; mip->mi_prefcnt = len; while (len > 0 && byts[arridx] == 0) { ++arridx; --len; } mip->mi_prefcnt -= len; /* Find the word that comes after the prefix. */ mip->mi_prefixlen = wlen; if (mode == FIND_COMPOUND) /* Skip over the previously found word(s). */ mip->mi_prefixlen += mip->mi_compoff; #ifdef FEAT_MBYTE if (has_mbyte) { /* Case-folded length may differ from original length. */ mip->mi_cprefixlen = nofold_len(mip->mi_fword, mip->mi_prefixlen, mip->mi_word); } else mip->mi_cprefixlen = mip->mi_prefixlen; #endif find_word(mip, FIND_PREFIX); if (len == 0) break; /* no children, word must end here */ } /* Stop looking at end of the line. */ if (ptr[wlen] == NUL) break; /* Perform a binary search in the list of accepted bytes. */ c = ptr[wlen]; lo = arridx; hi = arridx + len - 1; while (lo < hi) { m = (lo + hi) / 2; if (byts[m] > c) hi = m - 1; else if (byts[m] < c) lo = m + 1; else { lo = hi = m; break; } } /* Stop if there is no matching byte. */ if (hi < lo || byts[lo] != c) break; /* Continue at the child (if there is one). */ arridx = idxs[lo]; ++wlen; --flen; } } /* * Need to fold at least one more character. Do until next non-word character * for efficiency. Include the non-word character too. * Return the length of the folded chars in bytes. */ static int fold_more(mip) matchinf_T *mip; { int flen; char_u *p; p = mip->mi_fend; do { mb_ptr_adv(mip->mi_fend); } while (*mip->mi_fend != NUL && spell_iswordp(mip->mi_fend, mip->mi_win)); /* Include the non-word character so that we can check for the word end. */ if (*mip->mi_fend != NUL) mb_ptr_adv(mip->mi_fend); (void)spell_casefold(p, (int)(mip->mi_fend - p), mip->mi_fword + mip->mi_fwordlen, MAXWLEN - mip->mi_fwordlen); flen = (int)STRLEN(mip->mi_fword + mip->mi_fwordlen); mip->mi_fwordlen += flen; return flen; } /* * Check case flags for a word. Return TRUE if the word has the requested * case. */ static int spell_valid_case(wordflags, treeflags) int wordflags; /* flags for the checked word. */ int treeflags; /* flags for the word in the spell tree */ { return ((wordflags == WF_ALLCAP && (treeflags & WF_FIXCAP) == 0) || ((treeflags & (WF_ALLCAP | WF_KEEPCAP)) == 0 && ((treeflags & WF_ONECAP) == 0 || (wordflags & WF_ONECAP) != 0))); } /* * Return TRUE if spell checking is not enabled. */ static int no_spell_checking(wp) win_T *wp; { if (!wp->w_p_spell || *wp->w_s->b_p_spl == NUL || wp->w_s->b_langp.ga_len == 0) { EMSG(_("E756: Spell checking is not enabled")); return TRUE; } return FALSE; } /* * Move to next spell error. * "curline" is FALSE for "[s", "]s", "[S" and "]S". * "curline" is TRUE to find word under/after cursor in the same line. * For Insert mode completion "dir" is BACKWARD and "curline" is TRUE: move * to after badly spelled word before the cursor. * Return 0 if not found, length of the badly spelled word otherwise. */ int spell_move_to(wp, dir, allwords, curline, attrp) win_T *wp; int dir; /* FORWARD or BACKWARD */ int allwords; /* TRUE for "[s"/"]s", FALSE for "[S"/"]S" */ int curline; hlf_T *attrp; /* return: attributes of bad word or NULL (only when "dir" is FORWARD) */ { linenr_T lnum; pos_T found_pos; int found_len = 0; char_u *line; char_u *p; char_u *endp; hlf_T attr; int len; # ifdef FEAT_SYN_HL int has_syntax = syntax_present(wp); # endif int col; int can_spell; char_u *buf = NULL; int buflen = 0; int skip = 0; int capcol = -1; int found_one = FALSE; int wrapped = FALSE; if (no_spell_checking(wp)) return 0; /* * Start looking for bad word at the start of the line, because we can't * start halfway a word, we don't know where it starts or ends. * * When searching backwards, we continue in the line to find the last * bad word (in the cursor line: before the cursor). * * We concatenate the start of the next line, so that wrapped words work * (e.g. "et<line-break>cetera"). Doesn't work when searching backwards * though... */ lnum = wp->w_cursor.lnum; clearpos(&found_pos); while (!got_int) { line = ml_get_buf(wp->w_buffer, lnum, FALSE); len = (int)STRLEN(line); if (buflen < len + MAXWLEN + 2) { vim_free(buf); buflen = len + MAXWLEN + 2; buf = alloc(buflen); if (buf == NULL) break; } /* In first line check first word for Capital. */ if (lnum == 1) capcol = 0; /* For checking first word with a capital skip white space. */ if (capcol == 0) capcol = (int)(skipwhite(line) - line); else if (curline && wp == curwin) { /* For spellbadword(): check if first word needs a capital. */ col = (int)(skipwhite(line) - line); if (check_need_cap(lnum, col)) capcol = col; /* Need to get the line again, may have looked at the previous * one. */ line = ml_get_buf(wp->w_buffer, lnum, FALSE); } /* Copy the line into "buf" and append the start of the next line if * possible. */ STRCPY(buf, line); if (lnum < wp->w_buffer->b_ml.ml_line_count) spell_cat_line(buf + STRLEN(buf), ml_get_buf(wp->w_buffer, lnum + 1, FALSE), MAXWLEN); p = buf + skip; endp = buf + len; while (p < endp) { /* When searching backward don't search after the cursor. Unless * we wrapped around the end of the buffer. */ if (dir == BACKWARD && lnum == wp->w_cursor.lnum && !wrapped && (colnr_T)(p - buf) >= wp->w_cursor.col) break; /* start of word */ attr = HLF_COUNT; len = spell_check(wp, p, &attr, &capcol, FALSE); if (attr != HLF_COUNT) { /* We found a bad word. Check the attribute. */ if (allwords || attr == HLF_SPB) { /* When searching forward only accept a bad word after * the cursor. */ if (dir == BACKWARD || lnum != wp->w_cursor.lnum || (lnum == wp->w_cursor.lnum && (wrapped || (colnr_T)(curline ? p - buf + len : p - buf) > wp->w_cursor.col))) { # ifdef FEAT_SYN_HL if (has_syntax) { col = (int)(p - buf); (void)syn_get_id(wp, lnum, (colnr_T)col, FALSE, &can_spell, FALSE); if (!can_spell) attr = HLF_COUNT; } else #endif can_spell = TRUE; if (can_spell) { found_one = TRUE; found_pos.lnum = lnum; found_pos.col = (int)(p - buf); #ifdef FEAT_VIRTUALEDIT found_pos.coladd = 0; #endif if (dir == FORWARD) { /* No need to search further. */ wp->w_cursor = found_pos; vim_free(buf); if (attrp != NULL) *attrp = attr; return len; } else if (curline) /* Insert mode completion: put cursor after * the bad word. */ found_pos.col += len; found_len = len; } } else found_one = TRUE; } } /* advance to character after the word */ p += len; capcol -= len; } if (dir == BACKWARD && found_pos.lnum != 0) { /* Use the last match in the line (before the cursor). */ wp->w_cursor = found_pos; vim_free(buf); return found_len; } if (curline) break; /* only check cursor line */ /* Advance to next line. */ if (dir == BACKWARD) { /* If we are back at the starting line and searched it again there * is no match, give up. */ if (lnum == wp->w_cursor.lnum && wrapped) break; if (lnum > 1) --lnum; else if (!p_ws) break; /* at first line and 'nowrapscan' */ else { /* Wrap around to the end of the buffer. May search the * starting line again and accept the last match. */ lnum = wp->w_buffer->b_ml.ml_line_count; wrapped = TRUE; if (!shortmess(SHM_SEARCH)) give_warning((char_u *)_(top_bot_msg), TRUE); } capcol = -1; } else { if (lnum < wp->w_buffer->b_ml.ml_line_count) ++lnum; else if (!p_ws) break; /* at first line and 'nowrapscan' */ else { /* Wrap around to the start of the buffer. May search the * starting line again and accept the first match. */ lnum = 1; wrapped = TRUE; if (!shortmess(SHM_SEARCH)) give_warning((char_u *)_(bot_top_msg), TRUE); } /* If we are back at the starting line and there is no match then * give up. */ if (lnum == wp->w_cursor.lnum && (!found_one || wrapped)) break; /* Skip the characters at the start of the next line that were * included in a match crossing line boundaries. */ if (attr == HLF_COUNT) skip = (int)(p - endp); else skip = 0; /* Capcol skips over the inserted space. */ --capcol; /* But after empty line check first word in next line */ if (*skipwhite(line) == NUL) capcol = 0; } line_breakcheck(); } vim_free(buf); return 0; } /* * For spell checking: concatenate the start of the following line "line" into * "buf", blanking-out special characters. Copy less then "maxlen" bytes. * Keep the blanks at the start of the next line, this is used in win_line() * to skip those bytes if the word was OK. */ void spell_cat_line(buf, line, maxlen) char_u *buf; char_u *line; int maxlen; { char_u *p; int n; p = skipwhite(line); while (vim_strchr((char_u *)"*#/\"\t", *p) != NULL) p = skipwhite(p + 1); if (*p != NUL) { /* Only worth concatenating if there is something else than spaces to * concatenate. */ n = (int)(p - line) + 1; if (n < maxlen - 1) { vim_memset(buf, ' ', n); vim_strncpy(buf + n, p, maxlen - 1 - n); } } } /* * Structure used for the cookie argument of do_in_runtimepath(). */ typedef struct spelload_S { char_u sl_lang[MAXWLEN + 1]; /* language name */ slang_T *sl_slang; /* resulting slang_T struct */ int sl_nobreak; /* NOBREAK language found */ } spelload_T; /* * Load word list(s) for "lang" from Vim spell file(s). * "lang" must be the language without the region: e.g., "en". */ static void spell_load_lang(lang) char_u *lang; { char_u fname_enc[85]; int r; spelload_T sl; #ifdef FEAT_AUTOCMD int round; #endif /* Copy the language name to pass it to spell_load_cb() as a cookie. * It's truncated when an error is detected. */ STRCPY(sl.sl_lang, lang); sl.sl_slang = NULL; sl.sl_nobreak = FALSE; #ifdef FEAT_AUTOCMD /* We may retry when no spell file is found for the language, an * autocommand may load it then. */ for (round = 1; round <= 2; ++round) #endif { /* * Find the first spell file for "lang" in 'runtimepath' and load it. */ vim_snprintf((char *)fname_enc, sizeof(fname_enc) - 5, #ifdef VMS "spell/%s_%s.spl", #else "spell/%s.%s.spl", #endif lang, spell_enc()); r = do_in_runtimepath(fname_enc, FALSE, spell_load_cb, &sl); if (r == FAIL && *sl.sl_lang != NUL) { /* Try loading the ASCII version. */ vim_snprintf((char *)fname_enc, sizeof(fname_enc) - 5, #ifdef VMS "spell/%s_ascii.spl", #else "spell/%s.ascii.spl", #endif lang); r = do_in_runtimepath(fname_enc, FALSE, spell_load_cb, &sl); #ifdef FEAT_AUTOCMD if (r == FAIL && *sl.sl_lang != NUL && round == 1 && apply_autocmds(EVENT_SPELLFILEMISSING, lang, curbuf->b_fname, FALSE, curbuf)) continue; break; #endif } #ifdef FEAT_AUTOCMD break; #endif } if (r == FAIL) { smsg((char_u *) #ifdef VMS _("Warning: Cannot find word list \"%s_%s.spl\" or \"%s_ascii.spl\""), #else _("Warning: Cannot find word list \"%s.%s.spl\" or \"%s.ascii.spl\""), #endif lang, spell_enc(), lang); } else if (sl.sl_slang != NULL) { /* At least one file was loaded, now load ALL the additions. */ STRCPY(fname_enc + STRLEN(fname_enc) - 3, "add.spl"); do_in_runtimepath(fname_enc, TRUE, spell_load_cb, &sl); } } /* * Return the encoding used for spell checking: Use 'encoding', except that we * use "latin1" for "latin9". And limit to 60 characters (just in case). */ static char_u * spell_enc() { #ifdef FEAT_MBYTE if (STRLEN(p_enc) < 60 && STRCMP(p_enc, "iso-8859-15") != 0) return p_enc; #endif return (char_u *)"latin1"; } /* * Get the name of the .spl file for the internal wordlist into * "fname[MAXPATHL]". */ static void int_wordlist_spl(fname) char_u *fname; { vim_snprintf((char *)fname, MAXPATHL, SPL_FNAME_TMPL, int_wordlist, spell_enc()); } /* * Allocate a new slang_T for language "lang". "lang" can be NULL. * Caller must fill "sl_next". */ static slang_T * slang_alloc(lang) char_u *lang; { slang_T *lp; lp = (slang_T *)alloc_clear(sizeof(slang_T)); if (lp != NULL) { if (lang != NULL) lp->sl_name = vim_strsave(lang); ga_init2(&lp->sl_rep, sizeof(fromto_T), 10); ga_init2(&lp->sl_repsal, sizeof(fromto_T), 10); lp->sl_compmax = MAXWLEN; lp->sl_compsylmax = MAXWLEN; hash_init(&lp->sl_wordcount); } return lp; } /* * Free the contents of an slang_T and the structure itself. */ static void slang_free(lp) slang_T *lp; { vim_free(lp->sl_name); vim_free(lp->sl_fname); slang_clear(lp); vim_free(lp); } /* * Clear an slang_T so that the file can be reloaded. */ static void slang_clear(lp) slang_T *lp; { garray_T *gap; fromto_T *ftp; salitem_T *smp; int i; int round; vim_free(lp->sl_fbyts); lp->sl_fbyts = NULL; vim_free(lp->sl_kbyts); lp->sl_kbyts = NULL; vim_free(lp->sl_pbyts); lp->sl_pbyts = NULL; vim_free(lp->sl_fidxs); lp->sl_fidxs = NULL; vim_free(lp->sl_kidxs); lp->sl_kidxs = NULL; vim_free(lp->sl_pidxs); lp->sl_pidxs = NULL; for (round = 1; round <= 2; ++round) { gap = round == 1 ? &lp->sl_rep : &lp->sl_repsal; while (gap->ga_len > 0) { ftp = &((fromto_T *)gap->ga_data)[--gap->ga_len]; vim_free(ftp->ft_from); vim_free(ftp->ft_to); } ga_clear(gap); } gap = &lp->sl_sal; if (lp->sl_sofo) { /* "ga_len" is set to 1 without adding an item for latin1 */ if (gap->ga_data != NULL) /* SOFOFROM and SOFOTO items: free lists of wide characters. */ for (i = 0; i < gap->ga_len; ++i) vim_free(((int **)gap->ga_data)[i]); } else /* SAL items: free salitem_T items */ while (gap->ga_len > 0) { smp = &((salitem_T *)gap->ga_data)[--gap->ga_len]; vim_free(smp->sm_lead); /* Don't free sm_oneof and sm_rules, they point into sm_lead. */ vim_free(smp->sm_to); #ifdef FEAT_MBYTE vim_free(smp->sm_lead_w); vim_free(smp->sm_oneof_w); vim_free(smp->sm_to_w); #endif } ga_clear(gap); for (i = 0; i < lp->sl_prefixcnt; ++i) vim_free(lp->sl_prefprog[i]); lp->sl_prefixcnt = 0; vim_free(lp->sl_prefprog); lp->sl_prefprog = NULL; vim_free(lp->sl_info); lp->sl_info = NULL; vim_free(lp->sl_midword); lp->sl_midword = NULL; vim_free(lp->sl_compprog); vim_free(lp->sl_comprules); vim_free(lp->sl_compstartflags); vim_free(lp->sl_compallflags); lp->sl_compprog = NULL; lp->sl_comprules = NULL; lp->sl_compstartflags = NULL; lp->sl_compallflags = NULL; vim_free(lp->sl_syllable); lp->sl_syllable = NULL; ga_clear(&lp->sl_syl_items); ga_clear_strings(&lp->sl_comppat); hash_clear_all(&lp->sl_wordcount, WC_KEY_OFF); hash_init(&lp->sl_wordcount); #ifdef FEAT_MBYTE hash_clear_all(&lp->sl_map_hash, 0); #endif /* Clear info from .sug file. */ slang_clear_sug(lp); lp->sl_compmax = MAXWLEN; lp->sl_compminlen = 0; lp->sl_compsylmax = MAXWLEN; lp->sl_regions[0] = NUL; } /* * Clear the info from the .sug file in "lp". */ static void slang_clear_sug(lp) slang_T *lp; { vim_free(lp->sl_sbyts); lp->sl_sbyts = NULL; vim_free(lp->sl_sidxs); lp->sl_sidxs = NULL; close_spellbuf(lp->sl_sugbuf); lp->sl_sugbuf = NULL; lp->sl_sugloaded = FALSE; lp->sl_sugtime = 0; } /* * Load one spell file and store the info into a slang_T. * Invoked through do_in_runtimepath(). */ static void spell_load_cb(fname, cookie) char_u *fname; void *cookie; { spelload_T *slp = (spelload_T *)cookie; slang_T *slang; slang = spell_load_file(fname, slp->sl_lang, NULL, FALSE); if (slang != NULL) { /* When a previously loaded file has NOBREAK also use it for the * ".add" files. */ if (slp->sl_nobreak && slang->sl_add) slang->sl_nobreak = TRUE; else if (slang->sl_nobreak) slp->sl_nobreak = TRUE; slp->sl_slang = slang; } } /* * Load one spell file and store the info into a slang_T. * * This is invoked in three ways: * - From spell_load_cb() to load a spell file for the first time. "lang" is * the language name, "old_lp" is NULL. Will allocate an slang_T. * - To reload a spell file that was changed. "lang" is NULL and "old_lp" * points to the existing slang_T. * - Just after writing a .spl file; it's read back to produce the .sug file. * "old_lp" is NULL and "lang" is NULL. Will allocate an slang_T. * * Returns the slang_T the spell file was loaded into. NULL for error. */ static slang_T * spell_load_file(fname, lang, old_lp, silent) char_u *fname; char_u *lang; slang_T *old_lp; int silent; /* no error if file doesn't exist */ { FILE *fd; char_u buf[VIMSPELLMAGICL]; char_u *p; int i; int n; int len; char_u *save_sourcing_name = sourcing_name; linenr_T save_sourcing_lnum = sourcing_lnum; slang_T *lp = NULL; int c = 0; int res; fd = mch_fopen((char *)fname, "r"); if (fd == NULL) { if (!silent) EMSG2(_(e_notopen), fname); else if (p_verbose > 2) { verbose_enter(); smsg((char_u *)e_notopen, fname); verbose_leave(); } goto endFAIL; } if (p_verbose > 2) { verbose_enter(); smsg((char_u *)_("Reading spell file \"%s\""), fname); verbose_leave(); } if (old_lp == NULL) { lp = slang_alloc(lang); if (lp == NULL) goto endFAIL; /* Remember the file name, used to reload the file when it's updated. */ lp->sl_fname = vim_strsave(fname); if (lp->sl_fname == NULL) goto endFAIL; /* Check for .add.spl (_add.spl for VMS). */ lp->sl_add = strstr((char *)gettail(fname), SPL_FNAME_ADD) != NULL; } else lp = old_lp; /* Set sourcing_name, so that error messages mention the file name. */ sourcing_name = fname; sourcing_lnum = 0; /* * <HEADER>: <fileID> */ for (i = 0; i < VIMSPELLMAGICL; ++i) buf[i] = getc(fd); /* <fileID> */ if (STRNCMP(buf, VIMSPELLMAGIC, VIMSPELLMAGICL) != 0) { EMSG(_("E757: This does not look like a spell file")); goto endFAIL; } c = getc(fd); /* <versionnr> */ if (c < VIMSPELLVERSION) { EMSG(_("E771: Old spell file, needs to be updated")); goto endFAIL; } else if (c > VIMSPELLVERSION) { EMSG(_("E772: Spell file is for newer version of Vim")); goto endFAIL; } /* * <SECTIONS>: <section> ... <sectionend> * <section>: <sectionID> <sectionflags> <sectionlen> (section contents) */ for (;;) { n = getc(fd); /* <sectionID> or <sectionend> */ if (n == SN_END) break; c = getc(fd); /* <sectionflags> */ len = get4c(fd); /* <sectionlen> */ if (len < 0) goto truncerr; res = 0; switch (n) { case SN_INFO: lp->sl_info = read_string(fd, len); /* <infotext> */ if (lp->sl_info == NULL) goto endFAIL; break; case SN_REGION: res = read_region_section(fd, lp, len); break; case SN_CHARFLAGS: res = read_charflags_section(fd); break; case SN_MIDWORD: lp->sl_midword = read_string(fd, len); /* <midword> */ if (lp->sl_midword == NULL) goto endFAIL; break; case SN_PREFCOND: res = read_prefcond_section(fd, lp); break; case SN_REP: res = read_rep_section(fd, &lp->sl_rep, lp->sl_rep_first); break; case SN_REPSAL: res = read_rep_section(fd, &lp->sl_repsal, lp->sl_repsal_first); break; case SN_SAL: res = read_sal_section(fd, lp); break; case SN_SOFO: res = read_sofo_section(fd, lp); break; case SN_MAP: p = read_string(fd, len); /* <mapstr> */ if (p == NULL) goto endFAIL; set_map_str(lp, p); vim_free(p); break; case SN_WORDS: res = read_words_section(fd, lp, len); break; case SN_SUGFILE: lp->sl_sugtime = get8ctime(fd); /* <timestamp> */ break; case SN_NOSPLITSUGS: lp->sl_nosplitsugs = TRUE; /* <timestamp> */ break; case SN_COMPOUND: res = read_compound(fd, lp, len); break; case SN_NOBREAK: lp->sl_nobreak = TRUE; break; case SN_SYLLABLE: lp->sl_syllable = read_string(fd, len); /* <syllable> */ if (lp->sl_syllable == NULL) goto endFAIL; if (init_syl_tab(lp) == FAIL) goto endFAIL; break; default: /* Unsupported section. When it's required give an error * message. When it's not required skip the contents. */ if (c & SNF_REQUIRED) { EMSG(_("E770: Unsupported section in spell file")); goto endFAIL; } while (--len >= 0) if (getc(fd) < 0) goto truncerr; break; } someerror: if (res == SP_FORMERROR) { EMSG(_(e_format)); goto endFAIL; } if (res == SP_TRUNCERROR) { truncerr: EMSG(_(e_spell_trunc)); goto endFAIL; } if (res == SP_OTHERERROR) goto endFAIL; } /* <LWORDTREE> */ res = spell_read_tree(fd, &lp->sl_fbyts, &lp->sl_fidxs, FALSE, 0); if (res != 0) goto someerror; /* <KWORDTREE> */ res = spell_read_tree(fd, &lp->sl_kbyts, &lp->sl_kidxs, FALSE, 0); if (res != 0) goto someerror; /* <PREFIXTREE> */ res = spell_read_tree(fd, &lp->sl_pbyts, &lp->sl_pidxs, TRUE, lp->sl_prefixcnt); if (res != 0) goto someerror; /* For a new file link it in the list of spell files. */ if (old_lp == NULL && lang != NULL) { lp->sl_next = first_lang; first_lang = lp; } goto endOK; endFAIL: if (lang != NULL) /* truncating the name signals the error to spell_load_lang() */ *lang = NUL; if (lp != NULL && old_lp == NULL) slang_free(lp); lp = NULL; endOK: if (fd != NULL) fclose(fd); sourcing_name = save_sourcing_name; sourcing_lnum = save_sourcing_lnum; return lp; } /* * Read a length field from "fd" in "cnt_bytes" bytes. * Allocate memory, read the string into it and add a NUL at the end. * Returns NULL when the count is zero. * Sets "*cntp" to SP_*ERROR when there is an error, length of the result * otherwise. */ static char_u * read_cnt_string(fd, cnt_bytes, cntp) FILE *fd; int cnt_bytes; int *cntp; { int cnt = 0; int i; char_u *str; /* read the length bytes, MSB first */ for (i = 0; i < cnt_bytes; ++i) cnt = (cnt << 8) + getc(fd); if (cnt < 0) { *cntp = SP_TRUNCERROR; return NULL; } *cntp = cnt; if (cnt == 0) return NULL; /* nothing to read, return NULL */ str = read_string(fd, cnt); if (str == NULL) *cntp = SP_OTHERERROR; return str; } /* * Read SN_REGION: <regionname> ... * Return SP_*ERROR flags. */ static int read_region_section(fd, lp, len) FILE *fd; slang_T *lp; int len; { int i; if (len > 16) return SP_FORMERROR; for (i = 0; i < len; ++i) lp->sl_regions[i] = getc(fd); /* <regionname> */ lp->sl_regions[len] = NUL; return 0; } /* * Read SN_CHARFLAGS section: <charflagslen> <charflags> * <folcharslen> <folchars> * Return SP_*ERROR flags. */ static int read_charflags_section(fd) FILE *fd; { char_u *flags; char_u *fol; int flagslen, follen; /* <charflagslen> <charflags> */ flags = read_cnt_string(fd, 1, &flagslen); if (flagslen < 0) return flagslen; /* <folcharslen> <folchars> */ fol = read_cnt_string(fd, 2, &follen); if (follen < 0) { vim_free(flags); return follen; } /* Set the word-char flags and fill SPELL_ISUPPER() table. */ if (flags != NULL && fol != NULL) set_spell_charflags(flags, flagslen, fol); vim_free(flags); vim_free(fol); /* When <charflagslen> is zero then <fcharlen> must also be zero. */ if ((flags == NULL) != (fol == NULL)) return SP_FORMERROR; return 0; } /* * Read SN_PREFCOND section. * Return SP_*ERROR flags. */ static int read_prefcond_section(fd, lp) FILE *fd; slang_T *lp; { int cnt; int i; int n; char_u *p; char_u buf[MAXWLEN + 1]; /* <prefcondcnt> <prefcond> ... */ cnt = get2c(fd); /* <prefcondcnt> */ if (cnt <= 0) return SP_FORMERROR; lp->sl_prefprog = (regprog_T **)alloc_clear( (unsigned)sizeof(regprog_T *) * cnt); if (lp->sl_prefprog == NULL) return SP_OTHERERROR; lp->sl_prefixcnt = cnt; for (i = 0; i < cnt; ++i) { /* <prefcond> : <condlen> <condstr> */ n = getc(fd); /* <condlen> */ if (n < 0 || n >= MAXWLEN) return SP_FORMERROR; /* When <condlen> is zero we have an empty condition. Otherwise * compile the regexp program used to check for the condition. */ if (n > 0) { buf[0] = '^'; /* always match at one position only */ p = buf + 1; while (n-- > 0) *p++ = getc(fd); /* <condstr> */ *p = NUL; lp->sl_prefprog[i] = vim_regcomp(buf, RE_MAGIC + RE_STRING); } } return 0; } /* * Read REP or REPSAL items section from "fd": <repcount> <rep> ... * Return SP_*ERROR flags. */ static int read_rep_section(fd, gap, first) FILE *fd; garray_T *gap; short *first; { int cnt; fromto_T *ftp; int i; cnt = get2c(fd); /* <repcount> */ if (cnt < 0) return SP_TRUNCERROR; if (ga_grow(gap, cnt) == FAIL) return SP_OTHERERROR; /* <rep> : <repfromlen> <repfrom> <reptolen> <repto> */ for (; gap->ga_len < cnt; ++gap->ga_len) { ftp = &((fromto_T *)gap->ga_data)[gap->ga_len]; ftp->ft_from = read_cnt_string(fd, 1, &i); if (i < 0) return i; if (i == 0) return SP_FORMERROR; ftp->ft_to = read_cnt_string(fd, 1, &i); if (i <= 0) { vim_free(ftp->ft_from); if (i < 0) return i; return SP_FORMERROR; } } /* Fill the first-index table. */ for (i = 0; i < 256; ++i) first[i] = -1; for (i = 0; i < gap->ga_len; ++i) { ftp = &((fromto_T *)gap->ga_data)[i]; if (first[*ftp->ft_from] == -1) first[*ftp->ft_from] = i; } return 0; } /* * Read SN_SAL section: <salflags> <salcount> <sal> ... * Return SP_*ERROR flags. */ static int read_sal_section(fd, slang) FILE *fd; slang_T *slang; { int i; int cnt; garray_T *gap; salitem_T *smp; int ccnt; char_u *p; int c = NUL; slang->sl_sofo = FALSE; i = getc(fd); /* <salflags> */ if (i & SAL_F0LLOWUP) slang->sl_followup = TRUE; if (i & SAL_COLLAPSE) slang->sl_collapse = TRUE; if (i & SAL_REM_ACCENTS) slang->sl_rem_accents = TRUE; cnt = get2c(fd); /* <salcount> */ if (cnt < 0) return SP_TRUNCERROR; gap = &slang->sl_sal; ga_init2(gap, sizeof(salitem_T), 10); if (ga_grow(gap, cnt + 1) == FAIL) return SP_OTHERERROR; /* <sal> : <salfromlen> <salfrom> <saltolen> <salto> */ for (; gap->ga_len < cnt; ++gap->ga_len) { smp = &((salitem_T *)gap->ga_data)[gap->ga_len]; ccnt = getc(fd); /* <salfromlen> */ if (ccnt < 0) return SP_TRUNCERROR; if ((p = alloc(ccnt + 2)) == NULL) return SP_OTHERERROR; smp->sm_lead = p; /* Read up to the first special char into sm_lead. */ for (i = 0; i < ccnt; ++i) { c = getc(fd); /* <salfrom> */ if (vim_strchr((char_u *)"0123456789(-<^$", c) != NULL) break; *p++ = c; } smp->sm_leadlen = (int)(p - smp->sm_lead); *p++ = NUL; /* Put (abc) chars in sm_oneof, if any. */ if (c == '(') { smp->sm_oneof = p; for (++i; i < ccnt; ++i) { c = getc(fd); /* <salfrom> */ if (c == ')') break; *p++ = c; } *p++ = NUL; if (++i < ccnt) c = getc(fd); } else smp->sm_oneof = NULL; /* Any following chars go in sm_rules. */ smp->sm_rules = p; if (i < ccnt) /* store the char we got while checking for end of sm_lead */ *p++ = c; for (++i; i < ccnt; ++i) *p++ = getc(fd); /* <salfrom> */ *p++ = NUL; /* <saltolen> <salto> */ smp->sm_to = read_cnt_string(fd, 1, &ccnt); if (ccnt < 0) { vim_free(smp->sm_lead); return ccnt; } #ifdef FEAT_MBYTE if (has_mbyte) { /* convert the multi-byte strings to wide char strings */ smp->sm_lead_w = mb_str2wide(smp->sm_lead); smp->sm_leadlen = mb_charlen(smp->sm_lead); if (smp->sm_oneof == NULL) smp->sm_oneof_w = NULL; else smp->sm_oneof_w = mb_str2wide(smp->sm_oneof); if (smp->sm_to == NULL) smp->sm_to_w = NULL; else smp->sm_to_w = mb_str2wide(smp->sm_to); if (smp->sm_lead_w == NULL || (smp->sm_oneof_w == NULL && smp->sm_oneof != NULL) || (smp->sm_to_w == NULL && smp->sm_to != NULL)) { vim_free(smp->sm_lead); vim_free(smp->sm_to); vim_free(smp->sm_lead_w); vim_free(smp->sm_oneof_w); vim_free(smp->sm_to_w); return SP_OTHERERROR; } } #endif } if (gap->ga_len > 0) { /* Add one extra entry to mark the end with an empty sm_lead. Avoids * that we need to check the index every time. */ smp = &((salitem_T *)gap->ga_data)[gap->ga_len]; if ((p = alloc(1)) == NULL) return SP_OTHERERROR; p[0] = NUL; smp->sm_lead = p; smp->sm_leadlen = 0; smp->sm_oneof = NULL; smp->sm_rules = p; smp->sm_to = NULL; #ifdef FEAT_MBYTE if (has_mbyte) { smp->sm_lead_w = mb_str2wide(smp->sm_lead); smp->sm_leadlen = 0; smp->sm_oneof_w = NULL; smp->sm_to_w = NULL; } #endif ++gap->ga_len; } /* Fill the first-index table. */ set_sal_first(slang); return 0; } /* * Read SN_WORDS: <word> ... * Return SP_*ERROR flags. */ static int read_words_section(fd, lp, len) FILE *fd; slang_T *lp; int len; { int done = 0; int i; int c; char_u word[MAXWLEN]; while (done < len) { /* Read one word at a time. */ for (i = 0; ; ++i) { c = getc(fd); if (c == EOF) return SP_TRUNCERROR; word[i] = c; if (word[i] == NUL) break; if (i == MAXWLEN - 1) return SP_FORMERROR; } /* Init the count to 10. */ count_common_word(lp, word, -1, 10); done += i + 1; } return 0; } /* * Add a word to the hashtable of common words. * If it's already there then the counter is increased. */ static void count_common_word(lp, word, len, count) slang_T *lp; char_u *word; int len; /* word length, -1 for upto NUL */ int count; /* 1 to count once, 10 to init */ { hash_T hash; hashitem_T *hi; wordcount_T *wc; char_u buf[MAXWLEN]; char_u *p; if (len == -1) p = word; else { vim_strncpy(buf, word, len); p = buf; } hash = hash_hash(p); hi = hash_lookup(&lp->sl_wordcount, p, hash); if (HASHITEM_EMPTY(hi)) { wc = (wordcount_T *)alloc((unsigned)(sizeof(wordcount_T) + STRLEN(p))); if (wc == NULL) return; STRCPY(wc->wc_word, p); wc->wc_count = count; hash_add_item(&lp->sl_wordcount, hi, wc->wc_word, hash); } else { wc = HI2WC(hi); if ((wc->wc_count += count) < (unsigned)count) /* check for overflow */ wc->wc_count = MAXWORDCOUNT; } } /* * Adjust the score of common words. */ static int score_wordcount_adj(slang, score, word, split) slang_T *slang; int score; char_u *word; int split; /* word was split, less bonus */ { hashitem_T *hi; wordcount_T *wc; int bonus; int newscore; hi = hash_find(&slang->sl_wordcount, word); if (!HASHITEM_EMPTY(hi)) { wc = HI2WC(hi); if (wc->wc_count < SCORE_THRES2) bonus = SCORE_COMMON1; else if (wc->wc_count < SCORE_THRES3) bonus = SCORE_COMMON2; else bonus = SCORE_COMMON3; if (split) newscore = score - bonus / 2; else newscore = score - bonus; if (newscore < 0) return 0; return newscore; } return score; } /* * SN_SOFO: <sofofromlen> <sofofrom> <sofotolen> <sofoto> * Return SP_*ERROR flags. */ static int read_sofo_section(fd, slang) FILE *fd; slang_T *slang; { int cnt; char_u *from, *to; int res; slang->sl_sofo = TRUE; /* <sofofromlen> <sofofrom> */ from = read_cnt_string(fd, 2, &cnt); if (cnt < 0) return cnt; /* <sofotolen> <sofoto> */ to = read_cnt_string(fd, 2, &cnt); if (cnt < 0) { vim_free(from); return cnt; } /* Store the info in slang->sl_sal and/or slang->sl_sal_first. */ if (from != NULL && to != NULL) res = set_sofo(slang, from, to); else if (from != NULL || to != NULL) res = SP_FORMERROR; /* only one of two strings is an error */ else res = 0; vim_free(from); vim_free(to); return res; } /* * Read the compound section from the .spl file: * <compmax> <compminlen> <compsylmax> <compoptions> <compflags> * Returns SP_*ERROR flags. */ static int read_compound(fd, slang, len) FILE *fd; slang_T *slang; int len; { int todo = len; int c; int atstart; char_u *pat; char_u *pp; char_u *cp; char_u *ap; char_u *crp; int cnt; garray_T *gap; if (todo < 2) return SP_FORMERROR; /* need at least two bytes */ --todo; c = getc(fd); /* <compmax> */ if (c < 2) c = MAXWLEN; slang->sl_compmax = c; --todo; c = getc(fd); /* <compminlen> */ if (c < 1) c = 0; slang->sl_compminlen = c; --todo; c = getc(fd); /* <compsylmax> */ if (c < 1) c = MAXWLEN; slang->sl_compsylmax = c; c = getc(fd); /* <compoptions> */ if (c != 0) ungetc(c, fd); /* be backwards compatible with Vim 7.0b */ else { --todo; c = getc(fd); /* only use the lower byte for now */ --todo; slang->sl_compoptions = c; gap = &slang->sl_comppat; c = get2c(fd); /* <comppatcount> */ todo -= 2; ga_init2(gap, sizeof(char_u *), c); if (ga_grow(gap, c) == OK) while (--c >= 0) { ((char_u **)(gap->ga_data))[gap->ga_len++] = read_cnt_string(fd, 1, &cnt); /* <comppatlen> <comppattext> */ if (cnt < 0) return cnt; todo -= cnt + 1; } } if (todo < 0) return SP_FORMERROR; /* Turn the COMPOUNDRULE items into a regexp pattern: * "a[bc]/a*b+" -> "^\(a[bc]\|a*b\+\)$". * Inserting backslashes may double the length, "^\(\)$<Nul>" is 7 bytes. * Conversion to utf-8 may double the size. */ c = todo * 2 + 7; #ifdef FEAT_MBYTE if (enc_utf8) c += todo * 2; #endif pat = alloc((unsigned)c); if (pat == NULL) return SP_OTHERERROR; /* We also need a list of all flags that can appear at the start and one * for all flags. */ cp = alloc(todo + 1); if (cp == NULL) { vim_free(pat); return SP_OTHERERROR; } slang->sl_compstartflags = cp; *cp = NUL; ap = alloc(todo + 1); if (ap == NULL) { vim_free(pat); return SP_OTHERERROR; } slang->sl_compallflags = ap; *ap = NUL; /* And a list of all patterns in their original form, for checking whether * compounding may work in match_compoundrule(). This is freed when we * encounter a wildcard, the check doesn't work then. */ crp = alloc(todo + 1); slang->sl_comprules = crp; pp = pat; *pp++ = '^'; *pp++ = '\\'; *pp++ = '('; atstart = 1; while (todo-- > 0) { c = getc(fd); /* <compflags> */ if (c == EOF) { vim_free(pat); return SP_TRUNCERROR; } /* Add all flags to "sl_compallflags". */ if (vim_strchr((char_u *)"?*+[]/", c) == NULL && !byte_in_str(slang->sl_compallflags, c)) { *ap++ = c; *ap = NUL; } if (atstart != 0) { /* At start of item: copy flags to "sl_compstartflags". For a * [abc] item set "atstart" to 2 and copy up to the ']'. */ if (c == '[') atstart = 2; else if (c == ']') atstart = 0; else { if (!byte_in_str(slang->sl_compstartflags, c)) { *cp++ = c; *cp = NUL; } if (atstart == 1) atstart = 0; } } /* Copy flag to "sl_comprules", unless we run into a wildcard. */ if (crp != NULL) { if (c == '?' || c == '+' || c == '*') { vim_free(slang->sl_comprules); slang->sl_comprules = NULL; crp = NULL; } else *crp++ = c; } if (c == '/') /* slash separates two items */ { *pp++ = '\\'; *pp++ = '|'; atstart = 1; } else /* normal char, "[abc]" and '*' are copied as-is */ { if (c == '?' || c == '+' || c == '~') *pp++ = '\\'; /* "a?" becomes "a\?", "a+" becomes "a\+" */ #ifdef FEAT_MBYTE if (enc_utf8) pp += mb_char2bytes(c, pp); else #endif *pp++ = c; } } *pp++ = '\\'; *pp++ = ')'; *pp++ = '$'; *pp = NUL; if (crp != NULL) *crp = NUL; slang->sl_compprog = vim_regcomp(pat, RE_MAGIC + RE_STRING + RE_STRICT); vim_free(pat); if (slang->sl_compprog == NULL) return SP_FORMERROR; return 0; } /* * Return TRUE if byte "n" appears in "str". * Like strchr() but independent of locale. */ static int byte_in_str(str, n) char_u *str; int n; { char_u *p; for (p = str; *p != NUL; ++p) if (*p == n) return TRUE; return FALSE; } #define SY_MAXLEN 30 typedef struct syl_item_S { char_u sy_chars[SY_MAXLEN]; /* the sequence of chars */ int sy_len; } syl_item_T; /* * Truncate "slang->sl_syllable" at the first slash and put the following items * in "slang->sl_syl_items". */ static int init_syl_tab(slang) slang_T *slang; { char_u *p; char_u *s; int l; syl_item_T *syl; ga_init2(&slang->sl_syl_items, sizeof(syl_item_T), 4); p = vim_strchr(slang->sl_syllable, '/'); while (p != NULL) { *p++ = NUL; if (*p == NUL) /* trailing slash */ break; s = p; p = vim_strchr(p, '/'); if (p == NULL) l = (int)STRLEN(s); else l = (int)(p - s); if (l >= SY_MAXLEN) return SP_FORMERROR; if (ga_grow(&slang->sl_syl_items, 1) == FAIL) return SP_OTHERERROR; syl = ((syl_item_T *)slang->sl_syl_items.ga_data) + slang->sl_syl_items.ga_len++; vim_strncpy(syl->sy_chars, s, l); syl->sy_len = l; } return OK; } /* * Count the number of syllables in "word". * When "word" contains spaces the syllables after the last space are counted. * Returns zero if syllables are not defines. */ static int count_syllables(slang, word) slang_T *slang; char_u *word; { int cnt = 0; int skip = FALSE; char_u *p; int len; int i; syl_item_T *syl; int c; if (slang->sl_syllable == NULL) return 0; for (p = word; *p != NUL; p += len) { /* When running into a space reset counter. */ if (*p == ' ') { len = 1; cnt = 0; continue; } /* Find longest match of syllable items. */ len = 0; for (i = 0; i < slang->sl_syl_items.ga_len; ++i) { syl = ((syl_item_T *)slang->sl_syl_items.ga_data) + i; if (syl->sy_len > len && STRNCMP(p, syl->sy_chars, syl->sy_len) == 0) len = syl->sy_len; } if (len != 0) /* found a match, count syllable */ { ++cnt; skip = FALSE; } else { /* No recognized syllable item, at least a syllable char then? */ #ifdef FEAT_MBYTE c = mb_ptr2char(p); len = (*mb_ptr2len)(p); #else c = *p; len = 1; #endif if (vim_strchr(slang->sl_syllable, c) == NULL) skip = FALSE; /* No, search for next syllable */ else if (!skip) { ++cnt; /* Yes, count it */ skip = TRUE; /* don't count following syllable chars */ } } } return cnt; } /* * Set the SOFOFROM and SOFOTO items in language "lp". * Returns SP_*ERROR flags when there is something wrong. */ static int set_sofo(lp, from, to) slang_T *lp; char_u *from; char_u *to; { int i; #ifdef FEAT_MBYTE garray_T *gap; char_u *s; char_u *p; int c; int *inp; if (has_mbyte) { /* Use "sl_sal" as an array with 256 pointers to a list of wide * characters. The index is the low byte of the character. * The list contains from-to pairs with a terminating NUL. * sl_sal_first[] is used for latin1 "from" characters. */ gap = &lp->sl_sal; ga_init2(gap, sizeof(int *), 1); if (ga_grow(gap, 256) == FAIL) return SP_OTHERERROR; vim_memset(gap->ga_data, 0, sizeof(int *) * 256); gap->ga_len = 256; /* First count the number of items for each list. Temporarily use * sl_sal_first[] for this. */ for (p = from, s = to; *p != NUL && *s != NUL; ) { c = mb_cptr2char_adv(&p); mb_cptr_adv(s); if (c >= 256) ++lp->sl_sal_first[c & 0xff]; } if (*p != NUL || *s != NUL) /* lengths differ */ return SP_FORMERROR; /* Allocate the lists. */ for (i = 0; i < 256; ++i) if (lp->sl_sal_first[i] > 0) { p = alloc(sizeof(int) * (lp->sl_sal_first[i] * 2 + 1)); if (p == NULL) return SP_OTHERERROR; ((int **)gap->ga_data)[i] = (int *)p; *(int *)p = 0; } /* Put the characters up to 255 in sl_sal_first[] the rest in a sl_sal * list. */ vim_memset(lp->sl_sal_first, 0, sizeof(salfirst_T) * 256); for (p = from, s = to; *p != NUL && *s != NUL; ) { c = mb_cptr2char_adv(&p); i = mb_cptr2char_adv(&s); if (c >= 256) { /* Append the from-to chars at the end of the list with * the low byte. */ inp = ((int **)gap->ga_data)[c & 0xff]; while (*inp != 0) ++inp; *inp++ = c; /* from char */ *inp++ = i; /* to char */ *inp++ = NUL; /* NUL at the end */ } else /* mapping byte to char is done in sl_sal_first[] */ lp->sl_sal_first[c] = i; } } else #endif { /* mapping bytes to bytes is done in sl_sal_first[] */ if (STRLEN(from) != STRLEN(to)) return SP_FORMERROR; for (i = 0; to[i] != NUL; ++i) lp->sl_sal_first[from[i]] = to[i]; lp->sl_sal.ga_len = 1; /* indicates we have soundfolding */ } return 0; } /* * Fill the first-index table for "lp". */ static void set_sal_first(lp) slang_T *lp; { salfirst_T *sfirst; int i; salitem_T *smp; int c; garray_T *gap = &lp->sl_sal; sfirst = lp->sl_sal_first; for (i = 0; i < 256; ++i) sfirst[i] = -1; smp = (salitem_T *)gap->ga_data; for (i = 0; i < gap->ga_len; ++i) { #ifdef FEAT_MBYTE if (has_mbyte) /* Use the lowest byte of the first character. For latin1 it's * the character, for other encodings it should differ for most * characters. */ c = *smp[i].sm_lead_w & 0xff; else #endif c = *smp[i].sm_lead; if (sfirst[c] == -1) { sfirst[c] = i; #ifdef FEAT_MBYTE if (has_mbyte) { int n; /* Make sure all entries with this byte are following each * other. Move the ones that are in the wrong position. Do * keep the same ordering! */ while (i + 1 < gap->ga_len && (*smp[i + 1].sm_lead_w & 0xff) == c) /* Skip over entry with same index byte. */ ++i; for (n = 1; i + n < gap->ga_len; ++n) if ((*smp[i + n].sm_lead_w & 0xff) == c) { salitem_T tsal; /* Move entry with same index byte after the entries * we already found. */ ++i; --n; tsal = smp[i + n]; mch_memmove(smp + i + 1, smp + i, sizeof(salitem_T) * n); smp[i] = tsal; } } #endif } } } #ifdef FEAT_MBYTE /* * Turn a multi-byte string into a wide character string. * Return it in allocated memory (NULL for out-of-memory) */ static int * mb_str2wide(s) char_u *s; { int *res; char_u *p; int i = 0; res = (int *)alloc(sizeof(int) * (mb_charlen(s) + 1)); if (res != NULL) { for (p = s; *p != NUL; ) res[i++] = mb_ptr2char_adv(&p); res[i] = NUL; } return res; } #endif /* * Read a tree from the .spl or .sug file. * Allocates the memory and stores pointers in "bytsp" and "idxsp". * This is skipped when the tree has zero length. * Returns zero when OK, SP_ value for an error. */ static int spell_read_tree(fd, bytsp, idxsp, prefixtree, prefixcnt) FILE *fd; char_u **bytsp; idx_T **idxsp; int prefixtree; /* TRUE for the prefix tree */ int prefixcnt; /* when "prefixtree" is TRUE: prefix count */ { int len; int idx; char_u *bp; idx_T *ip; /* The tree size was computed when writing the file, so that we can * allocate it as one long block. <nodecount> */ len = get4c(fd); if (len < 0) return SP_TRUNCERROR; if (len > 0) { /* Allocate the byte array. */ bp = lalloc((long_u)len, TRUE); if (bp == NULL) return SP_OTHERERROR; *bytsp = bp; /* Allocate the index array. */ ip = (idx_T *)lalloc_clear((long_u)(len * sizeof(int)), TRUE); if (ip == NULL) return SP_OTHERERROR; *idxsp = ip; /* Recursively read the tree and store it in the array. */ idx = read_tree_node(fd, bp, ip, len, 0, prefixtree, prefixcnt); if (idx < 0) return idx; } return 0; } /* * Read one row of siblings from the spell file and store it in the byte array * "byts" and index array "idxs". Recursively read the children. * * NOTE: The code here must match put_node()! * * Returns the index (>= 0) following the siblings. * Returns SP_TRUNCERROR if the file is shorter than expected. * Returns SP_FORMERROR if there is a format error. */ static idx_T read_tree_node(fd, byts, idxs, maxidx, startidx, prefixtree, maxprefcondnr) FILE *fd; char_u *byts; idx_T *idxs; int maxidx; /* size of arrays */ idx_T startidx; /* current index in "byts" and "idxs" */ int prefixtree; /* TRUE for reading PREFIXTREE */ int maxprefcondnr; /* maximum for <prefcondnr> */ { int len; int i; int n; idx_T idx = startidx; int c; int c2; #define SHARED_MASK 0x8000000 len = getc(fd); /* <siblingcount> */ if (len <= 0) return SP_TRUNCERROR; if (startidx + len >= maxidx) return SP_FORMERROR; byts[idx++] = len; /* Read the byte values, flag/region bytes and shared indexes. */ for (i = 1; i <= len; ++i) { c = getc(fd); /* <byte> */ if (c < 0) return SP_TRUNCERROR; if (c <= BY_SPECIAL) { if (c == BY_NOFLAGS && !prefixtree) { /* No flags, all regions. */ idxs[idx] = 0; c = 0; } else if (c != BY_INDEX) { if (prefixtree) { /* Read the optional pflags byte, the prefix ID and the * condition nr. In idxs[] store the prefix ID in the low * byte, the condition index shifted up 8 bits, the flags * shifted up 24 bits. */ if (c == BY_FLAGS) c = getc(fd) << 24; /* <pflags> */ else c = 0; c |= getc(fd); /* <affixID> */ n = get2c(fd); /* <prefcondnr> */ if (n >= maxprefcondnr) return SP_FORMERROR; c |= (n << 8); } else /* c must be BY_FLAGS or BY_FLAGS2 */ { /* Read flags and optional region and prefix ID. In * idxs[] the flags go in the low two bytes, region above * that and prefix ID above the region. */ c2 = c; c = getc(fd); /* <flags> */ if (c2 == BY_FLAGS2) c = (getc(fd) << 8) + c; /* <flags2> */ if (c & WF_REGION) c = (getc(fd) << 16) + c; /* <region> */ if (c & WF_AFX) c = (getc(fd) << 24) + c; /* <affixID> */ } idxs[idx] = c; c = 0; } else /* c == BY_INDEX */ { /* <nodeidx> */ n = get3c(fd); if (n < 0 || n >= maxidx) return SP_FORMERROR; idxs[idx] = n + SHARED_MASK; c = getc(fd); /* <xbyte> */ } } byts[idx++] = c; } /* Recursively read the children for non-shared siblings. * Skip the end-of-word ones (zero byte value) and the shared ones (and * remove SHARED_MASK) */ for (i = 1; i <= len; ++i) if (byts[startidx + i] != 0) { if (idxs[startidx + i] & SHARED_MASK) idxs[startidx + i] &= ~SHARED_MASK; else { idxs[startidx + i] = idx; idx = read_tree_node(fd, byts, idxs, maxidx, idx, prefixtree, maxprefcondnr); if (idx < 0) break; } } return idx; } /* * Parse 'spelllang' and set w_s->b_langp accordingly. * Returns NULL if it's OK, an error message otherwise. */ char_u * did_set_spelllang(wp) win_T *wp; { garray_T ga; char_u *splp; char_u *region; char_u region_cp[3]; int filename; int region_mask; slang_T *slang; int c; char_u lang[MAXWLEN + 1]; char_u spf_name[MAXPATHL]; int len; char_u *p; int round; char_u *spf; char_u *use_region = NULL; int dont_use_region = FALSE; int nobreak = FALSE; int i, j; langp_T *lp, *lp2; static int recursive = FALSE; char_u *ret_msg = NULL; char_u *spl_copy; /* We don't want to do this recursively. May happen when a language is * not available and the SpellFileMissing autocommand opens a new buffer * in which 'spell' is set. */ if (recursive) return NULL; recursive = TRUE; ga_init2(&ga, sizeof(langp_T), 2); clear_midword(wp); /* Make a copy of 'spellang', the SpellFileMissing autocommands may change * it under our fingers. */ spl_copy = vim_strsave(wp->w_s->b_p_spl); if (spl_copy == NULL) goto theend; /* loop over comma separated language names. */ for (splp = spl_copy; *splp != NUL; ) { /* Get one language name. */ copy_option_part(&splp, lang, MAXWLEN, ","); region = NULL; len = (int)STRLEN(lang); /* If the name ends in ".spl" use it as the name of the spell file. * If there is a region name let "region" point to it and remove it * from the name. */ if (len > 4 && fnamecmp(lang + len - 4, ".spl") == 0) { filename = TRUE; /* Locate a region and remove it from the file name. */ p = vim_strchr(gettail(lang), '_'); if (p != NULL && ASCII_ISALPHA(p[1]) && ASCII_ISALPHA(p[2]) && !ASCII_ISALPHA(p[3])) { vim_strncpy(region_cp, p + 1, 2); mch_memmove(p, p + 3, len - (p - lang) - 2); len -= 3; region = region_cp; } else dont_use_region = TRUE; /* Check if we loaded this language before. */ for (slang = first_lang; slang != NULL; slang = slang->sl_next) if (fullpathcmp(lang, slang->sl_fname, FALSE) == FPC_SAME) break; } else { filename = FALSE; if (len > 3 && lang[len - 3] == '_') { region = lang + len - 2; len -= 3; lang[len] = NUL; } else dont_use_region = TRUE; /* Check if we loaded this language before. */ for (slang = first_lang; slang != NULL; slang = slang->sl_next) if (STRICMP(lang, slang->sl_name) == 0) break; } if (region != NULL) { /* If the region differs from what was used before then don't * use it for 'spellfile'. */ if (use_region != NULL && STRCMP(region, use_region) != 0) dont_use_region = TRUE; use_region = region; } /* If not found try loading the language now. */ if (slang == NULL) { if (filename) (void)spell_load_file(lang, lang, NULL, FALSE); else { spell_load_lang(lang); #ifdef FEAT_AUTOCMD /* SpellFileMissing autocommands may do anything, including * destroying the buffer we are using... */ if (!buf_valid(wp->w_buffer)) { ret_msg = (char_u *)"E797: SpellFileMissing autocommand deleted buffer"; goto theend; } #endif } } /* * Loop over the languages, there can be several files for "lang". */ for (slang = first_lang; slang != NULL; slang = slang->sl_next) if (filename ? fullpathcmp(lang, slang->sl_fname, FALSE) == FPC_SAME : STRICMP(lang, slang->sl_name) == 0) { region_mask = REGION_ALL; if (!filename && region != NULL) { /* find region in sl_regions */ c = find_region(slang->sl_regions, region); if (c == REGION_ALL) { if (slang->sl_add) { if (*slang->sl_regions != NUL) /* This addition file is for other regions. */ region_mask = 0; } else /* This is probably an error. Give a warning and * accept the words anyway. */ smsg((char_u *) _("Warning: region %s not supported"), region); } else region_mask = 1 << c; } if (region_mask != 0) { if (ga_grow(&ga, 1) == FAIL) { ga_clear(&ga); ret_msg = e_outofmem; goto theend; } LANGP_ENTRY(ga, ga.ga_len)->lp_slang = slang; LANGP_ENTRY(ga, ga.ga_len)->lp_region = region_mask; ++ga.ga_len; use_midword(slang, wp); if (slang->sl_nobreak) nobreak = TRUE; } } } /* round 0: load int_wordlist, if possible. * round 1: load first name in 'spellfile'. * round 2: load second name in 'spellfile. * etc. */ spf = curwin->w_s->b_p_spf; for (round = 0; round == 0 || *spf != NUL; ++round) { if (round == 0) { /* Internal wordlist, if there is one. */ if (int_wordlist == NULL) continue; int_wordlist_spl(spf_name); } else { /* One entry in 'spellfile'. */ copy_option_part(&spf, spf_name, MAXPATHL - 5, ","); STRCAT(spf_name, ".spl"); /* If it was already found above then skip it. */ for (c = 0; c < ga.ga_len; ++c) { p = LANGP_ENTRY(ga, c)->lp_slang->sl_fname; if (p != NULL && fullpathcmp(spf_name, p, FALSE) == FPC_SAME) break; } if (c < ga.ga_len) continue; } /* Check if it was loaded already. */ for (slang = first_lang; slang != NULL; slang = slang->sl_next) if (fullpathcmp(spf_name, slang->sl_fname, FALSE) == FPC_SAME) break; if (slang == NULL) { /* Not loaded, try loading it now. The language name includes the * region name, the region is ignored otherwise. for int_wordlist * use an arbitrary name. */ if (round == 0) STRCPY(lang, "internal wordlist"); else { vim_strncpy(lang, gettail(spf_name), MAXWLEN); p = vim_strchr(lang, '.'); if (p != NULL) *p = NUL; /* truncate at ".encoding.add" */ } slang = spell_load_file(spf_name, lang, NULL, TRUE); /* If one of the languages has NOBREAK we assume the addition * files also have this. */ if (slang != NULL && nobreak) slang->sl_nobreak = TRUE; } if (slang != NULL && ga_grow(&ga, 1) == OK) { region_mask = REGION_ALL; if (use_region != NULL && !dont_use_region) { /* find region in sl_regions */ c = find_region(slang->sl_regions, use_region); if (c != REGION_ALL) region_mask = 1 << c; else if (*slang->sl_regions != NUL) /* This spell file is for other regions. */ region_mask = 0; } if (region_mask != 0) { LANGP_ENTRY(ga, ga.ga_len)->lp_slang = slang; LANGP_ENTRY(ga, ga.ga_len)->lp_sallang = NULL; LANGP_ENTRY(ga, ga.ga_len)->lp_replang = NULL; LANGP_ENTRY(ga, ga.ga_len)->lp_region = region_mask; ++ga.ga_len; use_midword(slang, wp); } } } /* Everything is fine, store the new b_langp value. */ ga_clear(&wp->w_s->b_langp); wp->w_s->b_langp = ga; /* For each language figure out what language to use for sound folding and * REP items. If the language doesn't support it itself use another one * with the same name. E.g. for "en-math" use "en". */ for (i = 0; i < ga.ga_len; ++i) { lp = LANGP_ENTRY(ga, i); /* sound folding */ if (lp->lp_slang->sl_sal.ga_len > 0) /* language does sound folding itself */ lp->lp_sallang = lp->lp_slang; else /* find first similar language that does sound folding */ for (j = 0; j < ga.ga_len; ++j) { lp2 = LANGP_ENTRY(ga, j); if (lp2->lp_slang->sl_sal.ga_len > 0 && STRNCMP(lp->lp_slang->sl_name, lp2->lp_slang->sl_name, 2) == 0) { lp->lp_sallang = lp2->lp_slang; break; } } /* REP items */ if (lp->lp_slang->sl_rep.ga_len > 0) /* language has REP items itself */ lp->lp_replang = lp->lp_slang; else /* find first similar language that has REP items */ for (j = 0; j < ga.ga_len; ++j) { lp2 = LANGP_ENTRY(ga, j); if (lp2->lp_slang->sl_rep.ga_len > 0 && STRNCMP(lp->lp_slang->sl_name, lp2->lp_slang->sl_name, 2) == 0) { lp->lp_replang = lp2->lp_slang; break; } } } theend: vim_free(spl_copy); recursive = FALSE; return ret_msg; } /* * Clear the midword characters for buffer "buf". */ static void clear_midword(wp) win_T *wp; { vim_memset(wp->w_s->b_spell_ismw, 0, 256); #ifdef FEAT_MBYTE vim_free(wp->w_s->b_spell_ismw_mb); wp->w_s->b_spell_ismw_mb = NULL; #endif } /* * Use the "sl_midword" field of language "lp" for buffer "buf". * They add up to any currently used midword characters. */ static void use_midword(lp, wp) slang_T *lp; win_T *wp; { char_u *p; if (lp->sl_midword == NULL) /* there aren't any */ return; for (p = lp->sl_midword; *p != NUL; ) #ifdef FEAT_MBYTE if (has_mbyte) { int c, l, n; char_u *bp; c = mb_ptr2char(p); l = (*mb_ptr2len)(p); if (c < 256 && l <= 2) wp->w_s->b_spell_ismw[c] = TRUE; else if (wp->w_s->b_spell_ismw_mb == NULL) /* First multi-byte char in "b_spell_ismw_mb". */ wp->w_s->b_spell_ismw_mb = vim_strnsave(p, l); else { /* Append multi-byte chars to "b_spell_ismw_mb". */ n = (int)STRLEN(wp->w_s->b_spell_ismw_mb); bp = vim_strnsave(wp->w_s->b_spell_ismw_mb, n + l); if (bp != NULL) { vim_free(wp->w_s->b_spell_ismw_mb); wp->w_s->b_spell_ismw_mb = bp; vim_strncpy(bp + n, p, l); } } p += l; } else #endif wp->w_s->b_spell_ismw[*p++] = TRUE; } /* * Find the region "region[2]" in "rp" (points to "sl_regions"). * Each region is simply stored as the two characters of it's name. * Returns the index if found (first is 0), REGION_ALL if not found. */ static int find_region(rp, region) char_u *rp; char_u *region; { int i; for (i = 0; ; i += 2) { if (rp[i] == NUL) return REGION_ALL; if (rp[i] == region[0] && rp[i + 1] == region[1]) break; } return i / 2; } /* * Return case type of word: * w word 0 * Word WF_ONECAP * W WORD WF_ALLCAP * WoRd wOrd WF_KEEPCAP */ static int captype(word, end) char_u *word; char_u *end; /* When NULL use up to NUL byte. */ { char_u *p; int c; int firstcap; int allcap; int past_second = FALSE; /* past second word char */ /* find first letter */ for (p = word; !spell_iswordp_nmw(p); mb_ptr_adv(p)) if (end == NULL ? *p == NUL : p >= end) return 0; /* only non-word characters, illegal word */ #ifdef FEAT_MBYTE if (has_mbyte) c = mb_ptr2char_adv(&p); else #endif c = *p++; firstcap = allcap = SPELL_ISUPPER(c); /* * Need to check all letters to find a word with mixed upper/lower. * But a word with an upper char only at start is a ONECAP. */ for ( ; end == NULL ? *p != NUL : p < end; mb_ptr_adv(p)) if (spell_iswordp_nmw(p)) { c = PTR2CHAR(p); if (!SPELL_ISUPPER(c)) { /* UUl -> KEEPCAP */ if (past_second && allcap) return WF_KEEPCAP; allcap = FALSE; } else if (!allcap) /* UlU -> KEEPCAP */ return WF_KEEPCAP; past_second = TRUE; } if (allcap) return WF_ALLCAP; if (firstcap) return WF_ONECAP; return 0; } /* * Like captype() but for a KEEPCAP word add ONECAP if the word starts with a * capital. So that make_case_word() can turn WOrd into Word. * Add ALLCAP for "WOrD". */ static int badword_captype(word, end) char_u *word; char_u *end; { int flags = captype(word, end); int c; int l, u; int first; char_u *p; if (flags & WF_KEEPCAP) { /* Count the number of UPPER and lower case letters. */ l = u = 0; first = FALSE; for (p = word; p < end; mb_ptr_adv(p)) { c = PTR2CHAR(p); if (SPELL_ISUPPER(c)) { ++u; if (p == word) first = TRUE; } else ++l; } /* If there are more UPPER than lower case letters suggest an * ALLCAP word. Otherwise, if the first letter is UPPER then * suggest ONECAP. Exception: "ALl" most likely should be "All", * require three upper case letters. */ if (u > l && u > 2) flags |= WF_ALLCAP; else if (first) flags |= WF_ONECAP; if (u >= 2 && l >= 2) /* maCARONI maCAroni */ flags |= WF_MIXCAP; } return flags; } # if defined(FEAT_MBYTE) || defined(EXITFREE) || defined(PROTO) /* * Free all languages. */ void spell_free_all() { slang_T *slang; buf_T *buf; char_u fname[MAXPATHL]; /* Go through all buffers and handle 'spelllang'. <VN> */ for (buf = firstbuf; buf != NULL; buf = buf->b_next) ga_clear(&buf->b_s.b_langp); while (first_lang != NULL) { slang = first_lang; first_lang = slang->sl_next; slang_free(slang); } if (int_wordlist != NULL) { /* Delete the internal wordlist and its .spl file */ mch_remove(int_wordlist); int_wordlist_spl(fname); mch_remove(fname); vim_free(int_wordlist); int_wordlist = NULL; } vim_free(repl_to); repl_to = NULL; vim_free(repl_from); repl_from = NULL; } # endif # if defined(FEAT_MBYTE) || defined(PROTO) /* * Clear all spelling tables and reload them. * Used after 'encoding' is set and when ":mkspell" was used. */ void spell_reload() { win_T *wp; /* Initialize the table for spell_iswordp(). */ init_spell_chartab(); /* Unload all allocated memory. */ spell_free_all(); /* Go through all buffers and handle 'spelllang'. */ for (wp = firstwin; wp != NULL; wp = wp->w_next) { /* Only load the wordlists when 'spelllang' is set and there is a * window for this buffer in which 'spell' is set. */ if (*wp->w_s->b_p_spl != NUL) { if (wp->w_p_spell) { (void)did_set_spelllang(wp); # ifdef FEAT_WINDOWS break; # endif } } } } # endif /* * Reload the spell file "fname" if it's loaded. */ static void spell_reload_one(fname, added_word) char_u *fname; int added_word; /* invoked through "zg" */ { slang_T *slang; int didit = FALSE; for (slang = first_lang; slang != NULL; slang = slang->sl_next) { if (fullpathcmp(fname, slang->sl_fname, FALSE) == FPC_SAME) { slang_clear(slang); if (spell_load_file(fname, NULL, slang, FALSE) == NULL) /* reloading failed, clear the language */ slang_clear(slang); redraw_all_later(SOME_VALID); didit = TRUE; } } /* When "zg" was used and the file wasn't loaded yet, should redo * 'spelllang' to load it now. */ if (added_word && !didit) did_set_spelllang(curwin); } /* * Functions for ":mkspell". */ #define MAXLINELEN 500 /* Maximum length in bytes of a line in a .aff and .dic file. */ /* * Main structure to store the contents of a ".aff" file. */ typedef struct afffile_S { char_u *af_enc; /* "SET", normalized, alloc'ed string or NULL */ int af_flagtype; /* AFT_CHAR, AFT_LONG, AFT_NUM or AFT_CAPLONG */ unsigned af_rare; /* RARE ID for rare word */ unsigned af_keepcase; /* KEEPCASE ID for keep-case word */ unsigned af_bad; /* BAD ID for banned word */ unsigned af_needaffix; /* NEEDAFFIX ID */ unsigned af_circumfix; /* CIRCUMFIX ID */ unsigned af_needcomp; /* NEEDCOMPOUND ID */ unsigned af_comproot; /* COMPOUNDROOT ID */ unsigned af_compforbid; /* COMPOUNDFORBIDFLAG ID */ unsigned af_comppermit; /* COMPOUNDPERMITFLAG ID */ unsigned af_nosuggest; /* NOSUGGEST ID */ int af_pfxpostpone; /* postpone prefixes without chop string and without flags */ hashtab_T af_pref; /* hashtable for prefixes, affheader_T */ hashtab_T af_suff; /* hashtable for suffixes, affheader_T */ hashtab_T af_comp; /* hashtable for compound flags, compitem_T */ } afffile_T; #define AFT_CHAR 0 /* flags are one character */ #define AFT_LONG 1 /* flags are two characters */ #define AFT_CAPLONG 2 /* flags are one or two characters */ #define AFT_NUM 3 /* flags are numbers, comma separated */ typedef struct affentry_S affentry_T; /* Affix entry from ".aff" file. Used for prefixes and suffixes. */ struct affentry_S { affentry_T *ae_next; /* next affix with same name/number */ char_u *ae_chop; /* text to chop off basic word (can be NULL) */ char_u *ae_add; /* text to add to basic word (can be NULL) */ char_u *ae_flags; /* flags on the affix (can be NULL) */ char_u *ae_cond; /* condition (NULL for ".") */ regprog_T *ae_prog; /* regexp program for ae_cond or NULL */ char ae_compforbid; /* COMPOUNDFORBIDFLAG found */ char ae_comppermit; /* COMPOUNDPERMITFLAG found */ }; #ifdef FEAT_MBYTE # define AH_KEY_LEN 17 /* 2 x 8 bytes + NUL */ #else # define AH_KEY_LEN 7 /* 6 digits + NUL */ #endif /* Affix header from ".aff" file. Used for af_pref and af_suff. */ typedef struct affheader_S { char_u ah_key[AH_KEY_LEN]; /* key for hashtab == name of affix */ unsigned ah_flag; /* affix name as number, uses "af_flagtype" */ int ah_newID; /* prefix ID after renumbering; 0 if not used */ int ah_combine; /* suffix may combine with prefix */ int ah_follows; /* another affix block should be following */ affentry_T *ah_first; /* first affix entry */ } affheader_T; #define HI2AH(hi) ((affheader_T *)(hi)->hi_key) /* Flag used in compound items. */ typedef struct compitem_S { char_u ci_key[AH_KEY_LEN]; /* key for hashtab == name of compound */ unsigned ci_flag; /* affix name as number, uses "af_flagtype" */ int ci_newID; /* affix ID after renumbering. */ } compitem_T; #define HI2CI(hi) ((compitem_T *)(hi)->hi_key) /* * Structure that is used to store the items in the word tree. This avoids * the need to keep track of each allocated thing, everything is freed all at * once after ":mkspell" is done. * Note: "sb_next" must be just before "sb_data" to make sure the alignment of * "sb_data" is correct for systems where pointers must be aligned on * pointer-size boundaries and sizeof(pointer) > sizeof(int) (e.g., Sparc). */ #define SBLOCKSIZE 16000 /* size of sb_data */ typedef struct sblock_S sblock_T; struct sblock_S { int sb_used; /* nr of bytes already in use */ sblock_T *sb_next; /* next block in list */ char_u sb_data[1]; /* data, actually longer */ }; /* * A node in the tree. */ typedef struct wordnode_S wordnode_T; struct wordnode_S { union /* shared to save space */ { char_u hashkey[6]; /* the hash key, only used while compressing */ int index; /* index in written nodes (valid after first round) */ } wn_u1; union /* shared to save space */ { wordnode_T *next; /* next node with same hash key */ wordnode_T *wnode; /* parent node that will write this node */ } wn_u2; wordnode_T *wn_child; /* child (next byte in word) */ wordnode_T *wn_sibling; /* next sibling (alternate byte in word, always sorted) */ int wn_refs; /* Nr. of references to this node. Only relevant for first node in a list of siblings, in following siblings it is always one. */ char_u wn_byte; /* Byte for this node. NUL for word end */ /* Info for when "wn_byte" is NUL. * In PREFIXTREE "wn_region" is used for the prefcondnr. * In the soundfolded word tree "wn_flags" has the MSW of the wordnr and * "wn_region" the LSW of the wordnr. */ char_u wn_affixID; /* supported/required prefix ID or 0 */ short_u wn_flags; /* WF_ flags */ short wn_region; /* region mask */ #ifdef SPELL_PRINTTREE int wn_nr; /* sequence nr for printing */ #endif }; #define WN_MASK 0xffff /* mask relevant bits of "wn_flags" */ #define HI2WN(hi) (wordnode_T *)((hi)->hi_key) /* * Info used while reading the spell files. */ typedef struct spellinfo_S { wordnode_T *si_foldroot; /* tree with case-folded words */ long si_foldwcount; /* nr of words in si_foldroot */ wordnode_T *si_keeproot; /* tree with keep-case words */ long si_keepwcount; /* nr of words in si_keeproot */ wordnode_T *si_prefroot; /* tree with postponed prefixes */ long si_sugtree; /* creating the soundfolding trie */ sblock_T *si_blocks; /* memory blocks used */ long si_blocks_cnt; /* memory blocks allocated */ int si_did_emsg; /* TRUE when ran out of memory */ long si_compress_cnt; /* words to add before lowering compression limit */ wordnode_T *si_first_free; /* List of nodes that have been freed during compression, linked by "wn_child" field. */ long si_free_count; /* number of nodes in si_first_free */ #ifdef SPELL_PRINTTREE int si_wordnode_nr; /* sequence nr for nodes */ #endif buf_T *si_spellbuf; /* buffer used to store soundfold word table */ int si_ascii; /* handling only ASCII words */ int si_add; /* addition file */ int si_clear_chartab; /* when TRUE clear char tables */ int si_region; /* region mask */ vimconv_T si_conv; /* for conversion to 'encoding' */ int si_memtot; /* runtime memory used */ int si_verbose; /* verbose messages */ int si_msg_count; /* number of words added since last message */ char_u *si_info; /* info text chars or NULL */ int si_region_count; /* number of regions supported (1 when there are no regions) */ char_u si_region_name[17]; /* region names; used only if * si_region_count > 1) */ garray_T si_rep; /* list of fromto_T entries from REP lines */ garray_T si_repsal; /* list of fromto_T entries from REPSAL lines */ garray_T si_sal; /* list of fromto_T entries from SAL lines */ char_u *si_sofofr; /* SOFOFROM text */ char_u *si_sofoto; /* SOFOTO text */ int si_nosugfile; /* NOSUGFILE item found */ int si_nosplitsugs; /* NOSPLITSUGS item found */ int si_followup; /* soundsalike: ? */ int si_collapse; /* soundsalike: ? */ hashtab_T si_commonwords; /* hashtable for common words */ time_t si_sugtime; /* timestamp for .sug file */ int si_rem_accents; /* soundsalike: remove accents */ garray_T si_map; /* MAP info concatenated */ char_u *si_midword; /* MIDWORD chars or NULL */ int si_compmax; /* max nr of words for compounding */ int si_compminlen; /* minimal length for compounding */ int si_compsylmax; /* max nr of syllables for compounding */ int si_compoptions; /* COMP_ flags */ garray_T si_comppat; /* CHECKCOMPOUNDPATTERN items, each stored as a string */ char_u *si_compflags; /* flags used for compounding */ char_u si_nobreak; /* NOBREAK */ char_u *si_syllable; /* syllable string */ garray_T si_prefcond; /* table with conditions for postponed * prefixes, each stored as a string */ int si_newprefID; /* current value for ah_newID */ int si_newcompID; /* current value for compound ID */ } spellinfo_T; static afffile_T *spell_read_aff __ARGS((spellinfo_T *spin, char_u *fname)); static int is_aff_rule __ARGS((char_u **items, int itemcnt, char *rulename, int mincount)); static void aff_process_flags __ARGS((afffile_T *affile, affentry_T *entry)); static int spell_info_item __ARGS((char_u *s)); static unsigned affitem2flag __ARGS((int flagtype, char_u *item, char_u *fname, int lnum)); static unsigned get_affitem __ARGS((int flagtype, char_u **pp)); static void process_compflags __ARGS((spellinfo_T *spin, afffile_T *aff, char_u *compflags)); static void check_renumber __ARGS((spellinfo_T *spin)); static int flag_in_afflist __ARGS((int flagtype, char_u *afflist, unsigned flag)); static void aff_check_number __ARGS((int spinval, int affval, char *name)); static void aff_check_string __ARGS((char_u *spinval, char_u *affval, char *name)); static int str_equal __ARGS((char_u *s1, char_u *s2)); static void add_fromto __ARGS((spellinfo_T *spin, garray_T *gap, char_u *from, char_u *to)); static int sal_to_bool __ARGS((char_u *s)); static void spell_free_aff __ARGS((afffile_T *aff)); static int spell_read_dic __ARGS((spellinfo_T *spin, char_u *fname, afffile_T *affile)); static int get_affix_flags __ARGS((afffile_T *affile, char_u *afflist)); static int get_pfxlist __ARGS((afffile_T *affile, char_u *afflist, char_u *store_afflist)); static void get_compflags __ARGS((afffile_T *affile, char_u *afflist, char_u *store_afflist)); static int store_aff_word __ARGS((spellinfo_T *spin, char_u *word, char_u *afflist, afffile_T *affile, hashtab_T *ht, hashtab_T *xht, int condit, int flags, char_u *pfxlist, int pfxlen)); static int spell_read_wordfile __ARGS((spellinfo_T *spin, char_u *fname)); static void *getroom __ARGS((spellinfo_T *spin, size_t len, int align)); static char_u *getroom_save __ARGS((spellinfo_T *spin, char_u *s)); static void free_blocks __ARGS((sblock_T *bl)); static wordnode_T *wordtree_alloc __ARGS((spellinfo_T *spin)); static int store_word __ARGS((spellinfo_T *spin, char_u *word, int flags, int region, char_u *pfxlist, int need_affix)); static int tree_add_word __ARGS((spellinfo_T *spin, char_u *word, wordnode_T *tree, int flags, int region, int affixID)); static wordnode_T *get_wordnode __ARGS((spellinfo_T *spin)); static int deref_wordnode __ARGS((spellinfo_T *spin, wordnode_T *node)); static void free_wordnode __ARGS((spellinfo_T *spin, wordnode_T *n)); static void wordtree_compress __ARGS((spellinfo_T *spin, wordnode_T *root)); static int node_compress __ARGS((spellinfo_T *spin, wordnode_T *node, hashtab_T *ht, int *tot)); static int node_equal __ARGS((wordnode_T *n1, wordnode_T *n2)); static int write_vim_spell __ARGS((spellinfo_T *spin, char_u *fname)); static void clear_node __ARGS((wordnode_T *node)); static int put_node __ARGS((FILE *fd, wordnode_T *node, int idx, int regionmask, int prefixtree)); static void spell_make_sugfile __ARGS((spellinfo_T *spin, char_u *wfname)); static int sug_filltree __ARGS((spellinfo_T *spin, slang_T *slang)); static int sug_maketable __ARGS((spellinfo_T *spin)); static int sug_filltable __ARGS((spellinfo_T *spin, wordnode_T *node, int startwordnr, garray_T *gap)); static int offset2bytes __ARGS((int nr, char_u *buf)); static int bytes2offset __ARGS((char_u **pp)); static void sug_write __ARGS((spellinfo_T *spin, char_u *fname)); static void mkspell __ARGS((int fcount, char_u **fnames, int ascii, int over_write, int added_word)); static void spell_message __ARGS((spellinfo_T *spin, char_u *str)); static void init_spellfile __ARGS((void)); /* In the postponed prefixes tree wn_flags is used to store the WFP_ flags, * but it must be negative to indicate the prefix tree to tree_add_word(). * Use a negative number with the lower 8 bits zero. */ #define PFX_FLAGS -256 /* flags for "condit" argument of store_aff_word() */ #define CONDIT_COMB 1 /* affix must combine */ #define CONDIT_CFIX 2 /* affix must have CIRCUMFIX flag */ #define CONDIT_SUF 4 /* add a suffix for matching flags */ #define CONDIT_AFF 8 /* word already has an affix */ /* * Tunable parameters for when the tree is compressed. See 'mkspellmem'. */ static long compress_start = 30000; /* memory / SBLOCKSIZE */ static long compress_inc = 100; /* memory / SBLOCKSIZE */ static long compress_added = 500000; /* word count */ #ifdef SPELL_PRINTTREE /* * For debugging the tree code: print the current tree in a (more or less) * readable format, so that we can see what happens when adding a word and/or * compressing the tree. * Based on code from Olaf Seibert. */ #define PRINTLINESIZE 1000 #define PRINTWIDTH 6 #define PRINTSOME(l, depth, fmt, a1, a2) vim_snprintf(l + depth * PRINTWIDTH, \ PRINTLINESIZE - PRINTWIDTH * depth, fmt, a1, a2) static char line1[PRINTLINESIZE]; static char line2[PRINTLINESIZE]; static char line3[PRINTLINESIZE]; static void spell_clear_flags(wordnode_T *node) { wordnode_T *np; for (np = node; np != NULL; np = np->wn_sibling) { np->wn_u1.index = FALSE; spell_clear_flags(np->wn_child); } } static void spell_print_node(wordnode_T *node, int depth) { if (node->wn_u1.index) { /* Done this node before, print the reference. */ PRINTSOME(line1, depth, "(%d)", node->wn_nr, 0); PRINTSOME(line2, depth, " ", 0, 0); PRINTSOME(line3, depth, " ", 0, 0); msg(line1); msg(line2); msg(line3); } else { node->wn_u1.index = TRUE; if (node->wn_byte != NUL) { if (node->wn_child != NULL) PRINTSOME(line1, depth, " %c -> ", node->wn_byte, 0); else /* Cannot happen? */ PRINTSOME(line1, depth, " %c ???", node->wn_byte, 0); } else PRINTSOME(line1, depth, " $ ", 0, 0); PRINTSOME(line2, depth, "%d/%d ", node->wn_nr, node->wn_refs); if (node->wn_sibling != NULL) PRINTSOME(line3, depth, " | ", 0, 0); else PRINTSOME(line3, depth, " ", 0, 0); if (node->wn_byte == NUL) { msg(line1); msg(line2); msg(line3); } /* do the children */ if (node->wn_byte != NUL && node->wn_child != NULL) spell_print_node(node->wn_child, depth + 1); /* do the siblings */ if (node->wn_sibling != NULL) { /* get rid of all parent details except | */ STRCPY(line1, line3); STRCPY(line2, line3); spell_print_node(node->wn_sibling, depth); } } } static void spell_print_tree(wordnode_T *root) { if (root != NULL) { /* Clear the "wn_u1.index" fields, used to remember what has been * done. */ spell_clear_flags(root); /* Recursively print the tree. */ spell_print_node(root, 0); } } #endif /* SPELL_PRINTTREE */ /* * Read the affix file "fname". * Returns an afffile_T, NULL for complete failure. */ static afffile_T * spell_read_aff(spin, fname) spellinfo_T *spin; char_u *fname; { FILE *fd; afffile_T *aff; char_u rline[MAXLINELEN]; char_u *line; char_u *pc = NULL; #define MAXITEMCNT 30 char_u *(items[MAXITEMCNT]); int itemcnt; char_u *p; int lnum = 0; affheader_T *cur_aff = NULL; int did_postpone_prefix = FALSE; int aff_todo = 0; hashtab_T *tp; char_u *low = NULL; char_u *fol = NULL; char_u *upp = NULL; int do_rep; int do_repsal; int do_sal; int do_mapline; int found_map = FALSE; hashitem_T *hi; int l; int compminlen = 0; /* COMPOUNDMIN value */ int compsylmax = 0; /* COMPOUNDSYLMAX value */ int compoptions = 0; /* COMP_ flags */ int compmax = 0; /* COMPOUNDWORDMAX value */ char_u *compflags = NULL; /* COMPOUNDFLAG and COMPOUNDRULE concatenated */ char_u *midword = NULL; /* MIDWORD value */ char_u *syllable = NULL; /* SYLLABLE value */ char_u *sofofrom = NULL; /* SOFOFROM value */ char_u *sofoto = NULL; /* SOFOTO value */ /* * Open the file. */ fd = mch_fopen((char *)fname, "r"); if (fd == NULL) { EMSG2(_(e_notopen), fname); return NULL; } vim_snprintf((char *)IObuff, IOSIZE, _("Reading affix file %s ..."), fname); spell_message(spin, IObuff); /* Only do REP lines when not done in another .aff file already. */ do_rep = spin->si_rep.ga_len == 0; /* Only do REPSAL lines when not done in another .aff file already. */ do_repsal = spin->si_repsal.ga_len == 0; /* Only do SAL lines when not done in another .aff file already. */ do_sal = spin->si_sal.ga_len == 0; /* Only do MAP lines when not done in another .aff file already. */ do_mapline = spin->si_map.ga_len == 0; /* * Allocate and init the afffile_T structure. */ aff = (afffile_T *)getroom(spin, sizeof(afffile_T), TRUE); if (aff == NULL) { fclose(fd); return NULL; } hash_init(&aff->af_pref); hash_init(&aff->af_suff); hash_init(&aff->af_comp); /* * Read all the lines in the file one by one. */ while (!vim_fgets(rline, MAXLINELEN, fd) && !got_int) { line_breakcheck(); ++lnum; /* Skip comment lines. */ if (*rline == '#') continue; /* Convert from "SET" to 'encoding' when needed. */ vim_free(pc); #ifdef FEAT_MBYTE if (spin->si_conv.vc_type != CONV_NONE) { pc = string_convert(&spin->si_conv, rline, NULL); if (pc == NULL) { smsg((char_u *)_("Conversion failure for word in %s line %d: %s"), fname, lnum, rline); continue; } line = pc; } else #endif { pc = NULL; line = rline; } /* Split the line up in white separated items. Put a NUL after each * item. */ itemcnt = 0; for (p = line; ; ) { while (*p != NUL && *p <= ' ') /* skip white space and CR/NL */ ++p; if (*p == NUL) break; if (itemcnt == MAXITEMCNT) /* too many items */ break; items[itemcnt++] = p; /* A few items have arbitrary text argument, don't split them. */ if (itemcnt == 2 && spell_info_item(items[0])) while (*p >= ' ' || *p == TAB) /* skip until CR/NL */ ++p; else while (*p > ' ') /* skip until white space or CR/NL */ ++p; if (*p == NUL) break; *p++ = NUL; } /* Handle non-empty lines. */ if (itemcnt > 0) { if (is_aff_rule(items, itemcnt, "SET", 2) && aff->af_enc == NULL) { #ifdef FEAT_MBYTE /* Setup for conversion from "ENC" to 'encoding'. */ aff->af_enc = enc_canonize(items[1]); if (aff->af_enc != NULL && !spin->si_ascii && convert_setup(&spin->si_conv, aff->af_enc, p_enc) == FAIL) smsg((char_u *)_("Conversion in %s not supported: from %s to %s"), fname, aff->af_enc, p_enc); spin->si_conv.vc_fail = TRUE; #else smsg((char_u *)_("Conversion in %s not supported"), fname); #endif } else if (is_aff_rule(items, itemcnt, "FLAG", 2) && aff->af_flagtype == AFT_CHAR) { if (STRCMP(items[1], "long") == 0) aff->af_flagtype = AFT_LONG; else if (STRCMP(items[1], "num") == 0) aff->af_flagtype = AFT_NUM; else if (STRCMP(items[1], "caplong") == 0) aff->af_flagtype = AFT_CAPLONG; else smsg((char_u *)_("Invalid value for FLAG in %s line %d: %s"), fname, lnum, items[1]); if (aff->af_rare != 0 || aff->af_keepcase != 0 || aff->af_bad != 0 || aff->af_needaffix != 0 || aff->af_circumfix != 0 || aff->af_needcomp != 0 || aff->af_comproot != 0 || aff->af_nosuggest != 0 || compflags != NULL || aff->af_suff.ht_used > 0 || aff->af_pref.ht_used > 0) smsg((char_u *)_("FLAG after using flags in %s line %d: %s"), fname, lnum, items[1]); } else if (spell_info_item(items[0])) { p = (char_u *)getroom(spin, (spin->si_info == NULL ? 0 : STRLEN(spin->si_info)) + STRLEN(items[0]) + STRLEN(items[1]) + 3, FALSE); if (p != NULL) { if (spin->si_info != NULL) { STRCPY(p, spin->si_info); STRCAT(p, "\n"); } STRCAT(p, items[0]); STRCAT(p, " "); STRCAT(p, items[1]); spin->si_info = p; } } else if (is_aff_rule(items, itemcnt, "MIDWORD", 2) && midword == NULL) { midword = getroom_save(spin, items[1]); } else if (is_aff_rule(items, itemcnt, "TRY", 2)) { /* ignored, we look in the tree for what chars may appear */ } /* TODO: remove "RAR" later */ else if ((is_aff_rule(items, itemcnt, "RAR", 2) || is_aff_rule(items, itemcnt, "RARE", 2)) && aff->af_rare == 0) { aff->af_rare = affitem2flag(aff->af_flagtype, items[1], fname, lnum); } /* TODO: remove "KEP" later */ else if ((is_aff_rule(items, itemcnt, "KEP", 2) || is_aff_rule(items, itemcnt, "KEEPCASE", 2)) && aff->af_keepcase == 0) { aff->af_keepcase = affitem2flag(aff->af_flagtype, items[1], fname, lnum); } else if ((is_aff_rule(items, itemcnt, "BAD", 2) || is_aff_rule(items, itemcnt, "FORBIDDENWORD", 2)) && aff->af_bad == 0) { aff->af_bad = affitem2flag(aff->af_flagtype, items[1], fname, lnum); } else if (is_aff_rule(items, itemcnt, "NEEDAFFIX", 2) && aff->af_needaffix == 0) { aff->af_needaffix = affitem2flag(aff->af_flagtype, items[1], fname, lnum); } else if (is_aff_rule(items, itemcnt, "CIRCUMFIX", 2) && aff->af_circumfix == 0) { aff->af_circumfix = affitem2flag(aff->af_flagtype, items[1], fname, lnum); } else if (is_aff_rule(items, itemcnt, "NOSUGGEST", 2) && aff->af_nosuggest == 0) { aff->af_nosuggest = affitem2flag(aff->af_flagtype, items[1], fname, lnum); } else if ((is_aff_rule(items, itemcnt, "NEEDCOMPOUND", 2) || is_aff_rule(items, itemcnt, "ONLYINCOMPOUND", 2)) && aff->af_needcomp == 0) { aff->af_needcomp = affitem2flag(aff->af_flagtype, items[1], fname, lnum); } else if (is_aff_rule(items, itemcnt, "COMPOUNDROOT", 2) && aff->af_comproot == 0) { aff->af_comproot = affitem2flag(aff->af_flagtype, items[1], fname, lnum); } else if (is_aff_rule(items, itemcnt, "COMPOUNDFORBIDFLAG", 2) && aff->af_compforbid == 0) { aff->af_compforbid = affitem2flag(aff->af_flagtype, items[1], fname, lnum); if (aff->af_pref.ht_used > 0) smsg((char_u *)_("Defining COMPOUNDFORBIDFLAG after PFX item may give wrong results in %s line %d"), fname, lnum); } else if (is_aff_rule(items, itemcnt, "COMPOUNDPERMITFLAG", 2) && aff->af_comppermit == 0) { aff->af_comppermit = affitem2flag(aff->af_flagtype, items[1], fname, lnum); if (aff->af_pref.ht_used > 0) smsg((char_u *)_("Defining COMPOUNDPERMITFLAG after PFX item may give wrong results in %s line %d"), fname, lnum); } else if (is_aff_rule(items, itemcnt, "COMPOUNDFLAG", 2) && compflags == NULL) { /* Turn flag "c" into COMPOUNDRULE compatible string "c+", * "Na" into "Na+", "1234" into "1234+". */ p = getroom(spin, STRLEN(items[1]) + 2, FALSE); if (p != NULL) { STRCPY(p, items[1]); STRCAT(p, "+"); compflags = p; } } else if (is_aff_rule(items, itemcnt, "COMPOUNDRULES", 2)) { /* We don't use the count, but do check that it's a number and * not COMPOUNDRULE mistyped. */ if (atoi((char *)items[1]) == 0) smsg((char_u *)_("Wrong COMPOUNDRULES value in %s line %d: %s"), fname, lnum, items[1]); } else if (is_aff_rule(items, itemcnt, "COMPOUNDRULE", 2)) { /* Don't use the first rule if it is a number. */ if (compflags != NULL || *skipdigits(items[1]) != NUL) { /* Concatenate this string to previously defined ones, * using a slash to separate them. */ l = (int)STRLEN(items[1]) + 1; if (compflags != NULL) l += (int)STRLEN(compflags) + 1; p = getroom(spin, l, FALSE); if (p != NULL) { if (compflags != NULL) { STRCPY(p, compflags); STRCAT(p, "/"); } STRCAT(p, items[1]); compflags = p; } } } else if (is_aff_rule(items, itemcnt, "COMPOUNDWORDMAX", 2) && compmax == 0) { compmax = atoi((char *)items[1]); if (compmax == 0) smsg((char_u *)_("Wrong COMPOUNDWORDMAX value in %s line %d: %s"), fname, lnum, items[1]); } else if (is_aff_rule(items, itemcnt, "COMPOUNDMIN", 2) && compminlen == 0) { compminlen = atoi((char *)items[1]); if (compminlen == 0) smsg((char_u *)_("Wrong COMPOUNDMIN value in %s line %d: %s"), fname, lnum, items[1]); } else if (is_aff_rule(items, itemcnt, "COMPOUNDSYLMAX", 2) && compsylmax == 0) { compsylmax = atoi((char *)items[1]); if (compsylmax == 0) smsg((char_u *)_("Wrong COMPOUNDSYLMAX value in %s line %d: %s"), fname, lnum, items[1]); } else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDDUP", 1)) { compoptions |= COMP_CHECKDUP; } else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDREP", 1)) { compoptions |= COMP_CHECKREP; } else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDCASE", 1)) { compoptions |= COMP_CHECKCASE; } else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDTRIPLE", 1)) { compoptions |= COMP_CHECKTRIPLE; } else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDPATTERN", 2)) { if (atoi((char *)items[1]) == 0) smsg((char_u *)_("Wrong CHECKCOMPOUNDPATTERN value in %s line %d: %s"), fname, lnum, items[1]); } else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDPATTERN", 3)) { garray_T *gap = &spin->si_comppat; int i; /* Only add the couple if it isn't already there. */ for (i = 0; i < gap->ga_len - 1; i += 2) if (STRCMP(((char_u **)(gap->ga_data))[i], items[1]) == 0 && STRCMP(((char_u **)(gap->ga_data))[i + 1], items[2]) == 0) break; if (i >= gap->ga_len && ga_grow(gap, 2) == OK) { ((char_u **)(gap->ga_data))[gap->ga_len++] = getroom_save(spin, items[1]); ((char_u **)(gap->ga_data))[gap->ga_len++] = getroom_save(spin, items[2]); } } else if (is_aff_rule(items, itemcnt, "SYLLABLE", 2) && syllable == NULL) { syllable = getroom_save(spin, items[1]); } else if (is_aff_rule(items, itemcnt, "NOBREAK", 1)) { spin->si_nobreak = TRUE; } else if (is_aff_rule(items, itemcnt, "NOSPLITSUGS", 1)) { spin->si_nosplitsugs = TRUE; } else if (is_aff_rule(items, itemcnt, "NOSUGFILE", 1)) { spin->si_nosugfile = TRUE; } else if (is_aff_rule(items, itemcnt, "PFXPOSTPONE", 1)) { aff->af_pfxpostpone = TRUE; } else if ((STRCMP(items[0], "PFX") == 0 || STRCMP(items[0], "SFX") == 0) && aff_todo == 0 && itemcnt >= 4) { int lasti = 4; char_u key[AH_KEY_LEN]; if (*items[0] == 'P') tp = &aff->af_pref; else tp = &aff->af_suff; /* Myspell allows the same affix name to be used multiple * times. The affix files that do this have an undocumented * "S" flag on all but the last block, thus we check for that * and store it in ah_follows. */ vim_strncpy(key, items[1], AH_KEY_LEN - 1); hi = hash_find(tp, key); if (!HASHITEM_EMPTY(hi)) { cur_aff = HI2AH(hi); if (cur_aff->ah_combine != (*items[2] == 'Y')) smsg((char_u *)_("Different combining flag in continued affix block in %s line %d: %s"), fname, lnum, items[1]); if (!cur_aff->ah_follows) smsg((char_u *)_("Duplicate affix in %s line %d: %s"), fname, lnum, items[1]); } else { /* New affix letter. */ cur_aff = (affheader_T *)getroom(spin, sizeof(affheader_T), TRUE); if (cur_aff == NULL) break; cur_aff->ah_flag = affitem2flag(aff->af_flagtype, items[1], fname, lnum); if (cur_aff->ah_flag == 0 || STRLEN(items[1]) >= AH_KEY_LEN) break; if (cur_aff->ah_flag == aff->af_bad || cur_aff->ah_flag == aff->af_rare || cur_aff->ah_flag == aff->af_keepcase || cur_aff->ah_flag == aff->af_needaffix || cur_aff->ah_flag == aff->af_circumfix || cur_aff->ah_flag == aff->af_nosuggest || cur_aff->ah_flag == aff->af_needcomp || cur_aff->ah_flag == aff->af_comproot) smsg((char_u *)_("Affix also used for BAD/RARE/KEEPCASE/NEEDAFFIX/NEEDCOMPOUND/NOSUGGEST in %s line %d: %s"), fname, lnum, items[1]); STRCPY(cur_aff->ah_key, items[1]); hash_add(tp, cur_aff->ah_key); cur_aff->ah_combine = (*items[2] == 'Y'); } /* Check for the "S" flag, which apparently means that another * block with the same affix name is following. */ if (itemcnt > lasti && STRCMP(items[lasti], "S") == 0) { ++lasti; cur_aff->ah_follows = TRUE; } else cur_aff->ah_follows = FALSE; /* Myspell allows extra text after the item, but that might * mean mistakes go unnoticed. Require a comment-starter. */ if (itemcnt > lasti && *items[lasti] != '#') smsg((char_u *)_(e_afftrailing), fname, lnum, items[lasti]); if (STRCMP(items[2], "Y") != 0 && STRCMP(items[2], "N") != 0) smsg((char_u *)_("Expected Y or N in %s line %d: %s"), fname, lnum, items[2]); if (*items[0] == 'P' && aff->af_pfxpostpone) { if (cur_aff->ah_newID == 0) { /* Use a new number in the .spl file later, to be able * to handle multiple .aff files. */ check_renumber(spin); cur_aff->ah_newID = ++spin->si_newprefID; /* We only really use ah_newID if the prefix is * postponed. We know that only after handling all * the items. */ did_postpone_prefix = FALSE; } else /* Did use the ID in a previous block. */ did_postpone_prefix = TRUE; } aff_todo = atoi((char *)items[3]); } else if ((STRCMP(items[0], "PFX") == 0 || STRCMP(items[0], "SFX") == 0) && aff_todo > 0 && STRCMP(cur_aff->ah_key, items[1]) == 0 && itemcnt >= 5) { affentry_T *aff_entry; int upper = FALSE; int lasti = 5; /* Myspell allows extra text after the item, but that might * mean mistakes go unnoticed. Require a comment-starter. * Hunspell uses a "-" item. */ if (itemcnt > lasti && *items[lasti] != '#' && (STRCMP(items[lasti], "-") != 0 || itemcnt != lasti + 1)) smsg((char_u *)_(e_afftrailing), fname, lnum, items[lasti]); /* New item for an affix letter. */ --aff_todo; aff_entry = (affentry_T *)getroom(spin, sizeof(affentry_T), TRUE); if (aff_entry == NULL) break; if (STRCMP(items[2], "0") != 0) aff_entry->ae_chop = getroom_save(spin, items[2]); if (STRCMP(items[3], "0") != 0) { aff_entry->ae_add = getroom_save(spin, items[3]); /* Recognize flags on the affix: abcd/XYZ */ aff_entry->ae_flags = vim_strchr(aff_entry->ae_add, '/'); if (aff_entry->ae_flags != NULL) { *aff_entry->ae_flags++ = NUL; aff_process_flags(aff, aff_entry); } } /* Don't use an affix entry with non-ASCII characters when * "spin->si_ascii" is TRUE. */ if (!spin->si_ascii || !(has_non_ascii(aff_entry->ae_chop) || has_non_ascii(aff_entry->ae_add))) { aff_entry->ae_next = cur_aff->ah_first; cur_aff->ah_first = aff_entry; if (STRCMP(items[4], ".") != 0) { char_u buf[MAXLINELEN]; aff_entry->ae_cond = getroom_save(spin, items[4]); if (*items[0] == 'P') sprintf((char *)buf, "^%s", items[4]); else sprintf((char *)buf, "%s$", items[4]); aff_entry->ae_prog = vim_regcomp(buf, RE_MAGIC + RE_STRING + RE_STRICT); if (aff_entry->ae_prog == NULL) smsg((char_u *)_("Broken condition in %s line %d: %s"), fname, lnum, items[4]); } /* For postponed prefixes we need an entry in si_prefcond * for the condition. Use an existing one if possible. * Can't be done for an affix with flags, ignoring * COMPOUNDFORBIDFLAG and COMPOUNDPERMITFLAG. */ if (*items[0] == 'P' && aff->af_pfxpostpone && aff_entry->ae_flags == NULL) { /* When the chop string is one lower-case letter and * the add string ends in the upper-case letter we set * the "upper" flag, clear "ae_chop" and remove the * letters from "ae_add". The condition must either * be empty or start with the same letter. */ if (aff_entry->ae_chop != NULL && aff_entry->ae_add != NULL #ifdef FEAT_MBYTE && aff_entry->ae_chop[(*mb_ptr2len)( aff_entry->ae_chop)] == NUL #else && aff_entry->ae_chop[1] == NUL #endif ) { int c, c_up; c = PTR2CHAR(aff_entry->ae_chop); c_up = SPELL_TOUPPER(c); if (c_up != c && (aff_entry->ae_cond == NULL || PTR2CHAR(aff_entry->ae_cond) == c)) { p = aff_entry->ae_add + STRLEN(aff_entry->ae_add); mb_ptr_back(aff_entry->ae_add, p); if (PTR2CHAR(p) == c_up) { upper = TRUE; aff_entry->ae_chop = NULL; *p = NUL; /* The condition is matched with the * actual word, thus must check for the * upper-case letter. */ if (aff_entry->ae_cond != NULL) { char_u buf[MAXLINELEN]; #ifdef FEAT_MBYTE if (has_mbyte) { onecap_copy(items[4], buf, TRUE); aff_entry->ae_cond = getroom_save( spin, buf); } else #endif *aff_entry->ae_cond = c_up; if (aff_entry->ae_cond != NULL) { sprintf((char *)buf, "^%s", aff_entry->ae_cond); vim_free(aff_entry->ae_prog); aff_entry->ae_prog = vim_regcomp( buf, RE_MAGIC + RE_STRING); } } } } } if (aff_entry->ae_chop == NULL && aff_entry->ae_flags == NULL) { int idx; char_u **pp; int n; /* Find a previously used condition. */ for (idx = spin->si_prefcond.ga_len - 1; idx >= 0; --idx) { p = ((char_u **)spin->si_prefcond.ga_data)[idx]; if (str_equal(p, aff_entry->ae_cond)) break; } if (idx < 0 && ga_grow(&spin->si_prefcond, 1) == OK) { /* Not found, add a new condition. */ idx = spin->si_prefcond.ga_len++; pp = ((char_u **)spin->si_prefcond.ga_data) + idx; if (aff_entry->ae_cond == NULL) *pp = NULL; else *pp = getroom_save(spin, aff_entry->ae_cond); } /* Add the prefix to the prefix tree. */ if (aff_entry->ae_add == NULL) p = (char_u *)""; else p = aff_entry->ae_add; /* PFX_FLAGS is a negative number, so that * tree_add_word() knows this is the prefix tree. */ n = PFX_FLAGS; if (!cur_aff->ah_combine) n |= WFP_NC; if (upper) n |= WFP_UP; if (aff_entry->ae_comppermit) n |= WFP_COMPPERMIT; if (aff_entry->ae_compforbid) n |= WFP_COMPFORBID; tree_add_word(spin, p, spin->si_prefroot, n, idx, cur_aff->ah_newID); did_postpone_prefix = TRUE; } /* Didn't actually use ah_newID, backup si_newprefID. */ if (aff_todo == 0 && !did_postpone_prefix) { --spin->si_newprefID; cur_aff->ah_newID = 0; } } } } else if (is_aff_rule(items, itemcnt, "FOL", 2) && fol == NULL) { fol = vim_strsave(items[1]); } else if (is_aff_rule(items, itemcnt, "LOW", 2) && low == NULL) { low = vim_strsave(items[1]); } else if (is_aff_rule(items, itemcnt, "UPP", 2) && upp == NULL) { upp = vim_strsave(items[1]); } else if (is_aff_rule(items, itemcnt, "REP", 2) || is_aff_rule(items, itemcnt, "REPSAL", 2)) { /* Ignore REP/REPSAL count */; if (!isdigit(*items[1])) smsg((char_u *)_("Expected REP(SAL) count in %s line %d"), fname, lnum); } else if ((STRCMP(items[0], "REP") == 0 || STRCMP(items[0], "REPSAL") == 0) && itemcnt >= 3) { /* REP/REPSAL item */ /* Myspell ignores extra arguments, we require it starts with * # to detect mistakes. */ if (itemcnt > 3 && items[3][0] != '#') smsg((char_u *)_(e_afftrailing), fname, lnum, items[3]); if (items[0][3] == 'S' ? do_repsal : do_rep) { /* Replace underscore with space (can't include a space * directly). */ for (p = items[1]; *p != NUL; mb_ptr_adv(p)) if (*p == '_') *p = ' '; for (p = items[2]; *p != NUL; mb_ptr_adv(p)) if (*p == '_') *p = ' '; add_fromto(spin, items[0][3] == 'S' ? &spin->si_repsal : &spin->si_rep, items[1], items[2]); } } else if (is_aff_rule(items, itemcnt, "MAP", 2)) { /* MAP item or count */ if (!found_map) { /* First line contains the count. */ found_map = TRUE; if (!isdigit(*items[1])) smsg((char_u *)_("Expected MAP count in %s line %d"), fname, lnum); } else if (do_mapline) { int c; /* Check that every character appears only once. */ for (p = items[1]; *p != NUL; ) { #ifdef FEAT_MBYTE c = mb_ptr2char_adv(&p); #else c = *p++; #endif if ((spin->si_map.ga_len > 0 && vim_strchr(spin->si_map.ga_data, c) != NULL) || vim_strchr(p, c) != NULL) smsg((char_u *)_("Duplicate character in MAP in %s line %d"), fname, lnum); } /* We simply concatenate all the MAP strings, separated by * slashes. */ ga_concat(&spin->si_map, items[1]); ga_append(&spin->si_map, '/'); } } /* Accept "SAL from to" and "SAL from to #comment". */ else if (is_aff_rule(items, itemcnt, "SAL", 3)) { if (do_sal) { /* SAL item (sounds-a-like) * Either one of the known keys or a from-to pair. */ if (STRCMP(items[1], "followup") == 0) spin->si_followup = sal_to_bool(items[2]); else if (STRCMP(items[1], "collapse_result") == 0) spin->si_collapse = sal_to_bool(items[2]); else if (STRCMP(items[1], "remove_accents") == 0) spin->si_rem_accents = sal_to_bool(items[2]); else /* when "to" is "_" it means empty */ add_fromto(spin, &spin->si_sal, items[1], STRCMP(items[2], "_") == 0 ? (char_u *)"" : items[2]); } } else if (is_aff_rule(items, itemcnt, "SOFOFROM", 2) && sofofrom == NULL) { sofofrom = getroom_save(spin, items[1]); } else if (is_aff_rule(items, itemcnt, "SOFOTO", 2) && sofoto == NULL) { sofoto = getroom_save(spin, items[1]); } else if (STRCMP(items[0], "COMMON") == 0) { int i; for (i = 1; i < itemcnt; ++i) { if (HASHITEM_EMPTY(hash_find(&spin->si_commonwords, items[i]))) { p = vim_strsave(items[i]); if (p == NULL) break; hash_add(&spin->si_commonwords, p); } } } else smsg((char_u *)_("Unrecognized or duplicate item in %s line %d: %s"), fname, lnum, items[0]); } } if (fol != NULL || low != NULL || upp != NULL) { if (spin->si_clear_chartab) { /* Clear the char type tables, don't want to use any of the * currently used spell properties. */ init_spell_chartab(); spin->si_clear_chartab = FALSE; } /* * Don't write a word table for an ASCII file, so that we don't check * for conflicts with a word table that matches 'encoding'. * Don't write one for utf-8 either, we use utf_*() and * mb_get_class(), the list of chars in the file will be incomplete. */ if (!spin->si_ascii #ifdef FEAT_MBYTE && !enc_utf8 #endif ) { if (fol == NULL || low == NULL || upp == NULL) smsg((char_u *)_("Missing FOL/LOW/UPP line in %s"), fname); else (void)set_spell_chartab(fol, low, upp); } vim_free(fol); vim_free(low); vim_free(upp); } /* Use compound specifications of the .aff file for the spell info. */ if (compmax != 0) { aff_check_number(spin->si_compmax, compmax, "COMPOUNDWORDMAX"); spin->si_compmax = compmax; } if (compminlen != 0) { aff_check_number(spin->si_compminlen, compminlen, "COMPOUNDMIN"); spin->si_compminlen = compminlen; } if (compsylmax != 0) { if (syllable == NULL) smsg((char_u *)_("COMPOUNDSYLMAX used without SYLLABLE")); aff_check_number(spin->si_compsylmax, compsylmax, "COMPOUNDSYLMAX"); spin->si_compsylmax = compsylmax; } if (compoptions != 0) { aff_check_number(spin->si_compoptions, compoptions, "COMPOUND options"); spin->si_compoptions |= compoptions; } if (compflags != NULL) process_compflags(spin, aff, compflags); /* Check that we didn't use too many renumbered flags. */ if (spin->si_newcompID < spin->si_newprefID) { if (spin->si_newcompID == 127 || spin->si_newcompID == 255) MSG(_("Too many postponed prefixes")); else if (spin->si_newprefID == 0 || spin->si_newprefID == 127) MSG(_("Too many compound flags")); else MSG(_("Too many postponed prefixes and/or compound flags")); } if (syllable != NULL) { aff_check_string(spin->si_syllable, syllable, "SYLLABLE"); spin->si_syllable = syllable; } if (sofofrom != NULL || sofoto != NULL) { if (sofofrom == NULL || sofoto == NULL) smsg((char_u *)_("Missing SOFO%s line in %s"), sofofrom == NULL ? "FROM" : "TO", fname); else if (spin->si_sal.ga_len > 0) smsg((char_u *)_("Both SAL and SOFO lines in %s"), fname); else { aff_check_string(spin->si_sofofr, sofofrom, "SOFOFROM"); aff_check_string(spin->si_sofoto, sofoto, "SOFOTO"); spin->si_sofofr = sofofrom; spin->si_sofoto = sofoto; } } if (midword != NULL) { aff_check_string(spin->si_midword, midword, "MIDWORD"); spin->si_midword = midword; } vim_free(pc); fclose(fd); return aff; } /* * Return TRUE when items[0] equals "rulename", there are "mincount" items or * a comment is following after item "mincount". */ static int is_aff_rule(items, itemcnt, rulename, mincount) char_u **items; int itemcnt; char *rulename; int mincount; { return (STRCMP(items[0], rulename) == 0 && (itemcnt == mincount || (itemcnt > mincount && items[mincount][0] == '#'))); } /* * For affix "entry" move COMPOUNDFORBIDFLAG and COMPOUNDPERMITFLAG from * ae_flags to ae_comppermit and ae_compforbid. */ static void aff_process_flags(affile, entry) afffile_T *affile; affentry_T *entry; { char_u *p; char_u *prevp; unsigned flag; if (entry->ae_flags != NULL && (affile->af_compforbid != 0 || affile->af_comppermit != 0)) { for (p = entry->ae_flags; *p != NUL; ) { prevp = p; flag = get_affitem(affile->af_flagtype, &p); if (flag == affile->af_comppermit || flag == affile->af_compforbid) { STRMOVE(prevp, p); p = prevp; if (flag == affile->af_comppermit) entry->ae_comppermit = TRUE; else entry->ae_compforbid = TRUE; } if (affile->af_flagtype == AFT_NUM && *p == ',') ++p; } if (*entry->ae_flags == NUL) entry->ae_flags = NULL; /* nothing left */ } } /* * Return TRUE if "s" is the name of an info item in the affix file. */ static int spell_info_item(s) char_u *s; { return STRCMP(s, "NAME") == 0 || STRCMP(s, "HOME") == 0 || STRCMP(s, "VERSION") == 0 || STRCMP(s, "AUTHOR") == 0 || STRCMP(s, "EMAIL") == 0 || STRCMP(s, "COPYRIGHT") == 0; } /* * Turn an affix flag name into a number, according to the FLAG type. * returns zero for failure. */ static unsigned affitem2flag(flagtype, item, fname, lnum) int flagtype; char_u *item; char_u *fname; int lnum; { unsigned res; char_u *p = item; res = get_affitem(flagtype, &p); if (res == 0) { if (flagtype == AFT_NUM) smsg((char_u *)_("Flag is not a number in %s line %d: %s"), fname, lnum, item); else smsg((char_u *)_("Illegal flag in %s line %d: %s"), fname, lnum, item); } if (*p != NUL) { smsg((char_u *)_(e_affname), fname, lnum, item); return 0; } return res; } /* * Get one affix name from "*pp" and advance the pointer. * Returns zero for an error, still advances the pointer then. */ static unsigned get_affitem(flagtype, pp) int flagtype; char_u **pp; { int res; if (flagtype == AFT_NUM) { if (!VIM_ISDIGIT(**pp)) { ++*pp; /* always advance, avoid getting stuck */ return 0; } res = getdigits(pp); } else { #ifdef FEAT_MBYTE res = mb_ptr2char_adv(pp); #else res = *(*pp)++; #endif if (flagtype == AFT_LONG || (flagtype == AFT_CAPLONG && res >= 'A' && res <= 'Z')) { if (**pp == NUL) return 0; #ifdef FEAT_MBYTE res = mb_ptr2char_adv(pp) + (res << 16); #else res = *(*pp)++ + (res << 16); #endif } } return res; } /* * Process the "compflags" string used in an affix file and append it to * spin->si_compflags. * The processing involves changing the affix names to ID numbers, so that * they fit in one byte. */ static void process_compflags(spin, aff, compflags) spellinfo_T *spin; afffile_T *aff; char_u *compflags; { char_u *p; char_u *prevp; unsigned flag; compitem_T *ci; int id; int len; char_u *tp; char_u key[AH_KEY_LEN]; hashitem_T *hi; /* Make room for the old and the new compflags, concatenated with a / in * between. Processing it makes it shorter, but we don't know by how * much, thus allocate the maximum. */ len = (int)STRLEN(compflags) + 1; if (spin->si_compflags != NULL) len += (int)STRLEN(spin->si_compflags) + 1; p = getroom(spin, len, FALSE); if (p == NULL) return; if (spin->si_compflags != NULL) { STRCPY(p, spin->si_compflags); STRCAT(p, "/"); } spin->si_compflags = p; tp = p + STRLEN(p); for (p = compflags; *p != NUL; ) { if (vim_strchr((char_u *)"/?*+[]", *p) != NULL) /* Copy non-flag characters directly. */ *tp++ = *p++; else { /* First get the flag number, also checks validity. */ prevp = p; flag = get_affitem(aff->af_flagtype, &p); if (flag != 0) { /* Find the flag in the hashtable. If it was used before, use * the existing ID. Otherwise add a new entry. */ vim_strncpy(key, prevp, p - prevp); hi = hash_find(&aff->af_comp, key); if (!HASHITEM_EMPTY(hi)) id = HI2CI(hi)->ci_newID; else { ci = (compitem_T *)getroom(spin, sizeof(compitem_T), TRUE); if (ci == NULL) break; STRCPY(ci->ci_key, key); ci->ci_flag = flag; /* Avoid using a flag ID that has a special meaning in a * regexp (also inside []). */ do { check_renumber(spin); id = spin->si_newcompID--; } while (vim_strchr((char_u *)"/?*+[]\\-^", id) != NULL); ci->ci_newID = id; hash_add(&aff->af_comp, ci->ci_key); } *tp++ = id; } if (aff->af_flagtype == AFT_NUM && *p == ',') ++p; } } *tp = NUL; } /* * Check that the new IDs for postponed affixes and compounding don't overrun * each other. We have almost 255 available, but start at 0-127 to avoid * using two bytes for utf-8. When the 0-127 range is used up go to 128-255. * When that is used up an error message is given. */ static void check_renumber(spin) spellinfo_T *spin; { if (spin->si_newprefID == spin->si_newcompID && spin->si_newcompID < 128) { spin->si_newprefID = 127; spin->si_newcompID = 255; } } /* * Return TRUE if flag "flag" appears in affix list "afflist". */ static int flag_in_afflist(flagtype, afflist, flag) int flagtype; char_u *afflist; unsigned flag; { char_u *p; unsigned n; switch (flagtype) { case AFT_CHAR: return vim_strchr(afflist, flag) != NULL; case AFT_CAPLONG: case AFT_LONG: for (p = afflist; *p != NUL; ) { #ifdef FEAT_MBYTE n = mb_ptr2char_adv(&p); #else n = *p++; #endif if ((flagtype == AFT_LONG || (n >= 'A' && n <= 'Z')) && *p != NUL) #ifdef FEAT_MBYTE n = mb_ptr2char_adv(&p) + (n << 16); #else n = *p++ + (n << 16); #endif if (n == flag) return TRUE; } break; case AFT_NUM: for (p = afflist; *p != NUL; ) { n = getdigits(&p); if (n == flag) return TRUE; if (*p != NUL) /* skip over comma */ ++p; } break; } return FALSE; } /* * Give a warning when "spinval" and "affval" numbers are set and not the same. */ static void aff_check_number(spinval, affval, name) int spinval; int affval; char *name; { if (spinval != 0 && spinval != affval) smsg((char_u *)_("%s value differs from what is used in another .aff file"), name); } /* * Give a warning when "spinval" and "affval" strings are set and not the same. */ static void aff_check_string(spinval, affval, name) char_u *spinval; char_u *affval; char *name; { if (spinval != NULL && STRCMP(spinval, affval) != 0) smsg((char_u *)_("%s value differs from what is used in another .aff file"), name); } /* * Return TRUE if strings "s1" and "s2" are equal. Also consider both being * NULL as equal. */ static int str_equal(s1, s2) char_u *s1; char_u *s2; { if (s1 == NULL || s2 == NULL) return s1 == s2; return STRCMP(s1, s2) == 0; } /* * Add a from-to item to "gap". Used for REP and SAL items. * They are stored case-folded. */ static void add_fromto(spin, gap, from, to) spellinfo_T *spin; garray_T *gap; char_u *from; char_u *to; { fromto_T *ftp; char_u word[MAXWLEN]; if (ga_grow(gap, 1) == OK) { ftp = ((fromto_T *)gap->ga_data) + gap->ga_len; (void)spell_casefold(from, (int)STRLEN(from), word, MAXWLEN); ftp->ft_from = getroom_save(spin, word); (void)spell_casefold(to, (int)STRLEN(to), word, MAXWLEN); ftp->ft_to = getroom_save(spin, word); ++gap->ga_len; } } /* * Convert a boolean argument in a SAL line to TRUE or FALSE; */ static int sal_to_bool(s) char_u *s; { return STRCMP(s, "1") == 0 || STRCMP(s, "true") == 0; } /* * Free the structure filled by spell_read_aff(). */ static void spell_free_aff(aff) afffile_T *aff; { hashtab_T *ht; hashitem_T *hi; int todo; affheader_T *ah; affentry_T *ae; vim_free(aff->af_enc); /* All this trouble to free the "ae_prog" items... */ for (ht = &aff->af_pref; ; ht = &aff->af_suff) { todo = (int)ht->ht_used; for (hi = ht->ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; ah = HI2AH(hi); for (ae = ah->ah_first; ae != NULL; ae = ae->ae_next) vim_free(ae->ae_prog); } } if (ht == &aff->af_suff) break; } hash_clear(&aff->af_pref); hash_clear(&aff->af_suff); hash_clear(&aff->af_comp); } /* * Read dictionary file "fname". * Returns OK or FAIL; */ static int spell_read_dic(spin, fname, affile) spellinfo_T *spin; char_u *fname; afffile_T *affile; { hashtab_T ht; char_u line[MAXLINELEN]; char_u *p; char_u *afflist; char_u store_afflist[MAXWLEN]; int pfxlen; int need_affix; char_u *dw; char_u *pc; char_u *w; int l; hash_T hash; hashitem_T *hi; FILE *fd; int lnum = 1; int non_ascii = 0; int retval = OK; char_u message[MAXLINELEN + MAXWLEN]; int flags; int duplicate = 0; /* * Open the file. */ fd = mch_fopen((char *)fname, "r"); if (fd == NULL) { EMSG2(_(e_notopen), fname); return FAIL; } /* The hashtable is only used to detect duplicated words. */ hash_init(&ht); vim_snprintf((char *)IObuff, IOSIZE, _("Reading dictionary file %s ..."), fname); spell_message(spin, IObuff); /* start with a message for the first line */ spin->si_msg_count = 999999; /* Read and ignore the first line: word count. */ (void)vim_fgets(line, MAXLINELEN, fd); if (!vim_isdigit(*skipwhite(line))) EMSG2(_("E760: No word count in %s"), fname); /* * Read all the lines in the file one by one. * The words are converted to 'encoding' here, before being added to * the hashtable. */ while (!vim_fgets(line, MAXLINELEN, fd) && !got_int) { line_breakcheck(); ++lnum; if (line[0] == '#' || line[0] == '/') continue; /* comment line */ /* Remove CR, LF and white space from the end. White space halfway * the word is kept to allow e.g., "et al.". */ l = (int)STRLEN(line); while (l > 0 && line[l - 1] <= ' ') --l; if (l == 0) continue; /* empty line */ line[l] = NUL; #ifdef FEAT_MBYTE /* Convert from "SET" to 'encoding' when needed. */ if (spin->si_conv.vc_type != CONV_NONE) { pc = string_convert(&spin->si_conv, line, NULL); if (pc == NULL) { smsg((char_u *)_("Conversion failure for word in %s line %d: %s"), fname, lnum, line); continue; } w = pc; } else #endif { pc = NULL; w = line; } /* Truncate the word at the "/", set "afflist" to what follows. * Replace "\/" by "/" and "\\" by "\". */ afflist = NULL; for (p = w; *p != NUL; mb_ptr_adv(p)) { if (*p == '\\' && (p[1] == '\\' || p[1] == '/')) STRMOVE(p, p + 1); else if (*p == '/') { *p = NUL; afflist = p + 1; break; } } /* Skip non-ASCII words when "spin->si_ascii" is TRUE. */ if (spin->si_ascii && has_non_ascii(w)) { ++non_ascii; vim_free(pc); continue; } /* This takes time, print a message every 10000 words. */ if (spin->si_verbose && spin->si_msg_count > 10000) { spin->si_msg_count = 0; vim_snprintf((char *)message, sizeof(message), _("line %6d, word %6d - %s"), lnum, spin->si_foldwcount + spin->si_keepwcount, w); msg_start(); msg_puts_long_attr(message, 0); msg_clr_eos(); msg_didout = FALSE; msg_col = 0; out_flush(); } /* Store the word in the hashtable to be able to find duplicates. */ dw = (char_u *)getroom_save(spin, w); if (dw == NULL) { retval = FAIL; vim_free(pc); break; } hash = hash_hash(dw); hi = hash_lookup(&ht, dw, hash); if (!HASHITEM_EMPTY(hi)) { if (p_verbose > 0) smsg((char_u *)_("Duplicate word in %s line %d: %s"), fname, lnum, dw); else if (duplicate == 0) smsg((char_u *)_("First duplicate word in %s line %d: %s"), fname, lnum, dw); ++duplicate; } else hash_add_item(&ht, hi, dw, hash); flags = 0; store_afflist[0] = NUL; pfxlen = 0; need_affix = FALSE; if (afflist != NULL) { /* Extract flags from the affix list. */ flags |= get_affix_flags(affile, afflist); if (affile->af_needaffix != 0 && flag_in_afflist( affile->af_flagtype, afflist, affile->af_needaffix)) need_affix = TRUE; if (affile->af_pfxpostpone) /* Need to store the list of prefix IDs with the word. */ pfxlen = get_pfxlist(affile, afflist, store_afflist); if (spin->si_compflags != NULL) /* Need to store the list of compound flags with the word. * Concatenate them to the list of prefix IDs. */ get_compflags(affile, afflist, store_afflist + pfxlen); } /* Add the word to the word tree(s). */ if (store_word(spin, dw, flags, spin->si_region, store_afflist, need_affix) == FAIL) retval = FAIL; if (afflist != NULL) { /* Find all matching suffixes and add the resulting words. * Additionally do matching prefixes that combine. */ if (store_aff_word(spin, dw, afflist, affile, &affile->af_suff, &affile->af_pref, CONDIT_SUF, flags, store_afflist, pfxlen) == FAIL) retval = FAIL; /* Find all matching prefixes and add the resulting words. */ if (store_aff_word(spin, dw, afflist, affile, &affile->af_pref, NULL, CONDIT_SUF, flags, store_afflist, pfxlen) == FAIL) retval = FAIL; } vim_free(pc); } if (duplicate > 0) smsg((char_u *)_("%d duplicate word(s) in %s"), duplicate, fname); if (spin->si_ascii && non_ascii > 0) smsg((char_u *)_("Ignored %d word(s) with non-ASCII characters in %s"), non_ascii, fname); hash_clear(&ht); fclose(fd); return retval; } /* * Check for affix flags in "afflist" that are turned into word flags. * Return WF_ flags. */ static int get_affix_flags(affile, afflist) afffile_T *affile; char_u *afflist; { int flags = 0; if (affile->af_keepcase != 0 && flag_in_afflist( affile->af_flagtype, afflist, affile->af_keepcase)) flags |= WF_KEEPCAP | WF_FIXCAP; if (affile->af_rare != 0 && flag_in_afflist( affile->af_flagtype, afflist, affile->af_rare)) flags |= WF_RARE; if (affile->af_bad != 0 && flag_in_afflist( affile->af_flagtype, afflist, affile->af_bad)) flags |= WF_BANNED; if (affile->af_needcomp != 0 && flag_in_afflist( affile->af_flagtype, afflist, affile->af_needcomp)) flags |= WF_NEEDCOMP; if (affile->af_comproot != 0 && flag_in_afflist( affile->af_flagtype, afflist, affile->af_comproot)) flags |= WF_COMPROOT; if (affile->af_nosuggest != 0 && flag_in_afflist( affile->af_flagtype, afflist, affile->af_nosuggest)) flags |= WF_NOSUGGEST; return flags; } /* * Get the list of prefix IDs from the affix list "afflist". * Used for PFXPOSTPONE. * Put the resulting flags in "store_afflist[MAXWLEN]" with a terminating NUL * and return the number of affixes. */ static int get_pfxlist(affile, afflist, store_afflist) afffile_T *affile; char_u *afflist; char_u *store_afflist; { char_u *p; char_u *prevp; int cnt = 0; int id; char_u key[AH_KEY_LEN]; hashitem_T *hi; for (p = afflist; *p != NUL; ) { prevp = p; if (get_affitem(affile->af_flagtype, &p) != 0) { /* A flag is a postponed prefix flag if it appears in "af_pref" * and it's ID is not zero. */ vim_strncpy(key, prevp, p - prevp); hi = hash_find(&affile->af_pref, key); if (!HASHITEM_EMPTY(hi)) { id = HI2AH(hi)->ah_newID; if (id != 0) store_afflist[cnt++] = id; } } if (affile->af_flagtype == AFT_NUM && *p == ',') ++p; } store_afflist[cnt] = NUL; return cnt; } /* * Get the list of compound IDs from the affix list "afflist" that are used * for compound words. * Puts the flags in "store_afflist[]". */ static void get_compflags(affile, afflist, store_afflist) afffile_T *affile; char_u *afflist; char_u *store_afflist; { char_u *p; char_u *prevp; int cnt = 0; char_u key[AH_KEY_LEN]; hashitem_T *hi; for (p = afflist; *p != NUL; ) { prevp = p; if (get_affitem(affile->af_flagtype, &p) != 0) { /* A flag is a compound flag if it appears in "af_comp". */ vim_strncpy(key, prevp, p - prevp); hi = hash_find(&affile->af_comp, key); if (!HASHITEM_EMPTY(hi)) store_afflist[cnt++] = HI2CI(hi)->ci_newID; } if (affile->af_flagtype == AFT_NUM && *p == ',') ++p; } store_afflist[cnt] = NUL; } /* * Apply affixes to a word and store the resulting words. * "ht" is the hashtable with affentry_T that need to be applied, either * prefixes or suffixes. * "xht", when not NULL, is the prefix hashtable, to be used additionally on * the resulting words for combining affixes. * * Returns FAIL when out of memory. */ static int store_aff_word(spin, word, afflist, affile, ht, xht, condit, flags, pfxlist, pfxlen) spellinfo_T *spin; /* spell info */ char_u *word; /* basic word start */ char_u *afflist; /* list of names of supported affixes */ afffile_T *affile; hashtab_T *ht; hashtab_T *xht; int condit; /* CONDIT_SUF et al. */ int flags; /* flags for the word */ char_u *pfxlist; /* list of prefix IDs */ int pfxlen; /* nr of flags in "pfxlist" for prefixes, rest * is compound flags */ { int todo; hashitem_T *hi; affheader_T *ah; affentry_T *ae; regmatch_T regmatch; char_u newword[MAXWLEN]; int retval = OK; int i, j; char_u *p; int use_flags; char_u *use_pfxlist; int use_pfxlen; int need_affix; char_u store_afflist[MAXWLEN]; char_u pfx_pfxlist[MAXWLEN]; size_t wordlen = STRLEN(word); int use_condit; todo = (int)ht->ht_used; for (hi = ht->ht_array; todo > 0 && retval == OK; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; ah = HI2AH(hi); /* Check that the affix combines, if required, and that the word * supports this affix. */ if (((condit & CONDIT_COMB) == 0 || ah->ah_combine) && flag_in_afflist(affile->af_flagtype, afflist, ah->ah_flag)) { /* Loop over all affix entries with this name. */ for (ae = ah->ah_first; ae != NULL; ae = ae->ae_next) { /* Check the condition. It's not logical to match case * here, but it is required for compatibility with * Myspell. * Another requirement from Myspell is that the chop * string is shorter than the word itself. * For prefixes, when "PFXPOSTPONE" was used, only do * prefixes with a chop string and/or flags. * When a previously added affix had CIRCUMFIX this one * must have it too, if it had not then this one must not * have one either. */ regmatch.regprog = ae->ae_prog; regmatch.rm_ic = FALSE; if ((xht != NULL || !affile->af_pfxpostpone || ae->ae_chop != NULL || ae->ae_flags != NULL) && (ae->ae_chop == NULL || STRLEN(ae->ae_chop) < wordlen) && (ae->ae_prog == NULL || vim_regexec(&regmatch, word, (colnr_T)0)) && (((condit & CONDIT_CFIX) == 0) == ((condit & CONDIT_AFF) == 0 || ae->ae_flags == NULL || !flag_in_afflist(affile->af_flagtype, ae->ae_flags, affile->af_circumfix)))) { /* Match. Remove the chop and add the affix. */ if (xht == NULL) { /* prefix: chop/add at the start of the word */ if (ae->ae_add == NULL) *newword = NUL; else vim_strncpy(newword, ae->ae_add, MAXWLEN - 1); p = word; if (ae->ae_chop != NULL) { /* Skip chop string. */ #ifdef FEAT_MBYTE if (has_mbyte) { i = mb_charlen(ae->ae_chop); for ( ; i > 0; --i) mb_ptr_adv(p); } else #endif p += STRLEN(ae->ae_chop); } STRCAT(newword, p); } else { /* suffix: chop/add at the end of the word */ vim_strncpy(newword, word, MAXWLEN - 1); if (ae->ae_chop != NULL) { /* Remove chop string. */ p = newword + STRLEN(newword); i = (int)MB_CHARLEN(ae->ae_chop); for ( ; i > 0; --i) mb_ptr_back(newword, p); *p = NUL; } if (ae->ae_add != NULL) STRCAT(newword, ae->ae_add); } use_flags = flags; use_pfxlist = pfxlist; use_pfxlen = pfxlen; need_affix = FALSE; use_condit = condit | CONDIT_COMB | CONDIT_AFF; if (ae->ae_flags != NULL) { /* Extract flags from the affix list. */ use_flags |= get_affix_flags(affile, ae->ae_flags); if (affile->af_needaffix != 0 && flag_in_afflist( affile->af_flagtype, ae->ae_flags, affile->af_needaffix)) need_affix = TRUE; /* When there is a CIRCUMFIX flag the other affix * must also have it and we don't add the word * with one affix. */ if (affile->af_circumfix != 0 && flag_in_afflist( affile->af_flagtype, ae->ae_flags, affile->af_circumfix)) { use_condit |= CONDIT_CFIX; if ((condit & CONDIT_CFIX) == 0) need_affix = TRUE; } if (affile->af_pfxpostpone || spin->si_compflags != NULL) { if (affile->af_pfxpostpone) /* Get prefix IDS from the affix list. */ use_pfxlen = get_pfxlist(affile, ae->ae_flags, store_afflist); else use_pfxlen = 0; use_pfxlist = store_afflist; /* Combine the prefix IDs. Avoid adding the * same ID twice. */ for (i = 0; i < pfxlen; ++i) { for (j = 0; j < use_pfxlen; ++j) if (pfxlist[i] == use_pfxlist[j]) break; if (j == use_pfxlen) use_pfxlist[use_pfxlen++] = pfxlist[i]; } if (spin->si_compflags != NULL) /* Get compound IDS from the affix list. */ get_compflags(affile, ae->ae_flags, use_pfxlist + use_pfxlen); /* Combine the list of compound flags. * Concatenate them to the prefix IDs list. * Avoid adding the same ID twice. */ for (i = pfxlen; pfxlist[i] != NUL; ++i) { for (j = use_pfxlen; use_pfxlist[j] != NUL; ++j) if (pfxlist[i] == use_pfxlist[j]) break; if (use_pfxlist[j] == NUL) { use_pfxlist[j++] = pfxlist[i]; use_pfxlist[j] = NUL; } } } } /* Obey a "COMPOUNDFORBIDFLAG" of the affix: don't * use the compound flags. */ if (use_pfxlist != NULL && ae->ae_compforbid) { vim_strncpy(pfx_pfxlist, use_pfxlist, use_pfxlen); use_pfxlist = pfx_pfxlist; } /* When there are postponed prefixes... */ if (spin->si_prefroot != NULL && spin->si_prefroot->wn_sibling != NULL) { /* ... add a flag to indicate an affix was used. */ use_flags |= WF_HAS_AFF; /* ... don't use a prefix list if combining * affixes is not allowed. But do use the * compound flags after them. */ if (!ah->ah_combine && use_pfxlist != NULL) use_pfxlist += use_pfxlen; } /* When compounding is supported and there is no * "COMPOUNDPERMITFLAG" then forbid compounding on the * side where the affix is applied. */ if (spin->si_compflags != NULL && !ae->ae_comppermit) { if (xht != NULL) use_flags |= WF_NOCOMPAFT; else use_flags |= WF_NOCOMPBEF; } /* Store the modified word. */ if (store_word(spin, newword, use_flags, spin->si_region, use_pfxlist, need_affix) == FAIL) retval = FAIL; /* When added a prefix or a first suffix and the affix * has flags may add a(nother) suffix. RECURSIVE! */ if ((condit & CONDIT_SUF) && ae->ae_flags != NULL) if (store_aff_word(spin, newword, ae->ae_flags, affile, &affile->af_suff, xht, use_condit & (xht == NULL ? ~0 : ~CONDIT_SUF), use_flags, use_pfxlist, pfxlen) == FAIL) retval = FAIL; /* When added a suffix and combining is allowed also * try adding a prefix additionally. Both for the * word flags and for the affix flags. RECURSIVE! */ if (xht != NULL && ah->ah_combine) { if (store_aff_word(spin, newword, afflist, affile, xht, NULL, use_condit, use_flags, use_pfxlist, pfxlen) == FAIL || (ae->ae_flags != NULL && store_aff_word(spin, newword, ae->ae_flags, affile, xht, NULL, use_condit, use_flags, use_pfxlist, pfxlen) == FAIL)) retval = FAIL; } } } } } } return retval; } /* * Read a file with a list of words. */ static int spell_read_wordfile(spin, fname) spellinfo_T *spin; char_u *fname; { FILE *fd; long lnum = 0; char_u rline[MAXLINELEN]; char_u *line; char_u *pc = NULL; char_u *p; int l; int retval = OK; int did_word = FALSE; int non_ascii = 0; int flags; int regionmask; /* * Open the file. */ fd = mch_fopen((char *)fname, "r"); if (fd == NULL) { EMSG2(_(e_notopen), fname); return FAIL; } vim_snprintf((char *)IObuff, IOSIZE, _("Reading word file %s ..."), fname); spell_message(spin, IObuff); /* * Read all the lines in the file one by one. */ while (!vim_fgets(rline, MAXLINELEN, fd) && !got_int) { line_breakcheck(); ++lnum; /* Skip comment lines. */ if (*rline == '#') continue; /* Remove CR, LF and white space from the end. */ l = (int)STRLEN(rline); while (l > 0 && rline[l - 1] <= ' ') --l; if (l == 0) continue; /* empty or blank line */ rline[l] = NUL; /* Convert from "/encoding={encoding}" to 'encoding' when needed. */ vim_free(pc); #ifdef FEAT_MBYTE if (spin->si_conv.vc_type != CONV_NONE) { pc = string_convert(&spin->si_conv, rline, NULL); if (pc == NULL) { smsg((char_u *)_("Conversion failure for word in %s line %d: %s"), fname, lnum, rline); continue; } line = pc; } else #endif { pc = NULL; line = rline; } if (*line == '/') { ++line; if (STRNCMP(line, "encoding=", 9) == 0) { if (spin->si_conv.vc_type != CONV_NONE) smsg((char_u *)_("Duplicate /encoding= line ignored in %s line %d: %s"), fname, lnum, line - 1); else if (did_word) smsg((char_u *)_("/encoding= line after word ignored in %s line %d: %s"), fname, lnum, line - 1); else { #ifdef FEAT_MBYTE char_u *enc; /* Setup for conversion to 'encoding'. */ line += 9; enc = enc_canonize(line); if (enc != NULL && !spin->si_ascii && convert_setup(&spin->si_conv, enc, p_enc) == FAIL) smsg((char_u *)_("Conversion in %s not supported: from %s to %s"), fname, line, p_enc); vim_free(enc); spin->si_conv.vc_fail = TRUE; #else smsg((char_u *)_("Conversion in %s not supported"), fname); #endif } continue; } if (STRNCMP(line, "regions=", 8) == 0) { if (spin->si_region_count > 1) smsg((char_u *)_("Duplicate /regions= line ignored in %s line %d: %s"), fname, lnum, line); else { line += 8; if (STRLEN(line) > 16) smsg((char_u *)_("Too many regions in %s line %d: %s"), fname, lnum, line); else { spin->si_region_count = (int)STRLEN(line) / 2; STRCPY(spin->si_region_name, line); /* Adjust the mask for a word valid in all regions. */ spin->si_region = (1 << spin->si_region_count) - 1; } } continue; } smsg((char_u *)_("/ line ignored in %s line %d: %s"), fname, lnum, line - 1); continue; } flags = 0; regionmask = spin->si_region; /* Check for flags and region after a slash. */ p = vim_strchr(line, '/'); if (p != NULL) { *p++ = NUL; while (*p != NUL) { if (*p == '=') /* keep-case word */ flags |= WF_KEEPCAP | WF_FIXCAP; else if (*p == '!') /* Bad, bad, wicked word. */ flags |= WF_BANNED; else if (*p == '?') /* Rare word. */ flags |= WF_RARE; else if (VIM_ISDIGIT(*p)) /* region number(s) */ { if ((flags & WF_REGION) == 0) /* first one */ regionmask = 0; flags |= WF_REGION; l = *p - '0'; if (l > spin->si_region_count) { smsg((char_u *)_("Invalid region nr in %s line %d: %s"), fname, lnum, p); break; } regionmask |= 1 << (l - 1); } else { smsg((char_u *)_("Unrecognized flags in %s line %d: %s"), fname, lnum, p); break; } ++p; } } /* Skip non-ASCII words when "spin->si_ascii" is TRUE. */ if (spin->si_ascii && has_non_ascii(line)) { ++non_ascii; continue; } /* Normal word: store it. */ if (store_word(spin, line, flags, regionmask, NULL, FALSE) == FAIL) { retval = FAIL; break; } did_word = TRUE; } vim_free(pc); fclose(fd); if (spin->si_ascii && non_ascii > 0) { vim_snprintf((char *)IObuff, IOSIZE, _("Ignored %d words with non-ASCII characters"), non_ascii); spell_message(spin, IObuff); } return retval; } /* * Get part of an sblock_T, "len" bytes long. * This avoids calling free() for every little struct we use (and keeping * track of them). * The memory is cleared to all zeros. * Returns NULL when out of memory. */ static void * getroom(spin, len, align) spellinfo_T *spin; size_t len; /* length needed */ int align; /* align for pointer */ { char_u *p; sblock_T *bl = spin->si_blocks; if (align && bl != NULL) /* Round size up for alignment. On some systems structures need to be * aligned to the size of a pointer (e.g., SPARC). */ bl->sb_used = (bl->sb_used + sizeof(char *) - 1) & ~(sizeof(char *) - 1); if (bl == NULL || bl->sb_used + len > SBLOCKSIZE) { if (len >= SBLOCKSIZE) bl = NULL; else /* Allocate a block of memory. It is not freed until much later. */ bl = (sblock_T *)alloc_clear( (unsigned)(sizeof(sblock_T) + SBLOCKSIZE)); if (bl == NULL) { if (!spin->si_did_emsg) { EMSG(_("E845: Insufficient memory, word list will be incomplete")); spin->si_did_emsg = TRUE; } return NULL; } bl->sb_next = spin->si_blocks; spin->si_blocks = bl; bl->sb_used = 0; ++spin->si_blocks_cnt; } p = bl->sb_data + bl->sb_used; bl->sb_used += (int)len; return p; } /* * Make a copy of a string into memory allocated with getroom(). * Returns NULL when out of memory. */ static char_u * getroom_save(spin, s) spellinfo_T *spin; char_u *s; { char_u *sc; sc = (char_u *)getroom(spin, STRLEN(s) + 1, FALSE); if (sc != NULL) STRCPY(sc, s); return sc; } /* * Free the list of allocated sblock_T. */ static void free_blocks(bl) sblock_T *bl; { sblock_T *next; while (bl != NULL) { next = bl->sb_next; vim_free(bl); bl = next; } } /* * Allocate the root of a word tree. * Returns NULL when out of memory. */ static wordnode_T * wordtree_alloc(spin) spellinfo_T *spin; { return (wordnode_T *)getroom(spin, sizeof(wordnode_T), TRUE); } /* * Store a word in the tree(s). * Always store it in the case-folded tree. For a keep-case word this is * useful when the word can also be used with all caps (no WF_FIXCAP flag) and * used to find suggestions. * For a keep-case word also store it in the keep-case tree. * When "pfxlist" is not NULL store the word for each postponed prefix ID and * compound flag. */ static int store_word(spin, word, flags, region, pfxlist, need_affix) spellinfo_T *spin; char_u *word; int flags; /* extra flags, WF_BANNED */ int region; /* supported region(s) */ char_u *pfxlist; /* list of prefix IDs or NULL */ int need_affix; /* only store word with affix ID */ { int len = (int)STRLEN(word); int ct = captype(word, word + len); char_u foldword[MAXWLEN]; int res = OK; char_u *p; (void)spell_casefold(word, len, foldword, MAXWLEN); for (p = pfxlist; res == OK; ++p) { if (!need_affix || (p != NULL && *p != NUL)) res = tree_add_word(spin, foldword, spin->si_foldroot, ct | flags, region, p == NULL ? 0 : *p); if (p == NULL || *p == NUL) break; } ++spin->si_foldwcount; if (res == OK && (ct == WF_KEEPCAP || (flags & WF_KEEPCAP))) { for (p = pfxlist; res == OK; ++p) { if (!need_affix || (p != NULL && *p != NUL)) res = tree_add_word(spin, word, spin->si_keeproot, flags, region, p == NULL ? 0 : *p); if (p == NULL || *p == NUL) break; } ++spin->si_keepwcount; } return res; } /* * Add word "word" to a word tree at "root". * When "flags" < 0 we are adding to the prefix tree where "flags" is used for * "rare" and "region" is the condition nr. * Returns FAIL when out of memory. */ static int tree_add_word(spin, word, root, flags, region, affixID) spellinfo_T *spin; char_u *word; wordnode_T *root; int flags; int region; int affixID; { wordnode_T *node = root; wordnode_T *np; wordnode_T *copyp, **copyprev; wordnode_T **prev = NULL; int i; /* Add each byte of the word to the tree, including the NUL at the end. */ for (i = 0; ; ++i) { /* When there is more than one reference to this node we need to make * a copy, so that we can modify it. Copy the whole list of siblings * (we don't optimize for a partly shared list of siblings). */ if (node != NULL && node->wn_refs > 1) { --node->wn_refs; copyprev = prev; for (copyp = node; copyp != NULL; copyp = copyp->wn_sibling) { /* Allocate a new node and copy the info. */ np = get_wordnode(spin); if (np == NULL) return FAIL; np->wn_child = copyp->wn_child; if (np->wn_child != NULL) ++np->wn_child->wn_refs; /* child gets extra ref */ np->wn_byte = copyp->wn_byte; if (np->wn_byte == NUL) { np->wn_flags = copyp->wn_flags; np->wn_region = copyp->wn_region; np->wn_affixID = copyp->wn_affixID; } /* Link the new node in the list, there will be one ref. */ np->wn_refs = 1; if (copyprev != NULL) *copyprev = np; copyprev = &np->wn_sibling; /* Let "node" point to the head of the copied list. */ if (copyp == node) node = np; } } /* Look for the sibling that has the same character. They are sorted * on byte value, thus stop searching when a sibling is found with a * higher byte value. For zero bytes (end of word) the sorting is * done on flags and then on affixID. */ while (node != NULL && (node->wn_byte < word[i] || (node->wn_byte == NUL && (flags < 0 ? node->wn_affixID < (unsigned)affixID : (node->wn_flags < (unsigned)(flags & WN_MASK) || (node->wn_flags == (flags & WN_MASK) && (spin->si_sugtree ? (node->wn_region & 0xffff) < region : node->wn_affixID < (unsigned)affixID))))))) { prev = &node->wn_sibling; node = *prev; } if (node == NULL || node->wn_byte != word[i] || (word[i] == NUL && (flags < 0 || spin->si_sugtree || node->wn_flags != (flags & WN_MASK) || node->wn_affixID != affixID))) { /* Allocate a new node. */ np = get_wordnode(spin); if (np == NULL) return FAIL; np->wn_byte = word[i]; /* If "node" is NULL this is a new child or the end of the sibling * list: ref count is one. Otherwise use ref count of sibling and * make ref count of sibling one (matters when inserting in front * of the list of siblings). */ if (node == NULL) np->wn_refs = 1; else { np->wn_refs = node->wn_refs; node->wn_refs = 1; } if (prev != NULL) *prev = np; np->wn_sibling = node; node = np; } if (word[i] == NUL) { node->wn_flags = flags; node->wn_region |= region; node->wn_affixID = affixID; break; } prev = &node->wn_child; node = *prev; } #ifdef SPELL_PRINTTREE smsg("Added \"%s\"", word); spell_print_tree(root->wn_sibling); #endif /* count nr of words added since last message */ ++spin->si_msg_count; if (spin->si_compress_cnt > 1) { if (--spin->si_compress_cnt == 1) /* Did enough words to lower the block count limit. */ spin->si_blocks_cnt += compress_inc; } /* * When we have allocated lots of memory we need to compress the word tree * to free up some room. But compression is slow, and we might actually * need that room, thus only compress in the following situations: * 1. When not compressed before (si_compress_cnt == 0): when using * "compress_start" blocks. * 2. When compressed before and used "compress_inc" blocks before * adding "compress_added" words (si_compress_cnt > 1). * 3. When compressed before, added "compress_added" words * (si_compress_cnt == 1) and the number of free nodes drops below the * maximum word length. */ #ifndef SPELL_PRINTTREE if (spin->si_compress_cnt == 1 ? spin->si_free_count < MAXWLEN : spin->si_blocks_cnt >= compress_start) #endif { /* Decrement the block counter. The effect is that we compress again * when the freed up room has been used and another "compress_inc" * blocks have been allocated. Unless "compress_added" words have * been added, then the limit is put back again. */ spin->si_blocks_cnt -= compress_inc; spin->si_compress_cnt = compress_added; if (spin->si_verbose) { msg_start(); msg_puts((char_u *)_(msg_compressing)); msg_clr_eos(); msg_didout = FALSE; msg_col = 0; out_flush(); } /* Compress both trees. Either they both have many nodes, which makes * compression useful, or one of them is small, which means * compression goes fast. But when filling the souldfold word tree * there is no keep-case tree. */ wordtree_compress(spin, spin->si_foldroot); if (affixID >= 0) wordtree_compress(spin, spin->si_keeproot); } return OK; } /* * Check the 'mkspellmem' option. Return FAIL if it's wrong. * Sets "sps_flags". */ int spell_check_msm() { char_u *p = p_msm; long start = 0; long incr = 0; long added = 0; if (!VIM_ISDIGIT(*p)) return FAIL; /* block count = (value * 1024) / SBLOCKSIZE (but avoid overflow)*/ start = (getdigits(&p) * 10) / (SBLOCKSIZE / 102); if (*p != ',') return FAIL; ++p; if (!VIM_ISDIGIT(*p)) return FAIL; incr = (getdigits(&p) * 102) / (SBLOCKSIZE / 10); if (*p != ',') return FAIL; ++p; if (!VIM_ISDIGIT(*p)) return FAIL; added = getdigits(&p) * 1024; if (*p != NUL) return FAIL; if (start == 0 || incr == 0 || added == 0 || incr > start) return FAIL; compress_start = start; compress_inc = incr; compress_added = added; return OK; } /* * Get a wordnode_T, either from the list of previously freed nodes or * allocate a new one. * Returns NULL when out of memory. */ static wordnode_T * get_wordnode(spin) spellinfo_T *spin; { wordnode_T *n; if (spin->si_first_free == NULL) n = (wordnode_T *)getroom(spin, sizeof(wordnode_T), TRUE); else { n = spin->si_first_free; spin->si_first_free = n->wn_child; vim_memset(n, 0, sizeof(wordnode_T)); --spin->si_free_count; } #ifdef SPELL_PRINTTREE if (n != NULL) n->wn_nr = ++spin->si_wordnode_nr; #endif return n; } /* * Decrement the reference count on a node (which is the head of a list of * siblings). If the reference count becomes zero free the node and its * siblings. * Returns the number of nodes actually freed. */ static int deref_wordnode(spin, node) spellinfo_T *spin; wordnode_T *node; { wordnode_T *np; int cnt = 0; if (--node->wn_refs == 0) { for (np = node; np != NULL; np = np->wn_sibling) { if (np->wn_child != NULL) cnt += deref_wordnode(spin, np->wn_child); free_wordnode(spin, np); ++cnt; } ++cnt; /* length field */ } return cnt; } /* * Free a wordnode_T for re-use later. * Only the "wn_child" field becomes invalid. */ static void free_wordnode(spin, n) spellinfo_T *spin; wordnode_T *n; { n->wn_child = spin->si_first_free; spin->si_first_free = n; ++spin->si_free_count; } /* * Compress a tree: find tails that are identical and can be shared. */ static void wordtree_compress(spin, root) spellinfo_T *spin; wordnode_T *root; { hashtab_T ht; int n; int tot = 0; int perc; /* Skip the root itself, it's not actually used. The first sibling is the * start of the tree. */ if (root->wn_sibling != NULL) { hash_init(&ht); n = node_compress(spin, root->wn_sibling, &ht, &tot); #ifndef SPELL_PRINTTREE if (spin->si_verbose || p_verbose > 2) #endif { if (tot > 1000000) perc = (tot - n) / (tot / 100); else if (tot == 0) perc = 0; else perc = (tot - n) * 100 / tot; vim_snprintf((char *)IObuff, IOSIZE, _("Compressed %d of %d nodes; %d (%d%%) remaining"), n, tot, tot - n, perc); spell_message(spin, IObuff); } #ifdef SPELL_PRINTTREE spell_print_tree(root->wn_sibling); #endif hash_clear(&ht); } } /* * Compress a node, its siblings and its children, depth first. * Returns the number of compressed nodes. */ static int node_compress(spin, node, ht, tot) spellinfo_T *spin; wordnode_T *node; hashtab_T *ht; int *tot; /* total count of nodes before compressing, incremented while going through the tree */ { wordnode_T *np; wordnode_T *tp; wordnode_T *child; hash_T hash; hashitem_T *hi; int len = 0; unsigned nr, n; int compressed = 0; /* * Go through the list of siblings. Compress each child and then try * finding an identical child to replace it. * Note that with "child" we mean not just the node that is pointed to, * but the whole list of siblings of which the child node is the first. */ for (np = node; np != NULL && !got_int; np = np->wn_sibling) { ++len; if ((child = np->wn_child) != NULL) { /* Compress the child first. This fills hashkey. */ compressed += node_compress(spin, child, ht, tot); /* Try to find an identical child. */ hash = hash_hash(child->wn_u1.hashkey); hi = hash_lookup(ht, child->wn_u1.hashkey, hash); if (!HASHITEM_EMPTY(hi)) { /* There are children we encountered before with a hash value * identical to the current child. Now check if there is one * that is really identical. */ for (tp = HI2WN(hi); tp != NULL; tp = tp->wn_u2.next) if (node_equal(child, tp)) { /* Found one! Now use that child in place of the * current one. This means the current child and all * its siblings is unlinked from the tree. */ ++tp->wn_refs; compressed += deref_wordnode(spin, child); np->wn_child = tp; break; } if (tp == NULL) { /* No other child with this hash value equals the child of * the node, add it to the linked list after the first * item. */ tp = HI2WN(hi); child->wn_u2.next = tp->wn_u2.next; tp->wn_u2.next = child; } } else /* No other child has this hash value, add it to the * hashtable. */ hash_add_item(ht, hi, child->wn_u1.hashkey, hash); } } *tot += len + 1; /* add one for the node that stores the length */ /* * Make a hash key for the node and its siblings, so that we can quickly * find a lookalike node. This must be done after compressing the sibling * list, otherwise the hash key would become invalid by the compression. */ node->wn_u1.hashkey[0] = len; nr = 0; for (np = node; np != NULL; np = np->wn_sibling) { if (np->wn_byte == NUL) /* end node: use wn_flags, wn_region and wn_affixID */ n = np->wn_flags + (np->wn_region << 8) + (np->wn_affixID << 16); else /* byte node: use the byte value and the child pointer */ n = (unsigned)(np->wn_byte + ((long_u)np->wn_child << 8)); nr = nr * 101 + n; } /* Avoid NUL bytes, it terminates the hash key. */ n = nr & 0xff; node->wn_u1.hashkey[1] = n == 0 ? 1 : n; n = (nr >> 8) & 0xff; node->wn_u1.hashkey[2] = n == 0 ? 1 : n; n = (nr >> 16) & 0xff; node->wn_u1.hashkey[3] = n == 0 ? 1 : n; n = (nr >> 24) & 0xff; node->wn_u1.hashkey[4] = n == 0 ? 1 : n; node->wn_u1.hashkey[5] = NUL; /* Check for CTRL-C pressed now and then. */ fast_breakcheck(); return compressed; } /* * Return TRUE when two nodes have identical siblings and children. */ static int node_equal(n1, n2) wordnode_T *n1; wordnode_T *n2; { wordnode_T *p1; wordnode_T *p2; for (p1 = n1, p2 = n2; p1 != NULL && p2 != NULL; p1 = p1->wn_sibling, p2 = p2->wn_sibling) if (p1->wn_byte != p2->wn_byte || (p1->wn_byte == NUL ? (p1->wn_flags != p2->wn_flags || p1->wn_region != p2->wn_region || p1->wn_affixID != p2->wn_affixID) : (p1->wn_child != p2->wn_child))) break; return p1 == NULL && p2 == NULL; } static int #ifdef __BORLANDC__ _RTLENTRYF #endif rep_compare __ARGS((const void *s1, const void *s2)); /* * Function given to qsort() to sort the REP items on "from" string. */ static int #ifdef __BORLANDC__ _RTLENTRYF #endif rep_compare(s1, s2) const void *s1; const void *s2; { fromto_T *p1 = (fromto_T *)s1; fromto_T *p2 = (fromto_T *)s2; return STRCMP(p1->ft_from, p2->ft_from); } /* * Write the Vim .spl file "fname". * Return FAIL or OK; */ static int write_vim_spell(spin, fname) spellinfo_T *spin; char_u *fname; { FILE *fd; int regionmask; int round; wordnode_T *tree; int nodecount; int i; int l; garray_T *gap; fromto_T *ftp; char_u *p; int rr; int retval = OK; size_t fwv = 1; /* collect return value of fwrite() to avoid warnings from picky compiler */ fd = mch_fopen((char *)fname, "w"); if (fd == NULL) { EMSG2(_(e_notopen), fname); return FAIL; } /* <HEADER>: <fileID> <versionnr> */ /* <fileID> */ fwv &= fwrite(VIMSPELLMAGIC, VIMSPELLMAGICL, (size_t)1, fd); if (fwv != (size_t)1) /* Catch first write error, don't try writing more. */ goto theend; putc(VIMSPELLVERSION, fd); /* <versionnr> */ /* * <SECTIONS>: <section> ... <sectionend> */ /* SN_INFO: <infotext> */ if (spin->si_info != NULL) { putc(SN_INFO, fd); /* <sectionID> */ putc(0, fd); /* <sectionflags> */ i = (int)STRLEN(spin->si_info); put_bytes(fd, (long_u)i, 4); /* <sectionlen> */ fwv &= fwrite(spin->si_info, (size_t)i, (size_t)1, fd); /* <infotext> */ } /* SN_REGION: <regionname> ... * Write the region names only if there is more than one. */ if (spin->si_region_count > 1) { putc(SN_REGION, fd); /* <sectionID> */ putc(SNF_REQUIRED, fd); /* <sectionflags> */ l = spin->si_region_count * 2; put_bytes(fd, (long_u)l, 4); /* <sectionlen> */ fwv &= fwrite(spin->si_region_name, (size_t)l, (size_t)1, fd); /* <regionname> ... */ regionmask = (1 << spin->si_region_count) - 1; } else regionmask = 0; /* SN_CHARFLAGS: <charflagslen> <charflags> <folcharslen> <folchars> * * The table with character flags and the table for case folding. * This makes sure the same characters are recognized as word characters * when generating an when using a spell file. * Skip this for ASCII, the table may conflict with the one used for * 'encoding'. * Also skip this for an .add.spl file, the main spell file must contain * the table (avoids that it conflicts). File is shorter too. */ if (!spin->si_ascii && !spin->si_add) { char_u folchars[128 * 8]; int flags; putc(SN_CHARFLAGS, fd); /* <sectionID> */ putc(SNF_REQUIRED, fd); /* <sectionflags> */ /* Form the <folchars> string first, we need to know its length. */ l = 0; for (i = 128; i < 256; ++i) { #ifdef FEAT_MBYTE if (has_mbyte) l += mb_char2bytes(spelltab.st_fold[i], folchars + l); else #endif folchars[l++] = spelltab.st_fold[i]; } put_bytes(fd, (long_u)(1 + 128 + 2 + l), 4); /* <sectionlen> */ fputc(128, fd); /* <charflagslen> */ for (i = 128; i < 256; ++i) { flags = 0; if (spelltab.st_isw[i]) flags |= CF_WORD; if (spelltab.st_isu[i]) flags |= CF_UPPER; fputc(flags, fd); /* <charflags> */ } put_bytes(fd, (long_u)l, 2); /* <folcharslen> */ fwv &= fwrite(folchars, (size_t)l, (size_t)1, fd); /* <folchars> */ } /* SN_MIDWORD: <midword> */ if (spin->si_midword != NULL) { putc(SN_MIDWORD, fd); /* <sectionID> */ putc(SNF_REQUIRED, fd); /* <sectionflags> */ i = (int)STRLEN(spin->si_midword); put_bytes(fd, (long_u)i, 4); /* <sectionlen> */ fwv &= fwrite(spin->si_midword, (size_t)i, (size_t)1, fd); /* <midword> */ } /* SN_PREFCOND: <prefcondcnt> <prefcond> ... */ if (spin->si_prefcond.ga_len > 0) { putc(SN_PREFCOND, fd); /* <sectionID> */ putc(SNF_REQUIRED, fd); /* <sectionflags> */ l = write_spell_prefcond(NULL, &spin->si_prefcond); put_bytes(fd, (long_u)l, 4); /* <sectionlen> */ write_spell_prefcond(fd, &spin->si_prefcond); } /* SN_REP: <repcount> <rep> ... * SN_SAL: <salflags> <salcount> <sal> ... * SN_REPSAL: <repcount> <rep> ... */ /* round 1: SN_REP section * round 2: SN_SAL section (unless SN_SOFO is used) * round 3: SN_REPSAL section */ for (round = 1; round <= 3; ++round) { if (round == 1) gap = &spin->si_rep; else if (round == 2) { /* Don't write SN_SAL when using a SN_SOFO section */ if (spin->si_sofofr != NULL && spin->si_sofoto != NULL) continue; gap = &spin->si_sal; } else gap = &spin->si_repsal; /* Don't write the section if there are no items. */ if (gap->ga_len == 0) continue; /* Sort the REP/REPSAL items. */ if (round != 2) qsort(gap->ga_data, (size_t)gap->ga_len, sizeof(fromto_T), rep_compare); i = round == 1 ? SN_REP : (round == 2 ? SN_SAL : SN_REPSAL); putc(i, fd); /* <sectionID> */ /* This is for making suggestions, section is not required. */ putc(0, fd); /* <sectionflags> */ /* Compute the length of what follows. */ l = 2; /* count <repcount> or <salcount> */ for (i = 0; i < gap->ga_len; ++i) { ftp = &((fromto_T *)gap->ga_data)[i]; l += 1 + (int)STRLEN(ftp->ft_from); /* count <*fromlen> and <*from> */ l += 1 + (int)STRLEN(ftp->ft_to); /* count <*tolen> and <*to> */ } if (round == 2) ++l; /* count <salflags> */ put_bytes(fd, (long_u)l, 4); /* <sectionlen> */ if (round == 2) { i = 0; if (spin->si_followup) i |= SAL_F0LLOWUP; if (spin->si_collapse) i |= SAL_COLLAPSE; if (spin->si_rem_accents) i |= SAL_REM_ACCENTS; putc(i, fd); /* <salflags> */ } put_bytes(fd, (long_u)gap->ga_len, 2); /* <repcount> or <salcount> */ for (i = 0; i < gap->ga_len; ++i) { /* <rep> : <repfromlen> <repfrom> <reptolen> <repto> */ /* <sal> : <salfromlen> <salfrom> <saltolen> <salto> */ ftp = &((fromto_T *)gap->ga_data)[i]; for (rr = 1; rr <= 2; ++rr) { p = rr == 1 ? ftp->ft_from : ftp->ft_to; l = (int)STRLEN(p); putc(l, fd); if (l > 0) fwv &= fwrite(p, l, (size_t)1, fd); } } } /* SN_SOFO: <sofofromlen> <sofofrom> <sofotolen> <sofoto> * This is for making suggestions, section is not required. */ if (spin->si_sofofr != NULL && spin->si_sofoto != NULL) { putc(SN_SOFO, fd); /* <sectionID> */ putc(0, fd); /* <sectionflags> */ l = (int)STRLEN(spin->si_sofofr); put_bytes(fd, (long_u)(l + STRLEN(spin->si_sofoto) + 4), 4); /* <sectionlen> */ put_bytes(fd, (long_u)l, 2); /* <sofofromlen> */ fwv &= fwrite(spin->si_sofofr, l, (size_t)1, fd); /* <sofofrom> */ l = (int)STRLEN(spin->si_sofoto); put_bytes(fd, (long_u)l, 2); /* <sofotolen> */ fwv &= fwrite(spin->si_sofoto, l, (size_t)1, fd); /* <sofoto> */ } /* SN_WORDS: <word> ... * This is for making suggestions, section is not required. */ if (spin->si_commonwords.ht_used > 0) { putc(SN_WORDS, fd); /* <sectionID> */ putc(0, fd); /* <sectionflags> */ /* round 1: count the bytes * round 2: write the bytes */ for (round = 1; round <= 2; ++round) { int todo; int len = 0; hashitem_T *hi; todo = (int)spin->si_commonwords.ht_used; for (hi = spin->si_commonwords.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { l = (int)STRLEN(hi->hi_key) + 1; len += l; if (round == 2) /* <word> */ fwv &= fwrite(hi->hi_key, (size_t)l, (size_t)1, fd); --todo; } if (round == 1) put_bytes(fd, (long_u)len, 4); /* <sectionlen> */ } } /* SN_MAP: <mapstr> * This is for making suggestions, section is not required. */ if (spin->si_map.ga_len > 0) { putc(SN_MAP, fd); /* <sectionID> */ putc(0, fd); /* <sectionflags> */ l = spin->si_map.ga_len; put_bytes(fd, (long_u)l, 4); /* <sectionlen> */ fwv &= fwrite(spin->si_map.ga_data, (size_t)l, (size_t)1, fd); /* <mapstr> */ } /* SN_SUGFILE: <timestamp> * This is used to notify that a .sug file may be available and at the * same time allows for checking that a .sug file that is found matches * with this .spl file. That's because the word numbers must be exactly * right. */ if (!spin->si_nosugfile && (spin->si_sal.ga_len > 0 || (spin->si_sofofr != NULL && spin->si_sofoto != NULL))) { putc(SN_SUGFILE, fd); /* <sectionID> */ putc(0, fd); /* <sectionflags> */ put_bytes(fd, (long_u)8, 4); /* <sectionlen> */ /* Set si_sugtime and write it to the file. */ spin->si_sugtime = time(NULL); put_time(fd, spin->si_sugtime); /* <timestamp> */ } /* SN_NOSPLITSUGS: nothing * This is used to notify that no suggestions with word splits are to be * made. */ if (spin->si_nosplitsugs) { putc(SN_NOSPLITSUGS, fd); /* <sectionID> */ putc(0, fd); /* <sectionflags> */ put_bytes(fd, (long_u)0, 4); /* <sectionlen> */ } /* SN_COMPOUND: compound info. * We don't mark it required, when not supported all compound words will * be bad words. */ if (spin->si_compflags != NULL) { putc(SN_COMPOUND, fd); /* <sectionID> */ putc(0, fd); /* <sectionflags> */ l = (int)STRLEN(spin->si_compflags); for (i = 0; i < spin->si_comppat.ga_len; ++i) l += (int)STRLEN(((char_u **)(spin->si_comppat.ga_data))[i]) + 1; put_bytes(fd, (long_u)(l + 7), 4); /* <sectionlen> */ putc(spin->si_compmax, fd); /* <compmax> */ putc(spin->si_compminlen, fd); /* <compminlen> */ putc(spin->si_compsylmax, fd); /* <compsylmax> */ putc(0, fd); /* for Vim 7.0b compatibility */ putc(spin->si_compoptions, fd); /* <compoptions> */ put_bytes(fd, (long_u)spin->si_comppat.ga_len, 2); /* <comppatcount> */ for (i = 0; i < spin->si_comppat.ga_len; ++i) { p = ((char_u **)(spin->si_comppat.ga_data))[i]; putc((int)STRLEN(p), fd); /* <comppatlen> */ fwv &= fwrite(p, (size_t)STRLEN(p), (size_t)1, fd); /* <comppattext> */ } /* <compflags> */ fwv &= fwrite(spin->si_compflags, (size_t)STRLEN(spin->si_compflags), (size_t)1, fd); } /* SN_NOBREAK: NOBREAK flag */ if (spin->si_nobreak) { putc(SN_NOBREAK, fd); /* <sectionID> */ putc(0, fd); /* <sectionflags> */ /* It's empty, the presence of the section flags the feature. */ put_bytes(fd, (long_u)0, 4); /* <sectionlen> */ } /* SN_SYLLABLE: syllable info. * We don't mark it required, when not supported syllables will not be * counted. */ if (spin->si_syllable != NULL) { putc(SN_SYLLABLE, fd); /* <sectionID> */ putc(0, fd); /* <sectionflags> */ l = (int)STRLEN(spin->si_syllable); put_bytes(fd, (long_u)l, 4); /* <sectionlen> */ fwv &= fwrite(spin->si_syllable, (size_t)l, (size_t)1, fd); /* <syllable> */ } /* end of <SECTIONS> */ putc(SN_END, fd); /* <sectionend> */ /* * <LWORDTREE> <KWORDTREE> <PREFIXTREE> */ spin->si_memtot = 0; for (round = 1; round <= 3; ++round) { if (round == 1) tree = spin->si_foldroot->wn_sibling; else if (round == 2) tree = spin->si_keeproot->wn_sibling; else tree = spin->si_prefroot->wn_sibling; /* Clear the index and wnode fields in the tree. */ clear_node(tree); /* Count the number of nodes. Needed to be able to allocate the * memory when reading the nodes. Also fills in index for shared * nodes. */ nodecount = put_node(NULL, tree, 0, regionmask, round == 3); /* number of nodes in 4 bytes */ put_bytes(fd, (long_u)nodecount, 4); /* <nodecount> */ spin->si_memtot += nodecount + nodecount * sizeof(int); /* Write the nodes. */ (void)put_node(fd, tree, 0, regionmask, round == 3); } /* Write another byte to check for errors (file system full). */ if (putc(0, fd) == EOF) retval = FAIL; theend: if (fclose(fd) == EOF) retval = FAIL; if (fwv != (size_t)1) retval = FAIL; if (retval == FAIL) EMSG(_(e_write)); return retval; } /* * Clear the index and wnode fields of "node", it siblings and its * children. This is needed because they are a union with other items to save * space. */ static void clear_node(node) wordnode_T *node; { wordnode_T *np; if (node != NULL) for (np = node; np != NULL; np = np->wn_sibling) { np->wn_u1.index = 0; np->wn_u2.wnode = NULL; if (np->wn_byte != NUL) clear_node(np->wn_child); } } /* * Dump a word tree at node "node". * * This first writes the list of possible bytes (siblings). Then for each * byte recursively write the children. * * NOTE: The code here must match the code in read_tree_node(), since * assumptions are made about the indexes (so that we don't have to write them * in the file). * * Returns the number of nodes used. */ static int put_node(fd, node, idx, regionmask, prefixtree) FILE *fd; /* NULL when only counting */ wordnode_T *node; int idx; int regionmask; int prefixtree; /* TRUE for PREFIXTREE */ { int newindex = idx; int siblingcount = 0; wordnode_T *np; int flags; /* If "node" is zero the tree is empty. */ if (node == NULL) return 0; /* Store the index where this node is written. */ node->wn_u1.index = idx; /* Count the number of siblings. */ for (np = node; np != NULL; np = np->wn_sibling) ++siblingcount; /* Write the sibling count. */ if (fd != NULL) putc(siblingcount, fd); /* <siblingcount> */ /* Write each sibling byte and optionally extra info. */ for (np = node; np != NULL; np = np->wn_sibling) { if (np->wn_byte == 0) { if (fd != NULL) { /* For a NUL byte (end of word) write the flags etc. */ if (prefixtree) { /* In PREFIXTREE write the required affixID and the * associated condition nr (stored in wn_region). The * byte value is misused to store the "rare" and "not * combining" flags */ if (np->wn_flags == (short_u)PFX_FLAGS) putc(BY_NOFLAGS, fd); /* <byte> */ else { putc(BY_FLAGS, fd); /* <byte> */ putc(np->wn_flags, fd); /* <pflags> */ } putc(np->wn_affixID, fd); /* <affixID> */ put_bytes(fd, (long_u)np->wn_region, 2); /* <prefcondnr> */ } else { /* For word trees we write the flag/region items. */ flags = np->wn_flags; if (regionmask != 0 && np->wn_region != regionmask) flags |= WF_REGION; if (np->wn_affixID != 0) flags |= WF_AFX; if (flags == 0) { /* word without flags or region */ putc(BY_NOFLAGS, fd); /* <byte> */ } else { if (np->wn_flags >= 0x100) { putc(BY_FLAGS2, fd); /* <byte> */ putc(flags, fd); /* <flags> */ putc((unsigned)flags >> 8, fd); /* <flags2> */ } else { putc(BY_FLAGS, fd); /* <byte> */ putc(flags, fd); /* <flags> */ } if (flags & WF_REGION) putc(np->wn_region, fd); /* <region> */ if (flags & WF_AFX) putc(np->wn_affixID, fd); /* <affixID> */ } } } } else { if (np->wn_child->wn_u1.index != 0 && np->wn_child->wn_u2.wnode != node) { /* The child is written elsewhere, write the reference. */ if (fd != NULL) { putc(BY_INDEX, fd); /* <byte> */ /* <nodeidx> */ put_bytes(fd, (long_u)np->wn_child->wn_u1.index, 3); } } else if (np->wn_child->wn_u2.wnode == NULL) /* We will write the child below and give it an index. */ np->wn_child->wn_u2.wnode = node; if (fd != NULL) if (putc(np->wn_byte, fd) == EOF) /* <byte> or <xbyte> */ { EMSG(_(e_write)); return 0; } } } /* Space used in the array when reading: one for each sibling and one for * the count. */ newindex += siblingcount + 1; /* Recursively dump the children of each sibling. */ for (np = node; np != NULL; np = np->wn_sibling) if (np->wn_byte != 0 && np->wn_child->wn_u2.wnode == node) newindex = put_node(fd, np->wn_child, newindex, regionmask, prefixtree); return newindex; } /* * ":mkspell [-ascii] outfile infile ..." * ":mkspell [-ascii] addfile" */ void ex_mkspell(eap) exarg_T *eap; { int fcount; char_u **fnames; char_u *arg = eap->arg; int ascii = FALSE; if (STRNCMP(arg, "-ascii", 6) == 0) { ascii = TRUE; arg = skipwhite(arg + 6); } /* Expand all the remaining arguments (e.g., $VIMRUNTIME). */ if (get_arglist_exp(arg, &fcount, &fnames) == OK) { mkspell(fcount, fnames, ascii, eap->forceit, FALSE); FreeWild(fcount, fnames); } } /* * Create the .sug file. * Uses the soundfold info in "spin". * Writes the file with the name "wfname", with ".spl" changed to ".sug". */ static void spell_make_sugfile(spin, wfname) spellinfo_T *spin; char_u *wfname; { char_u *fname = NULL; int len; slang_T *slang; int free_slang = FALSE; /* * Read back the .spl file that was written. This fills the required * info for soundfolding. This also uses less memory than the * pointer-linked version of the trie. And it avoids having two versions * of the code for the soundfolding stuff. * It might have been done already by spell_reload_one(). */ for (slang = first_lang; slang != NULL; slang = slang->sl_next) if (fullpathcmp(wfname, slang->sl_fname, FALSE) == FPC_SAME) break; if (slang == NULL) { spell_message(spin, (char_u *)_("Reading back spell file...")); slang = spell_load_file(wfname, NULL, NULL, FALSE); if (slang == NULL) return; free_slang = TRUE; } /* * Clear the info in "spin" that is used. */ spin->si_blocks = NULL; spin->si_blocks_cnt = 0; spin->si_compress_cnt = 0; /* will stay at 0 all the time*/ spin->si_free_count = 0; spin->si_first_free = NULL; spin->si_foldwcount = 0; /* * Go through the trie of good words, soundfold each word and add it to * the soundfold trie. */ spell_message(spin, (char_u *)_("Performing soundfolding...")); if (sug_filltree(spin, slang) == FAIL) goto theend; /* * Create the table which links each soundfold word with a list of the * good words it may come from. Creates buffer "spin->si_spellbuf". * This also removes the wordnr from the NUL byte entries to make * compression possible. */ if (sug_maketable(spin) == FAIL) goto theend; smsg((char_u *)_("Number of words after soundfolding: %ld"), (long)spin->si_spellbuf->b_ml.ml_line_count); /* * Compress the soundfold trie. */ spell_message(spin, (char_u *)_(msg_compressing)); wordtree_compress(spin, spin->si_foldroot); /* * Write the .sug file. * Make the file name by changing ".spl" to ".sug". */ fname = alloc(MAXPATHL); if (fname == NULL) goto theend; vim_strncpy(fname, wfname, MAXPATHL - 1); len = (int)STRLEN(fname); fname[len - 2] = 'u'; fname[len - 1] = 'g'; sug_write(spin, fname); theend: vim_free(fname); if (free_slang) slang_free(slang); free_blocks(spin->si_blocks); close_spellbuf(spin->si_spellbuf); } /* * Build the soundfold trie for language "slang". */ static int sug_filltree(spin, slang) spellinfo_T *spin; slang_T *slang; { char_u *byts; idx_T *idxs; int depth; idx_T arridx[MAXWLEN]; int curi[MAXWLEN]; char_u tword[MAXWLEN]; char_u tsalword[MAXWLEN]; int c; idx_T n; unsigned words_done = 0; int wordcount[MAXWLEN]; /* We use si_foldroot for the souldfolded trie. */ spin->si_foldroot = wordtree_alloc(spin); if (spin->si_foldroot == NULL) return FAIL; /* let tree_add_word() know we're adding to the soundfolded tree */ spin->si_sugtree = TRUE; /* * Go through the whole case-folded tree, soundfold each word and put it * in the trie. */ byts = slang->sl_fbyts; idxs = slang->sl_fidxs; arridx[0] = 0; curi[0] = 1; wordcount[0] = 0; depth = 0; while (depth >= 0 && !got_int) { if (curi[depth] > byts[arridx[depth]]) { /* Done all bytes at this node, go up one level. */ idxs[arridx[depth]] = wordcount[depth]; if (depth > 0) wordcount[depth - 1] += wordcount[depth]; --depth; line_breakcheck(); } else { /* Do one more byte at this node. */ n = arridx[depth] + curi[depth]; ++curi[depth]; c = byts[n]; if (c == 0) { /* Sound-fold the word. */ tword[depth] = NUL; spell_soundfold(slang, tword, TRUE, tsalword); /* We use the "flags" field for the MSB of the wordnr, * "region" for the LSB of the wordnr. */ if (tree_add_word(spin, tsalword, spin->si_foldroot, words_done >> 16, words_done & 0xffff, 0) == FAIL) return FAIL; ++words_done; ++wordcount[depth]; /* Reset the block count each time to avoid compression * kicking in. */ spin->si_blocks_cnt = 0; /* Skip over any other NUL bytes (same word with different * flags). */ while (byts[n + 1] == 0) { ++n; ++curi[depth]; } } else { /* Normal char, go one level deeper. */ tword[depth++] = c; arridx[depth] = idxs[n]; curi[depth] = 1; wordcount[depth] = 0; } } } smsg((char_u *)_("Total number of words: %d"), words_done); return OK; } /* * Make the table that links each word in the soundfold trie to the words it * can be produced from. * This is not unlike lines in a file, thus use a memfile to be able to access * the table efficiently. * Returns FAIL when out of memory. */ static int sug_maketable(spin) spellinfo_T *spin; { garray_T ga; int res = OK; /* Allocate a buffer, open a memline for it and create the swap file * (uses a temp file, not a .swp file). */ spin->si_spellbuf = open_spellbuf(); if (spin->si_spellbuf == NULL) return FAIL; /* Use a buffer to store the line info, avoids allocating many small * pieces of memory. */ ga_init2(&ga, 1, 100); /* recursively go through the tree */ if (sug_filltable(spin, spin->si_foldroot->wn_sibling, 0, &ga) == -1) res = FAIL; ga_clear(&ga); return res; } /* * Fill the table for one node and its children. * Returns the wordnr at the start of the node. * Returns -1 when out of memory. */ static int sug_filltable(spin, node, startwordnr, gap) spellinfo_T *spin; wordnode_T *node; int startwordnr; garray_T *gap; /* place to store line of numbers */ { wordnode_T *p, *np; int wordnr = startwordnr; int nr; int prev_nr; for (p = node; p != NULL; p = p->wn_sibling) { if (p->wn_byte == NUL) { gap->ga_len = 0; prev_nr = 0; for (np = p; np != NULL && np->wn_byte == NUL; np = np->wn_sibling) { if (ga_grow(gap, 10) == FAIL) return -1; nr = (np->wn_flags << 16) + (np->wn_region & 0xffff); /* Compute the offset from the previous nr and store the * offset in a way that it takes a minimum number of bytes. * It's a bit like utf-8, but without the need to mark * following bytes. */ nr -= prev_nr; prev_nr += nr; gap->ga_len += offset2bytes(nr, (char_u *)gap->ga_data + gap->ga_len); } /* add the NUL byte */ ((char_u *)gap->ga_data)[gap->ga_len++] = NUL; if (ml_append_buf(spin->si_spellbuf, (linenr_T)wordnr, gap->ga_data, gap->ga_len, TRUE) == FAIL) return -1; ++wordnr; /* Remove extra NUL entries, we no longer need them. We don't * bother freeing the nodes, the won't be reused anyway. */ while (p->wn_sibling != NULL && p->wn_sibling->wn_byte == NUL) p->wn_sibling = p->wn_sibling->wn_sibling; /* Clear the flags on the remaining NUL node, so that compression * works a lot better. */ p->wn_flags = 0; p->wn_region = 0; } else { wordnr = sug_filltable(spin, p->wn_child, wordnr, gap); if (wordnr == -1) return -1; } } return wordnr; } /* * Convert an offset into a minimal number of bytes. * Similar to utf_char2byters, but use 8 bits in followup bytes and avoid NUL * bytes. */ static int offset2bytes(nr, buf) int nr; char_u *buf; { int rem; int b1, b2, b3, b4; /* Split the number in parts of base 255. We need to avoid NUL bytes. */ b1 = nr % 255 + 1; rem = nr / 255; b2 = rem % 255 + 1; rem = rem / 255; b3 = rem % 255 + 1; b4 = rem / 255 + 1; if (b4 > 1 || b3 > 0x1f) /* 4 bytes */ { buf[0] = 0xe0 + b4; buf[1] = b3; buf[2] = b2; buf[3] = b1; return 4; } if (b3 > 1 || b2 > 0x3f ) /* 3 bytes */ { buf[0] = 0xc0 + b3; buf[1] = b2; buf[2] = b1; return 3; } if (b2 > 1 || b1 > 0x7f ) /* 2 bytes */ { buf[0] = 0x80 + b2; buf[1] = b1; return 2; } /* 1 byte */ buf[0] = b1; return 1; } /* * Opposite of offset2bytes(). * "pp" points to the bytes and is advanced over it. * Returns the offset. */ static int bytes2offset(pp) char_u **pp; { char_u *p = *pp; int nr; int c; c = *p++; if ((c & 0x80) == 0x00) /* 1 byte */ { nr = c - 1; } else if ((c & 0xc0) == 0x80) /* 2 bytes */ { nr = (c & 0x3f) - 1; nr = nr * 255 + (*p++ - 1); } else if ((c & 0xe0) == 0xc0) /* 3 bytes */ { nr = (c & 0x1f) - 1; nr = nr * 255 + (*p++ - 1); nr = nr * 255 + (*p++ - 1); } else /* 4 bytes */ { nr = (c & 0x0f) - 1; nr = nr * 255 + (*p++ - 1); nr = nr * 255 + (*p++ - 1); nr = nr * 255 + (*p++ - 1); } *pp = p; return nr; } /* * Write the .sug file in "fname". */ static void sug_write(spin, fname) spellinfo_T *spin; char_u *fname; { FILE *fd; wordnode_T *tree; int nodecount; int wcount; char_u *line; linenr_T lnum; int len; /* Create the file. Note that an existing file is silently overwritten! */ fd = mch_fopen((char *)fname, "w"); if (fd == NULL) { EMSG2(_(e_notopen), fname); return; } vim_snprintf((char *)IObuff, IOSIZE, _("Writing suggestion file %s ..."), fname); spell_message(spin, IObuff); /* * <SUGHEADER>: <fileID> <versionnr> <timestamp> */ if (fwrite(VIMSUGMAGIC, VIMSUGMAGICL, (size_t)1, fd) != 1) /* <fileID> */ { EMSG(_(e_write)); goto theend; } putc(VIMSUGVERSION, fd); /* <versionnr> */ /* Write si_sugtime to the file. */ put_time(fd, spin->si_sugtime); /* <timestamp> */ /* * <SUGWORDTREE> */ spin->si_memtot = 0; tree = spin->si_foldroot->wn_sibling; /* Clear the index and wnode fields in the tree. */ clear_node(tree); /* Count the number of nodes. Needed to be able to allocate the * memory when reading the nodes. Also fills in index for shared * nodes. */ nodecount = put_node(NULL, tree, 0, 0, FALSE); /* number of nodes in 4 bytes */ put_bytes(fd, (long_u)nodecount, 4); /* <nodecount> */ spin->si_memtot += nodecount + nodecount * sizeof(int); /* Write the nodes. */ (void)put_node(fd, tree, 0, 0, FALSE); /* * <SUGTABLE>: <sugwcount> <sugline> ... */ wcount = spin->si_spellbuf->b_ml.ml_line_count; put_bytes(fd, (long_u)wcount, 4); /* <sugwcount> */ for (lnum = 1; lnum <= (linenr_T)wcount; ++lnum) { /* <sugline>: <sugnr> ... NUL */ line = ml_get_buf(spin->si_spellbuf, lnum, FALSE); len = (int)STRLEN(line) + 1; if (fwrite(line, (size_t)len, (size_t)1, fd) == 0) { EMSG(_(e_write)); goto theend; } spin->si_memtot += len; } /* Write another byte to check for errors. */ if (putc(0, fd) == EOF) EMSG(_(e_write)); vim_snprintf((char *)IObuff, IOSIZE, _("Estimated runtime memory use: %d bytes"), spin->si_memtot); spell_message(spin, IObuff); theend: /* close the file */ fclose(fd); } /* * Open a spell buffer. This is a nameless buffer that is not in the buffer * list and only contains text lines. Can use a swapfile to reduce memory * use. * Most other fields are invalid! Esp. watch out for string options being * NULL and there is no undo info. * Returns NULL when out of memory. */ static buf_T * open_spellbuf() { buf_T *buf; buf = (buf_T *)alloc_clear(sizeof(buf_T)); if (buf != NULL) { buf->b_spell = TRUE; buf->b_p_swf = TRUE; /* may create a swap file */ ml_open(buf); ml_open_file(buf); /* create swap file now */ } return buf; } /* * Close the buffer used for spell info. */ static void close_spellbuf(buf) buf_T *buf; { if (buf != NULL) { ml_close(buf, TRUE); vim_free(buf); } } /* * Create a Vim spell file from one or more word lists. * "fnames[0]" is the output file name. * "fnames[fcount - 1]" is the last input file name. * Exception: when "fnames[0]" ends in ".add" it's used as the input file name * and ".spl" is appended to make the output file name. */ static void mkspell(fcount, fnames, ascii, over_write, added_word) int fcount; char_u **fnames; int ascii; /* -ascii argument given */ int over_write; /* overwrite existing output file */ int added_word; /* invoked through "zg" */ { char_u *fname = NULL; char_u *wfname; char_u **innames; int incount; afffile_T *(afile[8]); int i; int len; struct stat st; int error = FALSE; spellinfo_T spin; vim_memset(&spin, 0, sizeof(spin)); spin.si_verbose = !added_word; spin.si_ascii = ascii; spin.si_followup = TRUE; spin.si_rem_accents = TRUE; ga_init2(&spin.si_rep, (int)sizeof(fromto_T), 20); ga_init2(&spin.si_repsal, (int)sizeof(fromto_T), 20); ga_init2(&spin.si_sal, (int)sizeof(fromto_T), 20); ga_init2(&spin.si_map, (int)sizeof(char_u), 100); ga_init2(&spin.si_comppat, (int)sizeof(char_u *), 20); ga_init2(&spin.si_prefcond, (int)sizeof(char_u *), 50); hash_init(&spin.si_commonwords); spin.si_newcompID = 127; /* start compound ID at first maximum */ /* default: fnames[0] is output file, following are input files */ innames = &fnames[1]; incount = fcount - 1; wfname = alloc(MAXPATHL); if (wfname == NULL) return; if (fcount >= 1) { len = (int)STRLEN(fnames[0]); if (fcount == 1 && len > 4 && STRCMP(fnames[0] + len - 4, ".add") == 0) { /* For ":mkspell path/en.latin1.add" output file is * "path/en.latin1.add.spl". */ innames = &fnames[0]; incount = 1; vim_snprintf((char *)wfname, MAXPATHL, "%s.spl", fnames[0]); } else if (fcount == 1) { /* For ":mkspell path/vim" output file is "path/vim.latin1.spl". */ innames = &fnames[0]; incount = 1; vim_snprintf((char *)wfname, MAXPATHL, SPL_FNAME_TMPL, fnames[0], spin.si_ascii ? (char_u *)"ascii" : spell_enc()); } else if (len > 4 && STRCMP(fnames[0] + len - 4, ".spl") == 0) { /* Name ends in ".spl", use as the file name. */ vim_strncpy(wfname, fnames[0], MAXPATHL - 1); } else /* Name should be language, make the file name from it. */ vim_snprintf((char *)wfname, MAXPATHL, SPL_FNAME_TMPL, fnames[0], spin.si_ascii ? (char_u *)"ascii" : spell_enc()); /* Check for .ascii.spl. */ if (strstr((char *)gettail(wfname), SPL_FNAME_ASCII) != NULL) spin.si_ascii = TRUE; /* Check for .add.spl. */ if (strstr((char *)gettail(wfname), SPL_FNAME_ADD) != NULL) spin.si_add = TRUE; } if (incount <= 0) EMSG(_(e_invarg)); /* need at least output and input names */ else if (vim_strchr(gettail(wfname), '_') != NULL) EMSG(_("E751: Output file name must not have region name")); else if (incount > 8) EMSG(_("E754: Only up to 8 regions supported")); else { /* Check for overwriting before doing things that may take a lot of * time. */ if (!over_write && mch_stat((char *)wfname, &st) >= 0) { EMSG(_(e_exists)); goto theend; } if (mch_isdir(wfname)) { EMSG2(_(e_isadir2), wfname); goto theend; } fname = alloc(MAXPATHL); if (fname == NULL) goto theend; /* * Init the aff and dic pointers. * Get the region names if there are more than 2 arguments. */ for (i = 0; i < incount; ++i) { afile[i] = NULL; if (incount > 1) { len = (int)STRLEN(innames[i]); if (STRLEN(gettail(innames[i])) < 5 || innames[i][len - 3] != '_') { EMSG2(_("E755: Invalid region in %s"), innames[i]); goto theend; } spin.si_region_name[i * 2] = TOLOWER_ASC(innames[i][len - 2]); spin.si_region_name[i * 2 + 1] = TOLOWER_ASC(innames[i][len - 1]); } } spin.si_region_count = incount; spin.si_foldroot = wordtree_alloc(&spin); spin.si_keeproot = wordtree_alloc(&spin); spin.si_prefroot = wordtree_alloc(&spin); if (spin.si_foldroot == NULL || spin.si_keeproot == NULL || spin.si_prefroot == NULL) { free_blocks(spin.si_blocks); goto theend; } /* When not producing a .add.spl file clear the character table when * we encounter one in the .aff file. This means we dump the current * one in the .spl file if the .aff file doesn't define one. That's * better than guessing the contents, the table will match a * previously loaded spell file. */ if (!spin.si_add) spin.si_clear_chartab = TRUE; /* * Read all the .aff and .dic files. * Text is converted to 'encoding'. * Words are stored in the case-folded and keep-case trees. */ for (i = 0; i < incount && !error; ++i) { spin.si_conv.vc_type = CONV_NONE; spin.si_region = 1 << i; vim_snprintf((char *)fname, MAXPATHL, "%s.aff", innames[i]); if (mch_stat((char *)fname, &st) >= 0) { /* Read the .aff file. Will init "spin->si_conv" based on the * "SET" line. */ afile[i] = spell_read_aff(&spin, fname); if (afile[i] == NULL) error = TRUE; else { /* Read the .dic file and store the words in the trees. */ vim_snprintf((char *)fname, MAXPATHL, "%s.dic", innames[i]); if (spell_read_dic(&spin, fname, afile[i]) == FAIL) error = TRUE; } } else { /* No .aff file, try reading the file as a word list. Store * the words in the trees. */ if (spell_read_wordfile(&spin, innames[i]) == FAIL) error = TRUE; } #ifdef FEAT_MBYTE /* Free any conversion stuff. */ convert_setup(&spin.si_conv, NULL, NULL); #endif } if (spin.si_compflags != NULL && spin.si_nobreak) MSG(_("Warning: both compounding and NOBREAK specified")); if (!error && !got_int) { /* * Combine tails in the tree. */ spell_message(&spin, (char_u *)_(msg_compressing)); wordtree_compress(&spin, spin.si_foldroot); wordtree_compress(&spin, spin.si_keeproot); wordtree_compress(&spin, spin.si_prefroot); } if (!error && !got_int) { /* * Write the info in the spell file. */ vim_snprintf((char *)IObuff, IOSIZE, _("Writing spell file %s ..."), wfname); spell_message(&spin, IObuff); error = write_vim_spell(&spin, wfname) == FAIL; spell_message(&spin, (char_u *)_("Done!")); vim_snprintf((char *)IObuff, IOSIZE, _("Estimated runtime memory use: %d bytes"), spin.si_memtot); spell_message(&spin, IObuff); /* * If the file is loaded need to reload it. */ if (!error) spell_reload_one(wfname, added_word); } /* Free the allocated memory. */ ga_clear(&spin.si_rep); ga_clear(&spin.si_repsal); ga_clear(&spin.si_sal); ga_clear(&spin.si_map); ga_clear(&spin.si_comppat); ga_clear(&spin.si_prefcond); hash_clear_all(&spin.si_commonwords, 0); /* Free the .aff file structures. */ for (i = 0; i < incount; ++i) if (afile[i] != NULL) spell_free_aff(afile[i]); /* Free all the bits and pieces at once. */ free_blocks(spin.si_blocks); /* * If there is soundfolding info and no NOSUGFILE item create the * .sug file with the soundfolded word trie. */ if (spin.si_sugtime != 0 && !error && !got_int) spell_make_sugfile(&spin, wfname); } theend: vim_free(fname); vim_free(wfname); } /* * Display a message for spell file processing when 'verbose' is set or using * ":mkspell". "str" can be IObuff. */ static void spell_message(spin, str) spellinfo_T *spin; char_u *str; { if (spin->si_verbose || p_verbose > 2) { if (!spin->si_verbose) verbose_enter(); MSG(str); out_flush(); if (!spin->si_verbose) verbose_leave(); } } /* * ":[count]spellgood {word}" * ":[count]spellwrong {word}" * ":[count]spellundo {word}" */ void ex_spell(eap) exarg_T *eap; { spell_add_word(eap->arg, (int)STRLEN(eap->arg), eap->cmdidx == CMD_spellwrong, eap->forceit ? 0 : (int)eap->line2, eap->cmdidx == CMD_spellundo); } /* * Add "word[len]" to 'spellfile' as a good or bad word. */ void spell_add_word(word, len, bad, idx, undo) char_u *word; int len; int bad; int idx; /* "zG" and "zW": zero, otherwise index in 'spellfile' */ int undo; /* TRUE for "zug", "zuG", "zuw" and "zuW" */ { FILE *fd = NULL; buf_T *buf = NULL; int new_spf = FALSE; char_u *fname; char_u *fnamebuf = NULL; char_u line[MAXWLEN * 2]; long fpos, fpos_next = 0; int i; char_u *spf; if (idx == 0) /* use internal wordlist */ { if (int_wordlist == NULL) { int_wordlist = vim_tempname('s'); if (int_wordlist == NULL) return; } fname = int_wordlist; } else { /* If 'spellfile' isn't set figure out a good default value. */ if (*curwin->w_s->b_p_spf == NUL) { init_spellfile(); new_spf = TRUE; } if (*curwin->w_s->b_p_spf == NUL) { EMSG2(_(e_notset), "spellfile"); return; } fnamebuf = alloc(MAXPATHL); if (fnamebuf == NULL) return; for (spf = curwin->w_s->b_p_spf, i = 1; *spf != NUL; ++i) { copy_option_part(&spf, fnamebuf, MAXPATHL, ","); if (i == idx) break; if (*spf == NUL) { EMSGN(_("E765: 'spellfile' does not have %ld entries"), idx); vim_free(fnamebuf); return; } } /* Check that the user isn't editing the .add file somewhere. */ buf = buflist_findname_exp(fnamebuf); if (buf != NULL && buf->b_ml.ml_mfp == NULL) buf = NULL; if (buf != NULL && bufIsChanged(buf)) { EMSG(_(e_bufloaded)); vim_free(fnamebuf); return; } fname = fnamebuf; } if (bad || undo) { /* When the word appears as good word we need to remove that one, * since its flags sort before the one with WF_BANNED. */ fd = mch_fopen((char *)fname, "r"); if (fd != NULL) { while (!vim_fgets(line, MAXWLEN * 2, fd)) { fpos = fpos_next; fpos_next = ftell(fd); if (STRNCMP(word, line, len) == 0 && (line[len] == '/' || line[len] < ' ')) { /* Found duplicate word. Remove it by writing a '#' at * the start of the line. Mixing reading and writing * doesn't work for all systems, close the file first. */ fclose(fd); fd = mch_fopen((char *)fname, "r+"); if (fd == NULL) break; if (fseek(fd, fpos, SEEK_SET) == 0) { fputc('#', fd); if (undo) { home_replace(NULL, fname, NameBuff, MAXPATHL, TRUE); smsg((char_u *)_("Word removed from %s"), NameBuff); } } fseek(fd, fpos_next, SEEK_SET); } } if (fd != NULL) fclose(fd); } } if (!undo) { fd = mch_fopen((char *)fname, "a"); if (fd == NULL && new_spf) { char_u *p; /* We just initialized the 'spellfile' option and can't open the * file. We may need to create the "spell" directory first. We * already checked the runtime directory is writable in * init_spellfile(). */ if (!dir_of_file_exists(fname) && (p = gettail_sep(fname)) != fname) { int c = *p; /* The directory doesn't exist. Try creating it and opening * the file again. */ *p = NUL; vim_mkdir(fname, 0755); *p = c; fd = mch_fopen((char *)fname, "a"); } } if (fd == NULL) EMSG2(_(e_notopen), fname); else { if (bad) fprintf(fd, "%.*s/!\n", len, word); else fprintf(fd, "%.*s\n", len, word); fclose(fd); home_replace(NULL, fname, NameBuff, MAXPATHL, TRUE); smsg((char_u *)_("Word added to %s"), NameBuff); } } if (fd != NULL) { /* Update the .add.spl file. */ mkspell(1, &fname, FALSE, TRUE, TRUE); /* If the .add file is edited somewhere, reload it. */ if (buf != NULL) buf_reload(buf, buf->b_orig_mode); redraw_all_later(SOME_VALID); } vim_free(fnamebuf); } /* * Initialize 'spellfile' for the current buffer. */ static void init_spellfile() { char_u *buf; int l; char_u *fname; char_u *rtp; char_u *lend; int aspath = FALSE; char_u *lstart = curbuf->b_s.b_p_spl; if (*curwin->w_s->b_p_spl != NUL && curwin->w_s->b_langp.ga_len > 0) { buf = alloc(MAXPATHL); if (buf == NULL) return; /* Find the end of the language name. Exclude the region. If there * is a path separator remember the start of the tail. */ for (lend = curwin->w_s->b_p_spl; *lend != NUL && vim_strchr((char_u *)",._", *lend) == NULL; ++lend) if (vim_ispathsep(*lend)) { aspath = TRUE; lstart = lend + 1; } /* Loop over all entries in 'runtimepath'. Use the first one where we * are allowed to write. */ rtp = p_rtp; while (*rtp != NUL) { if (aspath) /* Use directory of an entry with path, e.g., for * "/dir/lg.utf-8.spl" use "/dir". */ vim_strncpy(buf, curbuf->b_s.b_p_spl, lstart - curbuf->b_s.b_p_spl - 1); else /* Copy the path from 'runtimepath' to buf[]. */ copy_option_part(&rtp, buf, MAXPATHL, ","); if (filewritable(buf) == 2) { /* Use the first language name from 'spelllang' and the * encoding used in the first loaded .spl file. */ if (aspath) vim_strncpy(buf, curbuf->b_s.b_p_spl, lend - curbuf->b_s.b_p_spl); else { /* Create the "spell" directory if it doesn't exist yet. */ l = (int)STRLEN(buf); vim_snprintf((char *)buf + l, MAXPATHL - l, "/spell"); if (filewritable(buf) != 2) vim_mkdir(buf, 0755); l = (int)STRLEN(buf); vim_snprintf((char *)buf + l, MAXPATHL - l, "/%.*s", (int)(lend - lstart), lstart); } l = (int)STRLEN(buf); fname = LANGP_ENTRY(curwin->w_s->b_langp, 0) ->lp_slang->sl_fname; vim_snprintf((char *)buf + l, MAXPATHL - l, ".%s.add", fname != NULL && strstr((char *)gettail(fname), ".ascii.") != NULL ? (char_u *)"ascii" : spell_enc()); set_option_value((char_u *)"spellfile", 0L, buf, OPT_LOCAL); break; } aspath = FALSE; } vim_free(buf); } } /* * Init the chartab used for spelling for ASCII. * EBCDIC is not supported! */ static void clear_spell_chartab(sp) spelltab_T *sp; { int i; /* Init everything to FALSE. */ vim_memset(sp->st_isw, FALSE, sizeof(sp->st_isw)); vim_memset(sp->st_isu, FALSE, sizeof(sp->st_isu)); for (i = 0; i < 256; ++i) { sp->st_fold[i] = i; sp->st_upper[i] = i; } /* We include digits. A word shouldn't start with a digit, but handling * that is done separately. */ for (i = '0'; i <= '9'; ++i) sp->st_isw[i] = TRUE; for (i = 'A'; i <= 'Z'; ++i) { sp->st_isw[i] = TRUE; sp->st_isu[i] = TRUE; sp->st_fold[i] = i + 0x20; } for (i = 'a'; i <= 'z'; ++i) { sp->st_isw[i] = TRUE; sp->st_upper[i] = i - 0x20; } } /* * Init the chartab used for spelling. Only depends on 'encoding'. * Called once while starting up and when 'encoding' changes. * The default is to use isalpha(), but the spell file should define the word * characters to make it possible that 'encoding' differs from the current * locale. For utf-8 we don't use isalpha() but our own functions. */ void init_spell_chartab() { int i; did_set_spelltab = FALSE; clear_spell_chartab(&spelltab); #ifdef FEAT_MBYTE if (enc_dbcs) { /* DBCS: assume double-wide characters are word characters. */ for (i = 128; i <= 255; ++i) if (MB_BYTE2LEN(i) == 2) spelltab.st_isw[i] = TRUE; } else if (enc_utf8) { for (i = 128; i < 256; ++i) { int f = utf_fold(i); int u = utf_toupper(i); spelltab.st_isu[i] = utf_isupper(i); spelltab.st_isw[i] = spelltab.st_isu[i] || utf_islower(i); /* The folded/upper-cased value is different between latin1 and * utf8 for 0xb5, causing E763 for no good reason. Use the latin1 * value for utf-8 to avoid this. */ spelltab.st_fold[i] = (f < 256) ? f : i; spelltab.st_upper[i] = (u < 256) ? u : i; } } else #endif { /* Rough guess: use locale-dependent library functions. */ for (i = 128; i < 256; ++i) { if (MB_ISUPPER(i)) { spelltab.st_isw[i] = TRUE; spelltab.st_isu[i] = TRUE; spelltab.st_fold[i] = MB_TOLOWER(i); } else if (MB_ISLOWER(i)) { spelltab.st_isw[i] = TRUE; spelltab.st_upper[i] = MB_TOUPPER(i); } } } } /* * Set the spell character tables from strings in the affix file. */ static int set_spell_chartab(fol, low, upp) char_u *fol; char_u *low; char_u *upp; { /* We build the new tables here first, so that we can compare with the * previous one. */ spelltab_T new_st; char_u *pf = fol, *pl = low, *pu = upp; int f, l, u; clear_spell_chartab(&new_st); while (*pf != NUL) { if (*pl == NUL || *pu == NUL) { EMSG(_(e_affform)); return FAIL; } #ifdef FEAT_MBYTE f = mb_ptr2char_adv(&pf); l = mb_ptr2char_adv(&pl); u = mb_ptr2char_adv(&pu); #else f = *pf++; l = *pl++; u = *pu++; #endif /* Every character that appears is a word character. */ if (f < 256) new_st.st_isw[f] = TRUE; if (l < 256) new_st.st_isw[l] = TRUE; if (u < 256) new_st.st_isw[u] = TRUE; /* if "LOW" and "FOL" are not the same the "LOW" char needs * case-folding */ if (l < 256 && l != f) { if (f >= 256) { EMSG(_(e_affrange)); return FAIL; } new_st.st_fold[l] = f; } /* if "UPP" and "FOL" are not the same the "UPP" char needs * case-folding, it's upper case and the "UPP" is the upper case of * "FOL" . */ if (u < 256 && u != f) { if (f >= 256) { EMSG(_(e_affrange)); return FAIL; } new_st.st_fold[u] = f; new_st.st_isu[u] = TRUE; new_st.st_upper[f] = u; } } if (*pl != NUL || *pu != NUL) { EMSG(_(e_affform)); return FAIL; } return set_spell_finish(&new_st); } /* * Set the spell character tables from strings in the .spl file. */ static void set_spell_charflags(flags, cnt, fol) char_u *flags; int cnt; /* length of "flags" */ char_u *fol; { /* We build the new tables here first, so that we can compare with the * previous one. */ spelltab_T new_st; int i; char_u *p = fol; int c; clear_spell_chartab(&new_st); for (i = 0; i < 128; ++i) { if (i < cnt) { new_st.st_isw[i + 128] = (flags[i] & CF_WORD) != 0; new_st.st_isu[i + 128] = (flags[i] & CF_UPPER) != 0; } if (*p != NUL) { #ifdef FEAT_MBYTE c = mb_ptr2char_adv(&p); #else c = *p++; #endif new_st.st_fold[i + 128] = c; if (i + 128 != c && new_st.st_isu[i + 128] && c < 256) new_st.st_upper[c] = i + 128; } } (void)set_spell_finish(&new_st); } static int set_spell_finish(new_st) spelltab_T *new_st; { int i; if (did_set_spelltab) { /* check that it's the same table */ for (i = 0; i < 256; ++i) { if (spelltab.st_isw[i] != new_st->st_isw[i] || spelltab.st_isu[i] != new_st->st_isu[i] || spelltab.st_fold[i] != new_st->st_fold[i] || spelltab.st_upper[i] != new_st->st_upper[i]) { EMSG(_("E763: Word characters differ between spell files")); return FAIL; } } } else { /* copy the new spelltab into the one being used */ spelltab = *new_st; did_set_spelltab = TRUE; } return OK; } /* * Return TRUE if "p" points to a word character. * As a special case we see "midword" characters as word character when it is * followed by a word character. This finds they'there but not 'they there'. * Thus this only works properly when past the first character of the word. */ static int spell_iswordp(p, wp) char_u *p; win_T *wp; /* buffer used */ { #ifdef FEAT_MBYTE char_u *s; int l; int c; if (has_mbyte) { l = MB_BYTE2LEN(*p); s = p; if (l == 1) { /* be quick for ASCII */ if (wp->w_s->b_spell_ismw[*p]) s = p + 1; /* skip a mid-word character */ } else { c = mb_ptr2char(p); if (c < 256 ? wp->w_s->b_spell_ismw[c] : (wp->w_s->b_spell_ismw_mb != NULL && vim_strchr(wp->w_s->b_spell_ismw_mb, c) != NULL)) s = p + l; } c = mb_ptr2char(s); if (c > 255) return spell_mb_isword_class(mb_get_class(s)); return spelltab.st_isw[c]; } #endif return spelltab.st_isw[wp->w_s->b_spell_ismw[*p] ? p[1] : p[0]]; } /* * Return TRUE if "p" points to a word character. * Unlike spell_iswordp() this doesn't check for "midword" characters. */ static int spell_iswordp_nmw(p) char_u *p; { #ifdef FEAT_MBYTE int c; if (has_mbyte) { c = mb_ptr2char(p); if (c > 255) return spell_mb_isword_class(mb_get_class(p)); return spelltab.st_isw[c]; } #endif return spelltab.st_isw[*p]; } #ifdef FEAT_MBYTE /* * Return TRUE if word class indicates a word character. * Only for characters above 255. * Unicode subscript and superscript are not considered word characters. */ static int spell_mb_isword_class(cl) int cl; { return cl >= 2 && cl != 0x2070 && cl != 0x2080; } /* * Return TRUE if "p" points to a word character. * Wide version of spell_iswordp(). */ static int spell_iswordp_w(p, wp) int *p; win_T *wp; { int *s; if (*p < 256 ? wp->w_s->b_spell_ismw[*p] : (wp->w_s->b_spell_ismw_mb != NULL && vim_strchr(wp->w_s->b_spell_ismw_mb, *p) != NULL)) s = p + 1; else s = p; if (*s > 255) { if (enc_utf8) return spell_mb_isword_class(utf_class(*s)); if (enc_dbcs) return dbcs_class((unsigned)*s >> 8, *s & 0xff) >= 2; return 0; } return spelltab.st_isw[*s]; } #endif /* * Write the table with prefix conditions to the .spl file. * When "fd" is NULL only count the length of what is written. */ static int write_spell_prefcond(fd, gap) FILE *fd; garray_T *gap; { int i; char_u *p; int len; int totlen; size_t x = 1; /* collect return value of fwrite() */ if (fd != NULL) put_bytes(fd, (long_u)gap->ga_len, 2); /* <prefcondcnt> */ totlen = 2 + gap->ga_len; /* length of <prefcondcnt> and <condlen> bytes */ for (i = 0; i < gap->ga_len; ++i) { /* <prefcond> : <condlen> <condstr> */ p = ((char_u **)gap->ga_data)[i]; if (p != NULL) { len = (int)STRLEN(p); if (fd != NULL) { fputc(len, fd); x &= fwrite(p, (size_t)len, (size_t)1, fd); } totlen += len; } else if (fd != NULL) fputc(0, fd); } return totlen; } /* * Case-fold "str[len]" into "buf[buflen]". The result is NUL terminated. * Uses the character definitions from the .spl file. * When using a multi-byte 'encoding' the length may change! * Returns FAIL when something wrong. */ static int spell_casefold(str, len, buf, buflen) char_u *str; int len; char_u *buf; int buflen; { int i; if (len >= buflen) { buf[0] = NUL; return FAIL; /* result will not fit */ } #ifdef FEAT_MBYTE if (has_mbyte) { int outi = 0; char_u *p; int c; /* Fold one character at a time. */ for (p = str; p < str + len; ) { if (outi + MB_MAXBYTES > buflen) { buf[outi] = NUL; return FAIL; } c = mb_cptr2char_adv(&p); outi += mb_char2bytes(SPELL_TOFOLD(c), buf + outi); } buf[outi] = NUL; } else #endif { /* Be quick for non-multibyte encodings. */ for (i = 0; i < len; ++i) buf[i] = spelltab.st_fold[str[i]]; buf[i] = NUL; } return OK; } /* values for sps_flags */ #define SPS_BEST 1 #define SPS_FAST 2 #define SPS_DOUBLE 4 static int sps_flags = SPS_BEST; /* flags from 'spellsuggest' */ static int sps_limit = 9999; /* max nr of suggestions given */ /* * Check the 'spellsuggest' option. Return FAIL if it's wrong. * Sets "sps_flags" and "sps_limit". */ int spell_check_sps() { char_u *p; char_u *s; char_u buf[MAXPATHL]; int f; sps_flags = 0; sps_limit = 9999; for (p = p_sps; *p != NUL; ) { copy_option_part(&p, buf, MAXPATHL, ","); f = 0; if (VIM_ISDIGIT(*buf)) { s = buf; sps_limit = getdigits(&s); if (*s != NUL && !VIM_ISDIGIT(*s)) f = -1; } else if (STRCMP(buf, "best") == 0) f = SPS_BEST; else if (STRCMP(buf, "fast") == 0) f = SPS_FAST; else if (STRCMP(buf, "double") == 0) f = SPS_DOUBLE; else if (STRNCMP(buf, "expr:", 5) != 0 && STRNCMP(buf, "file:", 5) != 0) f = -1; if (f == -1 || (sps_flags != 0 && f != 0)) { sps_flags = SPS_BEST; sps_limit = 9999; return FAIL; } if (f != 0) sps_flags = f; } if (sps_flags == 0) sps_flags = SPS_BEST; return OK; } /* * "z?": Find badly spelled word under or after the cursor. * Give suggestions for the properly spelled word. * In Visual mode use the highlighted word as the bad word. * When "count" is non-zero use that suggestion. */ void spell_suggest(count) int count; { char_u *line; pos_T prev_cursor = curwin->w_cursor; char_u wcopy[MAXWLEN + 2]; char_u *p; int i; int c; suginfo_T sug; suggest_T *stp; int mouse_used; int need_cap; int limit; int selected = count; int badlen = 0; int msg_scroll_save = msg_scroll; if (no_spell_checking(curwin)) return; #ifdef FEAT_VISUAL if (VIsual_active) { /* Use the Visually selected text as the bad word. But reject * a multi-line selection. */ if (curwin->w_cursor.lnum != VIsual.lnum) { vim_beep(); return; } badlen = (int)curwin->w_cursor.col - (int)VIsual.col; if (badlen < 0) badlen = -badlen; else curwin->w_cursor.col = VIsual.col; ++badlen; end_visual_mode(); } else #endif /* Find the start of the badly spelled word. */ if (spell_move_to(curwin, FORWARD, TRUE, TRUE, NULL) == 0 || curwin->w_cursor.col > prev_cursor.col) { /* No bad word or it starts after the cursor: use the word under the * cursor. */ curwin->w_cursor = prev_cursor; line = ml_get_curline(); p = line + curwin->w_cursor.col; /* Backup to before start of word. */ while (p > line && spell_iswordp_nmw(p)) mb_ptr_back(line, p); /* Forward to start of word. */ while (*p != NUL && !spell_iswordp_nmw(p)) mb_ptr_adv(p); if (!spell_iswordp_nmw(p)) /* No word found. */ { beep_flush(); return; } curwin->w_cursor.col = (colnr_T)(p - line); } /* Get the word and its length. */ /* Figure out if the word should be capitalised. */ need_cap = check_need_cap(curwin->w_cursor.lnum, curwin->w_cursor.col); /* Make a copy of current line since autocommands may free the line. */ line = vim_strsave(ml_get_curline()); if (line == NULL) goto skip; /* Get the list of suggestions. Limit to 'lines' - 2 or the number in * 'spellsuggest', whatever is smaller. */ if (sps_limit > (int)Rows - 2) limit = (int)Rows - 2; else limit = sps_limit; spell_find_suggest(line + curwin->w_cursor.col, badlen, &sug, limit, TRUE, need_cap, TRUE); if (sug.su_ga.ga_len == 0) MSG(_("Sorry, no suggestions")); else if (count > 0) { if (count > sug.su_ga.ga_len) smsg((char_u *)_("Sorry, only %ld suggestions"), (long)sug.su_ga.ga_len); } else { vim_free(repl_from); repl_from = NULL; vim_free(repl_to); repl_to = NULL; #ifdef FEAT_RIGHTLEFT /* When 'rightleft' is set the list is drawn right-left. */ cmdmsg_rl = curwin->w_p_rl; if (cmdmsg_rl) msg_col = Columns - 1; #endif /* List the suggestions. */ msg_start(); msg_row = Rows - 1; /* for when 'cmdheight' > 1 */ lines_left = Rows; /* avoid more prompt */ vim_snprintf((char *)IObuff, IOSIZE, _("Change \"%.*s\" to:"), sug.su_badlen, sug.su_badptr); #ifdef FEAT_RIGHTLEFT if (cmdmsg_rl && STRNCMP(IObuff, "Change", 6) == 0) { /* And now the rabbit from the high hat: Avoid showing the * untranslated message rightleft. */ vim_snprintf((char *)IObuff, IOSIZE, ":ot \"%.*s\" egnahC", sug.su_badlen, sug.su_badptr); } #endif msg_puts(IObuff); msg_clr_eos(); msg_putchar('\n'); msg_scroll = TRUE; for (i = 0; i < sug.su_ga.ga_len; ++i) { stp = &SUG(sug.su_ga, i); /* The suggested word may replace only part of the bad word, add * the not replaced part. */ vim_strncpy(wcopy, stp->st_word, MAXWLEN); if (sug.su_badlen > stp->st_orglen) vim_strncpy(wcopy + stp->st_wordlen, sug.su_badptr + stp->st_orglen, sug.su_badlen - stp->st_orglen); vim_snprintf((char *)IObuff, IOSIZE, "%2d", i + 1); #ifdef FEAT_RIGHTLEFT if (cmdmsg_rl) rl_mirror(IObuff); #endif msg_puts(IObuff); vim_snprintf((char *)IObuff, IOSIZE, " \"%s\"", wcopy); msg_puts(IObuff); /* The word may replace more than "su_badlen". */ if (sug.su_badlen < stp->st_orglen) { vim_snprintf((char *)IObuff, IOSIZE, _(" < \"%.*s\""), stp->st_orglen, sug.su_badptr); msg_puts(IObuff); } if (p_verbose > 0) { /* Add the score. */ if (sps_flags & (SPS_DOUBLE | SPS_BEST)) vim_snprintf((char *)IObuff, IOSIZE, " (%s%d - %d)", stp->st_salscore ? "s " : "", stp->st_score, stp->st_altscore); else vim_snprintf((char *)IObuff, IOSIZE, " (%d)", stp->st_score); #ifdef FEAT_RIGHTLEFT if (cmdmsg_rl) /* Mirror the numbers, but keep the leading space. */ rl_mirror(IObuff + 1); #endif msg_advance(30); msg_puts(IObuff); } msg_putchar('\n'); } #ifdef FEAT_RIGHTLEFT cmdmsg_rl = FALSE; msg_col = 0; #endif /* Ask for choice. */ selected = prompt_for_number(&mouse_used); if (mouse_used) selected -= lines_left; lines_left = Rows; /* avoid more prompt */ /* don't delay for 'smd' in normal_cmd() */ msg_scroll = msg_scroll_save; } if (selected > 0 && selected <= sug.su_ga.ga_len && u_save_cursor() == OK) { /* Save the from and to text for :spellrepall. */ stp = &SUG(sug.su_ga, selected - 1); if (sug.su_badlen > stp->st_orglen) { /* Replacing less than "su_badlen", append the remainder to * repl_to. */ repl_from = vim_strnsave(sug.su_badptr, sug.su_badlen); vim_snprintf((char *)IObuff, IOSIZE, "%s%.*s", stp->st_word, sug.su_badlen - stp->st_orglen, sug.su_badptr + stp->st_orglen); repl_to = vim_strsave(IObuff); } else { /* Replacing su_badlen or more, use the whole word. */ repl_from = vim_strnsave(sug.su_badptr, stp->st_orglen); repl_to = vim_strsave(stp->st_word); } /* Replace the word. */ p = alloc((unsigned)STRLEN(line) - stp->st_orglen + stp->st_wordlen + 1); if (p != NULL) { c = (int)(sug.su_badptr - line); mch_memmove(p, line, c); STRCPY(p + c, stp->st_word); STRCAT(p, sug.su_badptr + stp->st_orglen); ml_replace(curwin->w_cursor.lnum, p, FALSE); curwin->w_cursor.col = c; /* For redo we use a change-word command. */ ResetRedobuff(); AppendToRedobuff((char_u *)"ciw"); AppendToRedobuffLit(p + c, stp->st_wordlen + sug.su_badlen - stp->st_orglen); AppendCharToRedobuff(ESC); /* After this "p" may be invalid. */ changed_bytes(curwin->w_cursor.lnum, c); } } else curwin->w_cursor = prev_cursor; spell_find_cleanup(&sug); skip: vim_free(line); } /* * Check if the word at line "lnum" column "col" is required to start with a * capital. This uses 'spellcapcheck' of the current buffer. */ static int check_need_cap(lnum, col) linenr_T lnum; colnr_T col; { int need_cap = FALSE; char_u *line; char_u *line_copy = NULL; char_u *p; colnr_T endcol; regmatch_T regmatch; if (curwin->w_s->b_cap_prog == NULL) return FALSE; line = ml_get_curline(); endcol = 0; if ((int)(skipwhite(line) - line) >= (int)col) { /* At start of line, check if previous line is empty or sentence * ends there. */ if (lnum == 1) need_cap = TRUE; else { line = ml_get(lnum - 1); if (*skipwhite(line) == NUL) need_cap = TRUE; else { /* Append a space in place of the line break. */ line_copy = concat_str(line, (char_u *)" "); line = line_copy; endcol = (colnr_T)STRLEN(line); } } } else endcol = col; if (endcol > 0) { /* Check if sentence ends before the bad word. */ regmatch.regprog = curwin->w_s->b_cap_prog; regmatch.rm_ic = FALSE; p = line + endcol; for (;;) { mb_ptr_back(line, p); if (p == line || spell_iswordp_nmw(p)) break; if (vim_regexec(&regmatch, p, 0) && regmatch.endp[0] == line + endcol) { need_cap = TRUE; break; } } } vim_free(line_copy); return need_cap; } /* * ":spellrepall" */ void ex_spellrepall(eap) exarg_T *eap UNUSED; { pos_T pos = curwin->w_cursor; char_u *frompat; int addlen; char_u *line; char_u *p; int save_ws = p_ws; linenr_T prev_lnum = 0; if (repl_from == NULL || repl_to == NULL) { EMSG(_("E752: No previous spell replacement")); return; } addlen = (int)(STRLEN(repl_to) - STRLEN(repl_from)); frompat = alloc((unsigned)STRLEN(repl_from) + 7); if (frompat == NULL) return; sprintf((char *)frompat, "\\V\\<%s\\>", repl_from); p_ws = FALSE; sub_nsubs = 0; sub_nlines = 0; curwin->w_cursor.lnum = 0; while (!got_int) { if (do_search(NULL, '/', frompat, 1L, SEARCH_KEEP, NULL) == 0 || u_save_cursor() == FAIL) break; /* Only replace when the right word isn't there yet. This happens * when changing "etc" to "etc.". */ line = ml_get_curline(); if (addlen <= 0 || STRNCMP(line + curwin->w_cursor.col, repl_to, STRLEN(repl_to)) != 0) { p = alloc((unsigned)STRLEN(line) + addlen + 1); if (p == NULL) break; mch_memmove(p, line, curwin->w_cursor.col); STRCPY(p + curwin->w_cursor.col, repl_to); STRCAT(p, line + curwin->w_cursor.col + STRLEN(repl_from)); ml_replace(curwin->w_cursor.lnum, p, FALSE); changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col); if (curwin->w_cursor.lnum != prev_lnum) { ++sub_nlines; prev_lnum = curwin->w_cursor.lnum; } ++sub_nsubs; } curwin->w_cursor.col += (colnr_T)STRLEN(repl_to); } p_ws = save_ws; curwin->w_cursor = pos; vim_free(frompat); if (sub_nsubs == 0) EMSG2(_("E753: Not found: %s"), repl_from); else do_sub_msg(FALSE); } /* * Find spell suggestions for "word". Return them in the growarray "*gap" as * a list of allocated strings. */ void spell_suggest_list(gap, word, maxcount, need_cap, interactive) garray_T *gap; char_u *word; int maxcount; /* maximum nr of suggestions */ int need_cap; /* 'spellcapcheck' matched */ int interactive; { suginfo_T sug; int i; suggest_T *stp; char_u *wcopy; spell_find_suggest(word, 0, &sug, maxcount, FALSE, need_cap, interactive); /* Make room in "gap". */ ga_init2(gap, sizeof(char_u *), sug.su_ga.ga_len + 1); if (ga_grow(gap, sug.su_ga.ga_len) == OK) { for (i = 0; i < sug.su_ga.ga_len; ++i) { stp = &SUG(sug.su_ga, i); /* The suggested word may replace only part of "word", add the not * replaced part. */ wcopy = alloc(stp->st_wordlen + (unsigned)STRLEN(sug.su_badptr + stp->st_orglen) + 1); if (wcopy == NULL) break; STRCPY(wcopy, stp->st_word); STRCPY(wcopy + stp->st_wordlen, sug.su_badptr + stp->st_orglen); ((char_u **)gap->ga_data)[gap->ga_len++] = wcopy; } } spell_find_cleanup(&sug); } /* * Find spell suggestions for the word at the start of "badptr". * Return the suggestions in "su->su_ga". * The maximum number of suggestions is "maxcount". * Note: does use info for the current window. * This is based on the mechanisms of Aspell, but completely reimplemented. */ static void spell_find_suggest(badptr, badlen, su, maxcount, banbadword, need_cap, interactive) char_u *badptr; int badlen; /* length of bad word or 0 if unknown */ suginfo_T *su; int maxcount; int banbadword; /* don't include badword in suggestions */ int need_cap; /* word should start with capital */ int interactive; { hlf_T attr = HLF_COUNT; char_u buf[MAXPATHL]; char_u *p; int do_combine = FALSE; char_u *sps_copy; #ifdef FEAT_EVAL static int expr_busy = FALSE; #endif int c; int i; langp_T *lp; /* * Set the info in "*su". */ vim_memset(su, 0, sizeof(suginfo_T)); ga_init2(&su->su_ga, (int)sizeof(suggest_T), 10); ga_init2(&su->su_sga, (int)sizeof(suggest_T), 10); if (*badptr == NUL) return; hash_init(&su->su_banned); su->su_badptr = badptr; if (badlen != 0) su->su_badlen = badlen; else su->su_badlen = spell_check(curwin, su->su_badptr, &attr, NULL, FALSE); su->su_maxcount = maxcount; su->su_maxscore = SCORE_MAXINIT; if (su->su_badlen >= MAXWLEN) su->su_badlen = MAXWLEN - 1; /* just in case */ vim_strncpy(su->su_badword, su->su_badptr, su->su_badlen); (void)spell_casefold(su->su_badptr, su->su_badlen, su->su_fbadword, MAXWLEN); /* get caps flags for bad word */ su->su_badflags = badword_captype(su->su_badptr, su->su_badptr + su->su_badlen); if (need_cap) su->su_badflags |= WF_ONECAP; /* Find the default language for sound folding. We simply use the first * one in 'spelllang' that supports sound folding. That's good for when * using multiple files for one language, it's not that bad when mixing * languages (e.g., "pl,en"). */ for (i = 0; i < curbuf->b_s.b_langp.ga_len; ++i) { lp = LANGP_ENTRY(curbuf->b_s.b_langp, i); if (lp->lp_sallang != NULL) { su->su_sallang = lp->lp_sallang; break; } } /* Soundfold the bad word with the default sound folding, so that we don't * have to do this many times. */ if (su->su_sallang != NULL) spell_soundfold(su->su_sallang, su->su_fbadword, TRUE, su->su_sal_badword); /* If the word is not capitalised and spell_check() doesn't consider the * word to be bad then it might need to be capitalised. Add a suggestion * for that. */ c = PTR2CHAR(su->su_badptr); if (!SPELL_ISUPPER(c) && attr == HLF_COUNT) { make_case_word(su->su_badword, buf, WF_ONECAP); add_suggestion(su, &su->su_ga, buf, su->su_badlen, SCORE_ICASE, 0, TRUE, su->su_sallang, FALSE); } /* Ban the bad word itself. It may appear in another region. */ if (banbadword) add_banned(su, su->su_badword); /* Make a copy of 'spellsuggest', because the expression may change it. */ sps_copy = vim_strsave(p_sps); if (sps_copy == NULL) return; /* Loop over the items in 'spellsuggest'. */ for (p = sps_copy; *p != NUL; ) { copy_option_part(&p, buf, MAXPATHL, ","); if (STRNCMP(buf, "expr:", 5) == 0) { #ifdef FEAT_EVAL /* Evaluate an expression. Skip this when called recursively, * when using spellsuggest() in the expression. */ if (!expr_busy) { expr_busy = TRUE; spell_suggest_expr(su, buf + 5); expr_busy = FALSE; } #endif } else if (STRNCMP(buf, "file:", 5) == 0) /* Use list of suggestions in a file. */ spell_suggest_file(su, buf + 5); else { /* Use internal method. */ spell_suggest_intern(su, interactive); if (sps_flags & SPS_DOUBLE) do_combine = TRUE; } } vim_free(sps_copy); if (do_combine) /* Combine the two list of suggestions. This must be done last, * because sorting changes the order again. */ score_combine(su); } #ifdef FEAT_EVAL /* * Find suggestions by evaluating expression "expr". */ static void spell_suggest_expr(su, expr) suginfo_T *su; char_u *expr; { list_T *list; listitem_T *li; int score; char_u *p; /* The work is split up in a few parts to avoid having to export * suginfo_T. * First evaluate the expression and get the resulting list. */ list = eval_spell_expr(su->su_badword, expr); if (list != NULL) { /* Loop over the items in the list. */ for (li = list->lv_first; li != NULL; li = li->li_next) if (li->li_tv.v_type == VAR_LIST) { /* Get the word and the score from the items. */ score = get_spellword(li->li_tv.vval.v_list, &p); if (score >= 0 && score <= su->su_maxscore) add_suggestion(su, &su->su_ga, p, su->su_badlen, score, 0, TRUE, su->su_sallang, FALSE); } list_unref(list); } /* Remove bogus suggestions, sort and truncate at "maxcount". */ check_suggestions(su, &su->su_ga); (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount); } #endif /* * Find suggestions in file "fname". Used for "file:" in 'spellsuggest'. */ static void spell_suggest_file(su, fname) suginfo_T *su; char_u *fname; { FILE *fd; char_u line[MAXWLEN * 2]; char_u *p; int len; char_u cword[MAXWLEN]; /* Open the file. */ fd = mch_fopen((char *)fname, "r"); if (fd == NULL) { EMSG2(_(e_notopen), fname); return; } /* Read it line by line. */ while (!vim_fgets(line, MAXWLEN * 2, fd) && !got_int) { line_breakcheck(); p = vim_strchr(line, '/'); if (p == NULL) continue; /* No Tab found, just skip the line. */ *p++ = NUL; if (STRICMP(su->su_badword, line) == 0) { /* Match! Isolate the good word, until CR or NL. */ for (len = 0; p[len] >= ' '; ++len) ; p[len] = NUL; /* If the suggestion doesn't have specific case duplicate the case * of the bad word. */ if (captype(p, NULL) == 0) { make_case_word(p, cword, su->su_badflags); p = cword; } add_suggestion(su, &su->su_ga, p, su->su_badlen, SCORE_FILE, 0, TRUE, su->su_sallang, FALSE); } } fclose(fd); /* Remove bogus suggestions, sort and truncate at "maxcount". */ check_suggestions(su, &su->su_ga); (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount); } /* * Find suggestions for the internal method indicated by "sps_flags". */ static void spell_suggest_intern(su, interactive) suginfo_T *su; int interactive; { /* * Load the .sug file(s) that are available and not done yet. */ suggest_load_files(); /* * 1. Try special cases, such as repeating a word: "the the" -> "the". * * Set a maximum score to limit the combination of operations that is * tried. */ suggest_try_special(su); /* * 2. Try inserting/deleting/swapping/changing a letter, use REP entries * from the .aff file and inserting a space (split the word). */ suggest_try_change(su); /* For the resulting top-scorers compute the sound-a-like score. */ if (sps_flags & SPS_DOUBLE) score_comp_sal(su); /* * 3. Try finding sound-a-like words. */ if ((sps_flags & SPS_FAST) == 0) { if (sps_flags & SPS_BEST) /* Adjust the word score for the suggestions found so far for how * they sounds like. */ rescore_suggestions(su); /* * While going through the soundfold tree "su_maxscore" is the score * for the soundfold word, limits the changes that are being tried, * and "su_sfmaxscore" the rescored score, which is set by * cleanup_suggestions(). * First find words with a small edit distance, because this is much * faster and often already finds the top-N suggestions. If we didn't * find many suggestions try again with a higher edit distance. * "sl_sounddone" is used to avoid doing the same word twice. */ suggest_try_soundalike_prep(); su->su_maxscore = SCORE_SFMAX1; su->su_sfmaxscore = SCORE_MAXINIT * 3; suggest_try_soundalike(su); if (su->su_ga.ga_len < SUG_CLEAN_COUNT(su)) { /* We didn't find enough matches, try again, allowing more * changes to the soundfold word. */ su->su_maxscore = SCORE_SFMAX2; suggest_try_soundalike(su); if (su->su_ga.ga_len < SUG_CLEAN_COUNT(su)) { /* Still didn't find enough matches, try again, allowing even * more changes to the soundfold word. */ su->su_maxscore = SCORE_SFMAX3; suggest_try_soundalike(su); } } su->su_maxscore = su->su_sfmaxscore; suggest_try_soundalike_finish(); } /* When CTRL-C was hit while searching do show the results. Only clear * got_int when using a command, not for spellsuggest(). */ ui_breakcheck(); if (interactive && got_int) { (void)vgetc(); got_int = FALSE; } if ((sps_flags & SPS_DOUBLE) == 0 && su->su_ga.ga_len != 0) { if (sps_flags & SPS_BEST) /* Adjust the word score for how it sounds like. */ rescore_suggestions(su); /* Remove bogus suggestions, sort and truncate at "maxcount". */ check_suggestions(su, &su->su_ga); (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount); } } /* * Load the .sug files for languages that have one and weren't loaded yet. */ static void suggest_load_files() { langp_T *lp; int lpi; slang_T *slang; char_u *dotp; FILE *fd; char_u buf[MAXWLEN]; int i; time_t timestamp; int wcount; int wordnr; garray_T ga; int c; /* Do this for all languages that support sound folding. */ for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi) { lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi); slang = lp->lp_slang; if (slang->sl_sugtime != 0 && !slang->sl_sugloaded) { /* Change ".spl" to ".sug" and open the file. When the file isn't * found silently skip it. Do set "sl_sugloaded" so that we * don't try again and again. */ slang->sl_sugloaded = TRUE; dotp = vim_strrchr(slang->sl_fname, '.'); if (dotp == NULL || fnamecmp(dotp, ".spl") != 0) continue; STRCPY(dotp, ".sug"); fd = mch_fopen((char *)slang->sl_fname, "r"); if (fd == NULL) goto nextone; /* * <SUGHEADER>: <fileID> <versionnr> <timestamp> */ for (i = 0; i < VIMSUGMAGICL; ++i) buf[i] = getc(fd); /* <fileID> */ if (STRNCMP(buf, VIMSUGMAGIC, VIMSUGMAGICL) != 0) { EMSG2(_("E778: This does not look like a .sug file: %s"), slang->sl_fname); goto nextone; } c = getc(fd); /* <versionnr> */ if (c < VIMSUGVERSION) { EMSG2(_("E779: Old .sug file, needs to be updated: %s"), slang->sl_fname); goto nextone; } else if (c > VIMSUGVERSION) { EMSG2(_("E780: .sug file is for newer version of Vim: %s"), slang->sl_fname); goto nextone; } /* Check the timestamp, it must be exactly the same as the one in * the .spl file. Otherwise the word numbers won't match. */ timestamp = get8ctime(fd); /* <timestamp> */ if (timestamp != slang->sl_sugtime) { EMSG2(_("E781: .sug file doesn't match .spl file: %s"), slang->sl_fname); goto nextone; } /* * <SUGWORDTREE>: <wordtree> * Read the trie with the soundfolded words. */ if (spell_read_tree(fd, &slang->sl_sbyts, &slang->sl_sidxs, FALSE, 0) != 0) { someerror: EMSG2(_("E782: error while reading .sug file: %s"), slang->sl_fname); slang_clear_sug(slang); goto nextone; } /* * <SUGTABLE>: <sugwcount> <sugline> ... * * Read the table with word numbers. We use a file buffer for * this, because it's so much like a file with lines. Makes it * possible to swap the info and save on memory use. */ slang->sl_sugbuf = open_spellbuf(); if (slang->sl_sugbuf == NULL) goto someerror; /* <sugwcount> */ wcount = get4c(fd); if (wcount < 0) goto someerror; /* Read all the wordnr lists into the buffer, one NUL terminated * list per line. */ ga_init2(&ga, 1, 100); for (wordnr = 0; wordnr < wcount; ++wordnr) { ga.ga_len = 0; for (;;) { c = getc(fd); /* <sugline> */ if (c < 0 || ga_grow(&ga, 1) == FAIL) goto someerror; ((char_u *)ga.ga_data)[ga.ga_len++] = c; if (c == NUL) break; } if (ml_append_buf(slang->sl_sugbuf, (linenr_T)wordnr, ga.ga_data, ga.ga_len, TRUE) == FAIL) goto someerror; } ga_clear(&ga); /* * Need to put word counts in the word tries, so that we can find * a word by its number. */ tree_count_words(slang->sl_fbyts, slang->sl_fidxs); tree_count_words(slang->sl_sbyts, slang->sl_sidxs); nextone: if (fd != NULL) fclose(fd); STRCPY(dotp, ".spl"); } } } /* * Fill in the wordcount fields for a trie. * Returns the total number of words. */ static void tree_count_words(byts, idxs) char_u *byts; idx_T *idxs; { int depth; idx_T arridx[MAXWLEN]; int curi[MAXWLEN]; int c; idx_T n; int wordcount[MAXWLEN]; arridx[0] = 0; curi[0] = 1; wordcount[0] = 0; depth = 0; while (depth >= 0 && !got_int) { if (curi[depth] > byts[arridx[depth]]) { /* Done all bytes at this node, go up one level. */ idxs[arridx[depth]] = wordcount[depth]; if (depth > 0) wordcount[depth - 1] += wordcount[depth]; --depth; fast_breakcheck(); } else { /* Do one more byte at this node. */ n = arridx[depth] + curi[depth]; ++curi[depth]; c = byts[n]; if (c == 0) { /* End of word, count it. */ ++wordcount[depth]; /* Skip over any other NUL bytes (same word with different * flags). */ while (byts[n + 1] == 0) { ++n; ++curi[depth]; } } else { /* Normal char, go one level deeper to count the words. */ ++depth; arridx[depth] = idxs[n]; curi[depth] = 1; wordcount[depth] = 0; } } } } /* * Free the info put in "*su" by spell_find_suggest(). */ static void spell_find_cleanup(su) suginfo_T *su; { int i; /* Free the suggestions. */ for (i = 0; i < su->su_ga.ga_len; ++i) vim_free(SUG(su->su_ga, i).st_word); ga_clear(&su->su_ga); for (i = 0; i < su->su_sga.ga_len; ++i) vim_free(SUG(su->su_sga, i).st_word); ga_clear(&su->su_sga); /* Free the banned words. */ hash_clear_all(&su->su_banned, 0); } /* * Make a copy of "word", with the first letter upper or lower cased, to * "wcopy[MAXWLEN]". "word" must not be empty. * The result is NUL terminated. */ static void onecap_copy(word, wcopy, upper) char_u *word; char_u *wcopy; int upper; /* TRUE: first letter made upper case */ { char_u *p; int c; int l; p = word; #ifdef FEAT_MBYTE if (has_mbyte) c = mb_cptr2char_adv(&p); else #endif c = *p++; if (upper) c = SPELL_TOUPPER(c); else c = SPELL_TOFOLD(c); #ifdef FEAT_MBYTE if (has_mbyte) l = mb_char2bytes(c, wcopy); else #endif { l = 1; wcopy[0] = c; } vim_strncpy(wcopy + l, p, MAXWLEN - l - 1); } /* * Make a copy of "word" with all the letters upper cased into * "wcopy[MAXWLEN]". The result is NUL terminated. */ static void allcap_copy(word, wcopy) char_u *word; char_u *wcopy; { char_u *s; char_u *d; int c; d = wcopy; for (s = word; *s != NUL; ) { #ifdef FEAT_MBYTE if (has_mbyte) c = mb_cptr2char_adv(&s); else #endif c = *s++; #ifdef FEAT_MBYTE /* We only change 0xdf to SS when we are certain latin1 is used. It * would cause weird errors in other 8-bit encodings. */ if (enc_latin1like && c == 0xdf) { c = 'S'; if (d - wcopy >= MAXWLEN - 1) break; *d++ = c; } else #endif c = SPELL_TOUPPER(c); #ifdef FEAT_MBYTE if (has_mbyte) { if (d - wcopy >= MAXWLEN - MB_MAXBYTES) break; d += mb_char2bytes(c, d); } else #endif { if (d - wcopy >= MAXWLEN - 1) break; *d++ = c; } } *d = NUL; } /* * Try finding suggestions by recognizing specific situations. */ static void suggest_try_special(su) suginfo_T *su; { char_u *p; size_t len; int c; char_u word[MAXWLEN]; /* * Recognize a word that is repeated: "the the". */ p = skiptowhite(su->su_fbadword); len = p - su->su_fbadword; p = skipwhite(p); if (STRLEN(p) == len && STRNCMP(su->su_fbadword, p, len) == 0) { /* Include badflags: if the badword is onecap or allcap * use that for the goodword too: "The the" -> "The". */ c = su->su_fbadword[len]; su->su_fbadword[len] = NUL; make_case_word(su->su_fbadword, word, su->su_badflags); su->su_fbadword[len] = c; /* Give a soundalike score of 0, compute the score as if deleting one * character. */ add_suggestion(su, &su->su_ga, word, su->su_badlen, RESCORE(SCORE_REP, 0), 0, TRUE, su->su_sallang, FALSE); } } /* * Try finding suggestions by adding/removing/swapping letters. */ static void suggest_try_change(su) suginfo_T *su; { char_u fword[MAXWLEN]; /* copy of the bad word, case-folded */ int n; char_u *p; int lpi; langp_T *lp; /* We make a copy of the case-folded bad word, so that we can modify it * to find matches (esp. REP items). Append some more text, changing * chars after the bad word may help. */ STRCPY(fword, su->su_fbadword); n = (int)STRLEN(fword); p = su->su_badptr + su->su_badlen; (void)spell_casefold(p, (int)STRLEN(p), fword + n, MAXWLEN - n); for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi) { lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi); /* If reloading a spell file fails it's still in the list but * everything has been cleared. */ if (lp->lp_slang->sl_fbyts == NULL) continue; /* Try it for this language. Will add possible suggestions. */ suggest_trie_walk(su, lp, fword, FALSE); } } /* Check the maximum score, if we go over it we won't try this change. */ #define TRY_DEEPER(su, stack, depth, add) \ (stack[depth].ts_score + (add) < su->su_maxscore) /* * Try finding suggestions by adding/removing/swapping letters. * * This uses a state machine. At each node in the tree we try various * operations. When trying if an operation works "depth" is increased and the * stack[] is used to store info. This allows combinations, thus insert one * character, replace one and delete another. The number of changes is * limited by su->su_maxscore. * * After implementing this I noticed an article by Kemal Oflazer that * describes something similar: "Error-tolerant Finite State Recognition with * Applications to Morphological Analysis and Spelling Correction" (1996). * The implementation in the article is simplified and requires a stack of * unknown depth. The implementation here only needs a stack depth equal to * the length of the word. * * This is also used for the sound-folded word, "soundfold" is TRUE then. * The mechanism is the same, but we find a match with a sound-folded word * that comes from one or more original words. Each of these words may be * added, this is done by add_sound_suggest(). * Don't use: * the prefix tree or the keep-case tree * "su->su_badlen" * anything to do with upper and lower case * anything to do with word or non-word characters ("spell_iswordp()") * banned words * word flags (rare, region, compounding) * word splitting for now * "similar_chars()" * use "slang->sl_repsal" instead of "lp->lp_replang->sl_rep" */ static void suggest_trie_walk(su, lp, fword, soundfold) suginfo_T *su; langp_T *lp; char_u *fword; int soundfold; { char_u tword[MAXWLEN]; /* good word collected so far */ trystate_T stack[MAXWLEN]; char_u preword[MAXWLEN * 3]; /* word found with proper case; * concatenation of prefix compound * words and split word. NUL terminated * when going deeper but not when coming * back. */ char_u compflags[MAXWLEN]; /* compound flags, one for each word */ trystate_T *sp; int newscore; int score; char_u *byts, *fbyts, *pbyts; idx_T *idxs, *fidxs, *pidxs; int depth; int c, c2, c3; int n = 0; int flags; garray_T *gap; idx_T arridx; int len; char_u *p; fromto_T *ftp; int fl = 0, tl; int repextra = 0; /* extra bytes in fword[] from REP item */ slang_T *slang = lp->lp_slang; int fword_ends; int goodword_ends; #ifdef DEBUG_TRIEWALK /* Stores the name of the change made at each level. */ char_u changename[MAXWLEN][80]; #endif int breakcheckcount = 1000; int compound_ok; /* * Go through the whole case-fold tree, try changes at each node. * "tword[]" contains the word collected from nodes in the tree. * "fword[]" the word we are trying to match with (initially the bad * word). */ depth = 0; sp = &stack[0]; vim_memset(sp, 0, sizeof(trystate_T)); sp->ts_curi = 1; if (soundfold) { /* Going through the soundfold tree. */ byts = fbyts = slang->sl_sbyts; idxs = fidxs = slang->sl_sidxs; pbyts = NULL; pidxs = NULL; sp->ts_prefixdepth = PFD_NOPREFIX; sp->ts_state = STATE_START; } else { /* * When there are postponed prefixes we need to use these first. At * the end of the prefix we continue in the case-fold tree. */ fbyts = slang->sl_fbyts; fidxs = slang->sl_fidxs; pbyts = slang->sl_pbyts; pidxs = slang->sl_pidxs; if (pbyts != NULL) { byts = pbyts; idxs = pidxs; sp->ts_prefixdepth = PFD_PREFIXTREE; sp->ts_state = STATE_NOPREFIX; /* try without prefix first */ } else { byts = fbyts; idxs = fidxs; sp->ts_prefixdepth = PFD_NOPREFIX; sp->ts_state = STATE_START; } } /* * Loop to find all suggestions. At each round we either: * - For the current state try one operation, advance "ts_curi", * increase "depth". * - When a state is done go to the next, set "ts_state". * - When all states are tried decrease "depth". */ while (depth >= 0 && !got_int) { sp = &stack[depth]; switch (sp->ts_state) { case STATE_START: case STATE_NOPREFIX: /* * Start of node: Deal with NUL bytes, which means * tword[] may end here. */ arridx = sp->ts_arridx; /* current node in the tree */ len = byts[arridx]; /* bytes in this node */ arridx += sp->ts_curi; /* index of current byte */ if (sp->ts_prefixdepth == PFD_PREFIXTREE) { /* Skip over the NUL bytes, we use them later. */ for (n = 0; n < len && byts[arridx + n] == 0; ++n) ; sp->ts_curi += n; /* Always past NUL bytes now. */ n = (int)sp->ts_state; sp->ts_state = STATE_ENDNUL; sp->ts_save_badflags = su->su_badflags; /* At end of a prefix or at start of prefixtree: check for * following word. */ if (byts[arridx] == 0 || n == (int)STATE_NOPREFIX) { /* Set su->su_badflags to the caps type at this position. * Use the caps type until here for the prefix itself. */ #ifdef FEAT_MBYTE if (has_mbyte) n = nofold_len(fword, sp->ts_fidx, su->su_badptr); else #endif n = sp->ts_fidx; flags = badword_captype(su->su_badptr, su->su_badptr + n); su->su_badflags = badword_captype(su->su_badptr + n, su->su_badptr + su->su_badlen); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "prefix"); #endif go_deeper(stack, depth, 0); ++depth; sp = &stack[depth]; sp->ts_prefixdepth = depth - 1; byts = fbyts; idxs = fidxs; sp->ts_arridx = 0; /* Move the prefix to preword[] with the right case * and make find_keepcap_word() works. */ tword[sp->ts_twordlen] = NUL; make_case_word(tword + sp->ts_splitoff, preword + sp->ts_prewordlen, flags); sp->ts_prewordlen = (char_u)STRLEN(preword); sp->ts_splitoff = sp->ts_twordlen; } break; } if (sp->ts_curi > len || byts[arridx] != 0) { /* Past bytes in node and/or past NUL bytes. */ sp->ts_state = STATE_ENDNUL; sp->ts_save_badflags = su->su_badflags; break; } /* * End of word in tree. */ ++sp->ts_curi; /* eat one NUL byte */ flags = (int)idxs[arridx]; /* Skip words with the NOSUGGEST flag. */ if (flags & WF_NOSUGGEST) break; fword_ends = (fword[sp->ts_fidx] == NUL || (soundfold ? vim_iswhite(fword[sp->ts_fidx]) : !spell_iswordp(fword + sp->ts_fidx, curwin))); tword[sp->ts_twordlen] = NUL; if (sp->ts_prefixdepth <= PFD_NOTSPECIAL && (sp->ts_flags & TSF_PREFIXOK) == 0) { /* There was a prefix before the word. Check that the prefix * can be used with this word. */ /* Count the length of the NULs in the prefix. If there are * none this must be the first try without a prefix. */ n = stack[sp->ts_prefixdepth].ts_arridx; len = pbyts[n++]; for (c = 0; c < len && pbyts[n + c] == 0; ++c) ; if (c > 0) { c = valid_word_prefix(c, n, flags, tword + sp->ts_splitoff, slang, FALSE); if (c == 0) break; /* Use the WF_RARE flag for a rare prefix. */ if (c & WF_RAREPFX) flags |= WF_RARE; /* Tricky: when checking for both prefix and compounding * we run into the prefix flag first. * Remember that it's OK, so that we accept the prefix * when arriving at a compound flag. */ sp->ts_flags |= TSF_PREFIXOK; } } /* Check NEEDCOMPOUND: can't use word without compounding. Do try * appending another compound word below. */ if (sp->ts_complen == sp->ts_compsplit && fword_ends && (flags & WF_NEEDCOMP)) goodword_ends = FALSE; else goodword_ends = TRUE; p = NULL; compound_ok = TRUE; if (sp->ts_complen > sp->ts_compsplit) { if (slang->sl_nobreak) { /* There was a word before this word. When there was no * change in this word (it was correct) add the first word * as a suggestion. If this word was corrected too, we * need to check if a correct word follows. */ if (sp->ts_fidx - sp->ts_splitfidx == sp->ts_twordlen - sp->ts_splitoff && STRNCMP(fword + sp->ts_splitfidx, tword + sp->ts_splitoff, sp->ts_fidx - sp->ts_splitfidx) == 0) { preword[sp->ts_prewordlen] = NUL; newscore = score_wordcount_adj(slang, sp->ts_score, preword + sp->ts_prewordlen, sp->ts_prewordlen > 0); /* Add the suggestion if the score isn't too bad. */ if (newscore <= su->su_maxscore) add_suggestion(su, &su->su_ga, preword, sp->ts_splitfidx - repextra, newscore, 0, FALSE, lp->lp_sallang, FALSE); break; } } else { /* There was a compound word before this word. If this * word does not support compounding then give up * (splitting is tried for the word without compound * flag). */ if (((unsigned)flags >> 24) == 0 || sp->ts_twordlen - sp->ts_splitoff < slang->sl_compminlen) break; #ifdef FEAT_MBYTE /* For multi-byte chars check character length against * COMPOUNDMIN. */ if (has_mbyte && slang->sl_compminlen > 0 && mb_charlen(tword + sp->ts_splitoff) < slang->sl_compminlen) break; #endif compflags[sp->ts_complen] = ((unsigned)flags >> 24); compflags[sp->ts_complen + 1] = NUL; vim_strncpy(preword + sp->ts_prewordlen, tword + sp->ts_splitoff, sp->ts_twordlen - sp->ts_splitoff); /* Verify CHECKCOMPOUNDPATTERN rules. */ if (match_checkcompoundpattern(preword, sp->ts_prewordlen, &slang->sl_comppat)) compound_ok = FALSE; if (compound_ok) { p = preword; while (*skiptowhite(p) != NUL) p = skipwhite(skiptowhite(p)); if (fword_ends && !can_compound(slang, p, compflags + sp->ts_compsplit)) /* Compound is not allowed. But it may still be * possible if we add another (short) word. */ compound_ok = FALSE; } /* Get pointer to last char of previous word. */ p = preword + sp->ts_prewordlen; mb_ptr_back(preword, p); } } /* * Form the word with proper case in preword. * If there is a word from a previous split, append. * For the soundfold tree don't change the case, simply append. */ if (soundfold) STRCPY(preword + sp->ts_prewordlen, tword + sp->ts_splitoff); else if (flags & WF_KEEPCAP) /* Must find the word in the keep-case tree. */ find_keepcap_word(slang, tword + sp->ts_splitoff, preword + sp->ts_prewordlen); else { /* Include badflags: If the badword is onecap or allcap * use that for the goodword too. But if the badword is * allcap and it's only one char long use onecap. */ c = su->su_badflags; if ((c & WF_ALLCAP) #ifdef FEAT_MBYTE && su->su_badlen == (*mb_ptr2len)(su->su_badptr) #else && su->su_badlen == 1 #endif ) c = WF_ONECAP; c |= flags; /* When appending a compound word after a word character don't * use Onecap. */ if (p != NULL && spell_iswordp_nmw(p)) c &= ~WF_ONECAP; make_case_word(tword + sp->ts_splitoff, preword + sp->ts_prewordlen, c); } if (!soundfold) { /* Don't use a banned word. It may appear again as a good * word, thus remember it. */ if (flags & WF_BANNED) { add_banned(su, preword + sp->ts_prewordlen); break; } if ((sp->ts_complen == sp->ts_compsplit && WAS_BANNED(su, preword + sp->ts_prewordlen)) || WAS_BANNED(su, preword)) { if (slang->sl_compprog == NULL) break; /* the word so far was banned but we may try compounding */ goodword_ends = FALSE; } } newscore = 0; if (!soundfold) /* soundfold words don't have flags */ { if ((flags & WF_REGION) && (((unsigned)flags >> 16) & lp->lp_region) == 0) newscore += SCORE_REGION; if (flags & WF_RARE) newscore += SCORE_RARE; if (!spell_valid_case(su->su_badflags, captype(preword + sp->ts_prewordlen, NULL))) newscore += SCORE_ICASE; } /* TODO: how about splitting in the soundfold tree? */ if (fword_ends && goodword_ends && sp->ts_fidx >= sp->ts_fidxtry && compound_ok) { /* The badword also ends: add suggestions. */ #ifdef DEBUG_TRIEWALK if (soundfold && STRCMP(preword, "smwrd") == 0) { int j; /* print the stack of changes that brought us here */ smsg("------ %s -------", fword); for (j = 0; j < depth; ++j) smsg("%s", changename[j]); } #endif if (soundfold) { /* For soundfolded words we need to find the original * words, the edit distance and then add them. */ add_sound_suggest(su, preword, sp->ts_score, lp); } else if (sp->ts_fidx > 0) { /* Give a penalty when changing non-word char to word * char, e.g., "thes," -> "these". */ p = fword + sp->ts_fidx; mb_ptr_back(fword, p); if (!spell_iswordp(p, curwin)) { p = preword + STRLEN(preword); mb_ptr_back(preword, p); if (spell_iswordp(p, curwin)) newscore += SCORE_NONWORD; } /* Give a bonus to words seen before. */ score = score_wordcount_adj(slang, sp->ts_score + newscore, preword + sp->ts_prewordlen, sp->ts_prewordlen > 0); /* Add the suggestion if the score isn't too bad. */ if (score <= su->su_maxscore) { add_suggestion(su, &su->su_ga, preword, sp->ts_fidx - repextra, score, 0, FALSE, lp->lp_sallang, FALSE); if (su->su_badflags & WF_MIXCAP) { /* We really don't know if the word should be * upper or lower case, add both. */ c = captype(preword, NULL); if (c == 0 || c == WF_ALLCAP) { make_case_word(tword + sp->ts_splitoff, preword + sp->ts_prewordlen, c == 0 ? WF_ALLCAP : 0); add_suggestion(su, &su->su_ga, preword, sp->ts_fidx - repextra, score + SCORE_ICASE, 0, FALSE, lp->lp_sallang, FALSE); } } } } } /* * Try word split and/or compounding. */ if ((sp->ts_fidx >= sp->ts_fidxtry || fword_ends) #ifdef FEAT_MBYTE /* Don't split halfway a character. */ && (!has_mbyte || sp->ts_tcharlen == 0) #endif ) { int try_compound; int try_split; /* If past the end of the bad word don't try a split. * Otherwise try changing the next word. E.g., find * suggestions for "the the" where the second "the" is * different. It's done like a split. * TODO: word split for soundfold words */ try_split = (sp->ts_fidx - repextra < su->su_badlen) && !soundfold; /* Get here in several situations: * 1. The word in the tree ends: * If the word allows compounding try that. Otherwise try * a split by inserting a space. For both check that a * valid words starts at fword[sp->ts_fidx]. * For NOBREAK do like compounding to be able to check if * the next word is valid. * 2. The badword does end, but it was due to a change (e.g., * a swap). No need to split, but do check that the * following word is valid. * 3. The badword and the word in the tree end. It may still * be possible to compound another (short) word. */ try_compound = FALSE; if (!soundfold && slang->sl_compprog != NULL && ((unsigned)flags >> 24) != 0 && sp->ts_twordlen - sp->ts_splitoff >= slang->sl_compminlen #ifdef FEAT_MBYTE && (!has_mbyte || slang->sl_compminlen == 0 || mb_charlen(tword + sp->ts_splitoff) >= slang->sl_compminlen) #endif && (slang->sl_compsylmax < MAXWLEN || sp->ts_complen + 1 - sp->ts_compsplit < slang->sl_compmax) && (can_be_compound(sp, slang, compflags, ((unsigned)flags >> 24)))) { try_compound = TRUE; compflags[sp->ts_complen] = ((unsigned)flags >> 24); compflags[sp->ts_complen + 1] = NUL; } /* For NOBREAK we never try splitting, it won't make any word * valid. */ if (slang->sl_nobreak) try_compound = TRUE; /* If we could add a compound word, and it's also possible to * split at this point, do the split first and set * TSF_DIDSPLIT to avoid doing it again. */ else if (!fword_ends && try_compound && (sp->ts_flags & TSF_DIDSPLIT) == 0) { try_compound = FALSE; sp->ts_flags |= TSF_DIDSPLIT; --sp->ts_curi; /* do the same NUL again */ compflags[sp->ts_complen] = NUL; } else sp->ts_flags &= ~TSF_DIDSPLIT; if (try_split || try_compound) { if (!try_compound && (!fword_ends || !goodword_ends)) { /* If we're going to split need to check that the * words so far are valid for compounding. If there * is only one word it must not have the NEEDCOMPOUND * flag. */ if (sp->ts_complen == sp->ts_compsplit && (flags & WF_NEEDCOMP)) break; p = preword; while (*skiptowhite(p) != NUL) p = skipwhite(skiptowhite(p)); if (sp->ts_complen > sp->ts_compsplit && !can_compound(slang, p, compflags + sp->ts_compsplit)) break; if (slang->sl_nosplitsugs) newscore += SCORE_SPLIT_NO; else newscore += SCORE_SPLIT; /* Give a bonus to words seen before. */ newscore = score_wordcount_adj(slang, newscore, preword + sp->ts_prewordlen, TRUE); } if (TRY_DEEPER(su, stack, depth, newscore)) { go_deeper(stack, depth, newscore); #ifdef DEBUG_TRIEWALK if (!try_compound && !fword_ends) sprintf(changename[depth], "%.*s-%s: split", sp->ts_twordlen, tword, fword + sp->ts_fidx); else sprintf(changename[depth], "%.*s-%s: compound", sp->ts_twordlen, tword, fword + sp->ts_fidx); #endif /* Save things to be restored at STATE_SPLITUNDO. */ sp->ts_save_badflags = su->su_badflags; sp->ts_state = STATE_SPLITUNDO; ++depth; sp = &stack[depth]; /* Append a space to preword when splitting. */ if (!try_compound && !fword_ends) STRCAT(preword, " "); sp->ts_prewordlen = (char_u)STRLEN(preword); sp->ts_splitoff = sp->ts_twordlen; sp->ts_splitfidx = sp->ts_fidx; /* If the badword has a non-word character at this * position skip it. That means replacing the * non-word character with a space. Always skip a * character when the word ends. But only when the * good word can end. */ if (((!try_compound && !spell_iswordp_nmw(fword + sp->ts_fidx)) || fword_ends) && fword[sp->ts_fidx] != NUL && goodword_ends) { int l; #ifdef FEAT_MBYTE if (has_mbyte) l = MB_BYTE2LEN(fword[sp->ts_fidx]); else #endif l = 1; if (fword_ends) { /* Copy the skipped character to preword. */ mch_memmove(preword + sp->ts_prewordlen, fword + sp->ts_fidx, l); sp->ts_prewordlen += l; preword[sp->ts_prewordlen] = NUL; } else sp->ts_score -= SCORE_SPLIT - SCORE_SUBST; sp->ts_fidx += l; } /* When compounding include compound flag in * compflags[] (already set above). When splitting we * may start compounding over again. */ if (try_compound) ++sp->ts_complen; else sp->ts_compsplit = sp->ts_complen; sp->ts_prefixdepth = PFD_NOPREFIX; /* set su->su_badflags to the caps type at this * position */ #ifdef FEAT_MBYTE if (has_mbyte) n = nofold_len(fword, sp->ts_fidx, su->su_badptr); else #endif n = sp->ts_fidx; su->su_badflags = badword_captype(su->su_badptr + n, su->su_badptr + su->su_badlen); /* Restart at top of the tree. */ sp->ts_arridx = 0; /* If there are postponed prefixes, try these too. */ if (pbyts != NULL) { byts = pbyts; idxs = pidxs; sp->ts_prefixdepth = PFD_PREFIXTREE; sp->ts_state = STATE_NOPREFIX; } } } } break; case STATE_SPLITUNDO: /* Undo the changes done for word split or compound word. */ su->su_badflags = sp->ts_save_badflags; /* Continue looking for NUL bytes. */ sp->ts_state = STATE_START; /* In case we went into the prefix tree. */ byts = fbyts; idxs = fidxs; break; case STATE_ENDNUL: /* Past the NUL bytes in the node. */ su->su_badflags = sp->ts_save_badflags; if (fword[sp->ts_fidx] == NUL #ifdef FEAT_MBYTE && sp->ts_tcharlen == 0 #endif ) { /* The badword ends, can't use STATE_PLAIN. */ sp->ts_state = STATE_DEL; break; } sp->ts_state = STATE_PLAIN; /*FALLTHROUGH*/ case STATE_PLAIN: /* * Go over all possible bytes at this node, add each to tword[] * and use child node. "ts_curi" is the index. */ arridx = sp->ts_arridx; if (sp->ts_curi > byts[arridx]) { /* Done all bytes at this node, do next state. When still at * already changed bytes skip the other tricks. */ if (sp->ts_fidx >= sp->ts_fidxtry) sp->ts_state = STATE_DEL; else sp->ts_state = STATE_FINAL; } else { arridx += sp->ts_curi++; c = byts[arridx]; /* Normal byte, go one level deeper. If it's not equal to the * byte in the bad word adjust the score. But don't even try * when the byte was already changed. And don't try when we * just deleted this byte, accepting it is always cheaper then * delete + substitute. */ if (c == fword[sp->ts_fidx] #ifdef FEAT_MBYTE || (sp->ts_tcharlen > 0 && sp->ts_isdiff != DIFF_NONE) #endif ) newscore = 0; else newscore = SCORE_SUBST; if ((newscore == 0 || (sp->ts_fidx >= sp->ts_fidxtry && ((sp->ts_flags & TSF_DIDDEL) == 0 || c != fword[sp->ts_delidx]))) && TRY_DEEPER(su, stack, depth, newscore)) { go_deeper(stack, depth, newscore); #ifdef DEBUG_TRIEWALK if (newscore > 0) sprintf(changename[depth], "%.*s-%s: subst %c to %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, fword[sp->ts_fidx], c); else sprintf(changename[depth], "%.*s-%s: accept %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, fword[sp->ts_fidx]); #endif ++depth; sp = &stack[depth]; ++sp->ts_fidx; tword[sp->ts_twordlen++] = c; sp->ts_arridx = idxs[arridx]; #ifdef FEAT_MBYTE if (newscore == SCORE_SUBST) sp->ts_isdiff = DIFF_YES; if (has_mbyte) { /* Multi-byte characters are a bit complicated to * handle: They differ when any of the bytes differ * and then their length may also differ. */ if (sp->ts_tcharlen == 0) { /* First byte. */ sp->ts_tcharidx = 0; sp->ts_tcharlen = MB_BYTE2LEN(c); sp->ts_fcharstart = sp->ts_fidx - 1; sp->ts_isdiff = (newscore != 0) ? DIFF_YES : DIFF_NONE; } else if (sp->ts_isdiff == DIFF_INSERT) /* When inserting trail bytes don't advance in the * bad word. */ --sp->ts_fidx; if (++sp->ts_tcharidx == sp->ts_tcharlen) { /* Last byte of character. */ if (sp->ts_isdiff == DIFF_YES) { /* Correct ts_fidx for the byte length of the * character (we didn't check that before). */ sp->ts_fidx = sp->ts_fcharstart + MB_BYTE2LEN( fword[sp->ts_fcharstart]); /* For changing a composing character adjust * the score from SCORE_SUBST to * SCORE_SUBCOMP. */ if (enc_utf8 && utf_iscomposing( mb_ptr2char(tword + sp->ts_twordlen - sp->ts_tcharlen)) && utf_iscomposing( mb_ptr2char(fword + sp->ts_fcharstart))) sp->ts_score -= SCORE_SUBST - SCORE_SUBCOMP; /* For a similar character adjust score from * SCORE_SUBST to SCORE_SIMILAR. */ else if (!soundfold && slang->sl_has_map && similar_chars(slang, mb_ptr2char(tword + sp->ts_twordlen - sp->ts_tcharlen), mb_ptr2char(fword + sp->ts_fcharstart))) sp->ts_score -= SCORE_SUBST - SCORE_SIMILAR; } else if (sp->ts_isdiff == DIFF_INSERT && sp->ts_twordlen > sp->ts_tcharlen) { p = tword + sp->ts_twordlen - sp->ts_tcharlen; c = mb_ptr2char(p); if (enc_utf8 && utf_iscomposing(c)) { /* Inserting a composing char doesn't * count that much. */ sp->ts_score -= SCORE_INS - SCORE_INSCOMP; } else { /* If the previous character was the same, * thus doubling a character, give a bonus * to the score. Also for the soundfold * tree (might seem illogical but does * give better scores). */ mb_ptr_back(tword, p); if (c == mb_ptr2char(p)) sp->ts_score -= SCORE_INS - SCORE_INSDUP; } } /* Starting a new char, reset the length. */ sp->ts_tcharlen = 0; } } else #endif { /* If we found a similar char adjust the score. * We do this after calling go_deeper() because * it's slow. */ if (newscore != 0 && !soundfold && slang->sl_has_map && similar_chars(slang, c, fword[sp->ts_fidx - 1])) sp->ts_score -= SCORE_SUBST - SCORE_SIMILAR; } } } break; case STATE_DEL: #ifdef FEAT_MBYTE /* When past the first byte of a multi-byte char don't try * delete/insert/swap a character. */ if (has_mbyte && sp->ts_tcharlen > 0) { sp->ts_state = STATE_FINAL; break; } #endif /* * Try skipping one character in the bad word (delete it). */ sp->ts_state = STATE_INS_PREP; sp->ts_curi = 1; if (soundfold && sp->ts_fidx == 0 && fword[sp->ts_fidx] == '*') /* Deleting a vowel at the start of a word counts less, see * soundalike_score(). */ newscore = 2 * SCORE_DEL / 3; else newscore = SCORE_DEL; if (fword[sp->ts_fidx] != NUL && TRY_DEEPER(su, stack, depth, newscore)) { go_deeper(stack, depth, newscore); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "%.*s-%s: delete %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, fword[sp->ts_fidx]); #endif ++depth; /* Remember what character we deleted, so that we can avoid * inserting it again. */ stack[depth].ts_flags |= TSF_DIDDEL; stack[depth].ts_delidx = sp->ts_fidx; /* Advance over the character in fword[]. Give a bonus to the * score if the same character is following "nn" -> "n". It's * a bit illogical for soundfold tree but it does give better * results. */ #ifdef FEAT_MBYTE if (has_mbyte) { c = mb_ptr2char(fword + sp->ts_fidx); stack[depth].ts_fidx += MB_BYTE2LEN(fword[sp->ts_fidx]); if (enc_utf8 && utf_iscomposing(c)) stack[depth].ts_score -= SCORE_DEL - SCORE_DELCOMP; else if (c == mb_ptr2char(fword + stack[depth].ts_fidx)) stack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP; } else #endif { ++stack[depth].ts_fidx; if (fword[sp->ts_fidx] == fword[sp->ts_fidx + 1]) stack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP; } break; } /*FALLTHROUGH*/ case STATE_INS_PREP: if (sp->ts_flags & TSF_DIDDEL) { /* If we just deleted a byte then inserting won't make sense, * a substitute is always cheaper. */ sp->ts_state = STATE_SWAP; break; } /* skip over NUL bytes */ n = sp->ts_arridx; for (;;) { if (sp->ts_curi > byts[n]) { /* Only NUL bytes at this node, go to next state. */ sp->ts_state = STATE_SWAP; break; } if (byts[n + sp->ts_curi] != NUL) { /* Found a byte to insert. */ sp->ts_state = STATE_INS; break; } ++sp->ts_curi; } break; /*FALLTHROUGH*/ case STATE_INS: /* Insert one byte. Repeat this for each possible byte at this * node. */ n = sp->ts_arridx; if (sp->ts_curi > byts[n]) { /* Done all bytes at this node, go to next state. */ sp->ts_state = STATE_SWAP; break; } /* Do one more byte at this node, but: * - Skip NUL bytes. * - Skip the byte if it's equal to the byte in the word, * accepting that byte is always better. */ n += sp->ts_curi++; c = byts[n]; if (soundfold && sp->ts_twordlen == 0 && c == '*') /* Inserting a vowel at the start of a word counts less, * see soundalike_score(). */ newscore = 2 * SCORE_INS / 3; else newscore = SCORE_INS; if (c != fword[sp->ts_fidx] && TRY_DEEPER(su, stack, depth, newscore)) { go_deeper(stack, depth, newscore); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "%.*s-%s: insert %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, c); #endif ++depth; sp = &stack[depth]; tword[sp->ts_twordlen++] = c; sp->ts_arridx = idxs[n]; #ifdef FEAT_MBYTE if (has_mbyte) { fl = MB_BYTE2LEN(c); if (fl > 1) { /* There are following bytes for the same character. * We must find all bytes before trying * delete/insert/swap/etc. */ sp->ts_tcharlen = fl; sp->ts_tcharidx = 1; sp->ts_isdiff = DIFF_INSERT; } } else fl = 1; if (fl == 1) #endif { /* If the previous character was the same, thus doubling a * character, give a bonus to the score. Also for * soundfold words (illogical but does give a better * score). */ if (sp->ts_twordlen >= 2 && tword[sp->ts_twordlen - 2] == c) sp->ts_score -= SCORE_INS - SCORE_INSDUP; } } break; case STATE_SWAP: /* * Swap two bytes in the bad word: "12" -> "21". * We change "fword" here, it's changed back afterwards at * STATE_UNSWAP. */ p = fword + sp->ts_fidx; c = *p; if (c == NUL) { /* End of word, can't swap or replace. */ sp->ts_state = STATE_FINAL; break; } /* Don't swap if the first character is not a word character. * SWAP3 etc. also don't make sense then. */ if (!soundfold && !spell_iswordp(p, curwin)) { sp->ts_state = STATE_REP_INI; break; } #ifdef FEAT_MBYTE if (has_mbyte) { n = mb_cptr2len(p); c = mb_ptr2char(p); if (p[n] == NUL) c2 = NUL; else if (!soundfold && !spell_iswordp(p + n, curwin)) c2 = c; /* don't swap non-word char */ else c2 = mb_ptr2char(p + n); } else #endif { if (p[1] == NUL) c2 = NUL; else if (!soundfold && !spell_iswordp(p + 1, curwin)) c2 = c; /* don't swap non-word char */ else c2 = p[1]; } /* When the second character is NUL we can't swap. */ if (c2 == NUL) { sp->ts_state = STATE_REP_INI; break; } /* When characters are identical, swap won't do anything. * Also get here if the second char is not a word character. */ if (c == c2) { sp->ts_state = STATE_SWAP3; break; } if (c2 != NUL && TRY_DEEPER(su, stack, depth, SCORE_SWAP)) { go_deeper(stack, depth, SCORE_SWAP); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "%.*s-%s: swap %c and %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, c, c2); #endif sp->ts_state = STATE_UNSWAP; ++depth; #ifdef FEAT_MBYTE if (has_mbyte) { fl = mb_char2len(c2); mch_memmove(p, p + n, fl); mb_char2bytes(c, p + fl); stack[depth].ts_fidxtry = sp->ts_fidx + n + fl; } else #endif { p[0] = c2; p[1] = c; stack[depth].ts_fidxtry = sp->ts_fidx + 2; } } else /* If this swap doesn't work then SWAP3 won't either. */ sp->ts_state = STATE_REP_INI; break; case STATE_UNSWAP: /* Undo the STATE_SWAP swap: "21" -> "12". */ p = fword + sp->ts_fidx; #ifdef FEAT_MBYTE if (has_mbyte) { n = MB_BYTE2LEN(*p); c = mb_ptr2char(p + n); mch_memmove(p + MB_BYTE2LEN(p[n]), p, n); mb_char2bytes(c, p); } else #endif { c = *p; *p = p[1]; p[1] = c; } /*FALLTHROUGH*/ case STATE_SWAP3: /* Swap two bytes, skipping one: "123" -> "321". We change * "fword" here, it's changed back afterwards at STATE_UNSWAP3. */ p = fword + sp->ts_fidx; #ifdef FEAT_MBYTE if (has_mbyte) { n = mb_cptr2len(p); c = mb_ptr2char(p); fl = mb_cptr2len(p + n); c2 = mb_ptr2char(p + n); if (!soundfold && !spell_iswordp(p + n + fl, curwin)) c3 = c; /* don't swap non-word char */ else c3 = mb_ptr2char(p + n + fl); } else #endif { c = *p; c2 = p[1]; if (!soundfold && !spell_iswordp(p + 2, curwin)) c3 = c; /* don't swap non-word char */ else c3 = p[2]; } /* When characters are identical: "121" then SWAP3 result is * identical, ROT3L result is same as SWAP: "211", ROT3L result is * same as SWAP on next char: "112". Thus skip all swapping. * Also skip when c3 is NUL. * Also get here when the third character is not a word character. * Second character may any char: "a.b" -> "b.a" */ if (c == c3 || c3 == NUL) { sp->ts_state = STATE_REP_INI; break; } if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3)) { go_deeper(stack, depth, SCORE_SWAP3); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "%.*s-%s: swap3 %c and %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, c, c3); #endif sp->ts_state = STATE_UNSWAP3; ++depth; #ifdef FEAT_MBYTE if (has_mbyte) { tl = mb_char2len(c3); mch_memmove(p, p + n + fl, tl); mb_char2bytes(c2, p + tl); mb_char2bytes(c, p + fl + tl); stack[depth].ts_fidxtry = sp->ts_fidx + n + fl + tl; } else #endif { p[0] = p[2]; p[2] = c; stack[depth].ts_fidxtry = sp->ts_fidx + 3; } } else sp->ts_state = STATE_REP_INI; break; case STATE_UNSWAP3: /* Undo STATE_SWAP3: "321" -> "123" */ p = fword + sp->ts_fidx; #ifdef FEAT_MBYTE if (has_mbyte) { n = MB_BYTE2LEN(*p); c2 = mb_ptr2char(p + n); fl = MB_BYTE2LEN(p[n]); c = mb_ptr2char(p + n + fl); tl = MB_BYTE2LEN(p[n + fl]); mch_memmove(p + fl + tl, p, n); mb_char2bytes(c, p); mb_char2bytes(c2, p + tl); p = p + tl; } else #endif { c = *p; *p = p[2]; p[2] = c; ++p; } if (!soundfold && !spell_iswordp(p, curwin)) { /* Middle char is not a word char, skip the rotate. First and * third char were already checked at swap and swap3. */ sp->ts_state = STATE_REP_INI; break; } /* Rotate three characters left: "123" -> "231". We change * "fword" here, it's changed back afterwards at STATE_UNROT3L. */ if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3)) { go_deeper(stack, depth, SCORE_SWAP3); #ifdef DEBUG_TRIEWALK p = fword + sp->ts_fidx; sprintf(changename[depth], "%.*s-%s: rotate left %c%c%c", sp->ts_twordlen, tword, fword + sp->ts_fidx, p[0], p[1], p[2]); #endif sp->ts_state = STATE_UNROT3L; ++depth; p = fword + sp->ts_fidx; #ifdef FEAT_MBYTE if (has_mbyte) { n = mb_cptr2len(p); c = mb_ptr2char(p); fl = mb_cptr2len(p + n); fl += mb_cptr2len(p + n + fl); mch_memmove(p, p + n, fl); mb_char2bytes(c, p + fl); stack[depth].ts_fidxtry = sp->ts_fidx + n + fl; } else #endif { c = *p; *p = p[1]; p[1] = p[2]; p[2] = c; stack[depth].ts_fidxtry = sp->ts_fidx + 3; } } else sp->ts_state = STATE_REP_INI; break; case STATE_UNROT3L: /* Undo ROT3L: "231" -> "123" */ p = fword + sp->ts_fidx; #ifdef FEAT_MBYTE if (has_mbyte) { n = MB_BYTE2LEN(*p); n += MB_BYTE2LEN(p[n]); c = mb_ptr2char(p + n); tl = MB_BYTE2LEN(p[n]); mch_memmove(p + tl, p, n); mb_char2bytes(c, p); } else #endif { c = p[2]; p[2] = p[1]; p[1] = *p; *p = c; } /* Rotate three bytes right: "123" -> "312". We change "fword" * here, it's changed back afterwards at STATE_UNROT3R. */ if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3)) { go_deeper(stack, depth, SCORE_SWAP3); #ifdef DEBUG_TRIEWALK p = fword + sp->ts_fidx; sprintf(changename[depth], "%.*s-%s: rotate right %c%c%c", sp->ts_twordlen, tword, fword + sp->ts_fidx, p[0], p[1], p[2]); #endif sp->ts_state = STATE_UNROT3R; ++depth; p = fword + sp->ts_fidx; #ifdef FEAT_MBYTE if (has_mbyte) { n = mb_cptr2len(p); n += mb_cptr2len(p + n); c = mb_ptr2char(p + n); tl = mb_cptr2len(p + n); mch_memmove(p + tl, p, n); mb_char2bytes(c, p); stack[depth].ts_fidxtry = sp->ts_fidx + n + tl; } else #endif { c = p[2]; p[2] = p[1]; p[1] = *p; *p = c; stack[depth].ts_fidxtry = sp->ts_fidx + 3; } } else sp->ts_state = STATE_REP_INI; break; case STATE_UNROT3R: /* Undo ROT3R: "312" -> "123" */ p = fword + sp->ts_fidx; #ifdef FEAT_MBYTE if (has_mbyte) { c = mb_ptr2char(p); tl = MB_BYTE2LEN(*p); n = MB_BYTE2LEN(p[tl]); n += MB_BYTE2LEN(p[tl + n]); mch_memmove(p, p + tl, n); mb_char2bytes(c, p + n); } else #endif { c = *p; *p = p[1]; p[1] = p[2]; p[2] = c; } /*FALLTHROUGH*/ case STATE_REP_INI: /* Check if matching with REP items from the .aff file would work. * Quickly skip if: * - there are no REP items and we are not in the soundfold trie * - the score is going to be too high anyway * - already applied a REP item or swapped here */ if ((lp->lp_replang == NULL && !soundfold) || sp->ts_score + SCORE_REP >= su->su_maxscore || sp->ts_fidx < sp->ts_fidxtry) { sp->ts_state = STATE_FINAL; break; } /* Use the first byte to quickly find the first entry that may * match. If the index is -1 there is none. */ if (soundfold) sp->ts_curi = slang->sl_repsal_first[fword[sp->ts_fidx]]; else sp->ts_curi = lp->lp_replang->sl_rep_first[fword[sp->ts_fidx]]; if (sp->ts_curi < 0) { sp->ts_state = STATE_FINAL; break; } sp->ts_state = STATE_REP; /*FALLTHROUGH*/ case STATE_REP: /* Try matching with REP items from the .aff file. For each match * replace the characters and check if the resulting word is * valid. */ p = fword + sp->ts_fidx; if (soundfold) gap = &slang->sl_repsal; else gap = &lp->lp_replang->sl_rep; while (sp->ts_curi < gap->ga_len) { ftp = (fromto_T *)gap->ga_data + sp->ts_curi++; if (*ftp->ft_from != *p) { /* past possible matching entries */ sp->ts_curi = gap->ga_len; break; } if (STRNCMP(ftp->ft_from, p, STRLEN(ftp->ft_from)) == 0 && TRY_DEEPER(su, stack, depth, SCORE_REP)) { go_deeper(stack, depth, SCORE_REP); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "%.*s-%s: replace %s with %s", sp->ts_twordlen, tword, fword + sp->ts_fidx, ftp->ft_from, ftp->ft_to); #endif /* Need to undo this afterwards. */ sp->ts_state = STATE_REP_UNDO; /* Change the "from" to the "to" string. */ ++depth; fl = (int)STRLEN(ftp->ft_from); tl = (int)STRLEN(ftp->ft_to); if (fl != tl) { STRMOVE(p + tl, p + fl); repextra += tl - fl; } mch_memmove(p, ftp->ft_to, tl); stack[depth].ts_fidxtry = sp->ts_fidx + tl; #ifdef FEAT_MBYTE stack[depth].ts_tcharlen = 0; #endif break; } } if (sp->ts_curi >= gap->ga_len && sp->ts_state == STATE_REP) /* No (more) matches. */ sp->ts_state = STATE_FINAL; break; case STATE_REP_UNDO: /* Undo a REP replacement and continue with the next one. */ if (soundfold) gap = &slang->sl_repsal; else gap = &lp->lp_replang->sl_rep; ftp = (fromto_T *)gap->ga_data + sp->ts_curi - 1; fl = (int)STRLEN(ftp->ft_from); tl = (int)STRLEN(ftp->ft_to); p = fword + sp->ts_fidx; if (fl != tl) { STRMOVE(p + fl, p + tl); repextra -= tl - fl; } mch_memmove(p, ftp->ft_from, fl); sp->ts_state = STATE_REP; break; default: /* Did all possible states at this level, go up one level. */ --depth; if (depth >= 0 && stack[depth].ts_prefixdepth == PFD_PREFIXTREE) { /* Continue in or go back to the prefix tree. */ byts = pbyts; idxs = pidxs; } /* Don't check for CTRL-C too often, it takes time. */ if (--breakcheckcount == 0) { ui_breakcheck(); breakcheckcount = 1000; } } } } /* * Go one level deeper in the tree. */ static void go_deeper(stack, depth, score_add) trystate_T *stack; int depth; int score_add; { stack[depth + 1] = stack[depth]; stack[depth + 1].ts_state = STATE_START; stack[depth + 1].ts_score = stack[depth].ts_score + score_add; stack[depth + 1].ts_curi = 1; /* start just after length byte */ stack[depth + 1].ts_flags = 0; } #ifdef FEAT_MBYTE /* * Case-folding may change the number of bytes: Count nr of chars in * fword[flen] and return the byte length of that many chars in "word". */ static int nofold_len(fword, flen, word) char_u *fword; int flen; char_u *word; { char_u *p; int i = 0; for (p = fword; p < fword + flen; mb_ptr_adv(p)) ++i; for (p = word; i > 0; mb_ptr_adv(p)) --i; return (int)(p - word); } #endif /* * "fword" is a good word with case folded. Find the matching keep-case * words and put it in "kword". * Theoretically there could be several keep-case words that result in the * same case-folded word, but we only find one... */ static void find_keepcap_word(slang, fword, kword) slang_T *slang; char_u *fword; char_u *kword; { char_u uword[MAXWLEN]; /* "fword" in upper-case */ int depth; idx_T tryidx; /* The following arrays are used at each depth in the tree. */ idx_T arridx[MAXWLEN]; int round[MAXWLEN]; int fwordidx[MAXWLEN]; int uwordidx[MAXWLEN]; int kwordlen[MAXWLEN]; int flen, ulen; int l; int len; int c; idx_T lo, hi, m; char_u *p; char_u *byts = slang->sl_kbyts; /* array with bytes of the words */ idx_T *idxs = slang->sl_kidxs; /* array with indexes */ if (byts == NULL) { /* array is empty: "cannot happen" */ *kword = NUL; return; } /* Make an all-cap version of "fword". */ allcap_copy(fword, uword); /* * Each character needs to be tried both case-folded and upper-case. * All this gets very complicated if we keep in mind that changing case * may change the byte length of a multi-byte character... */ depth = 0; arridx[0] = 0; round[0] = 0; fwordidx[0] = 0; uwordidx[0] = 0; kwordlen[0] = 0; while (depth >= 0) { if (fword[fwordidx[depth]] == NUL) { /* We are at the end of "fword". If the tree allows a word to end * here we have found a match. */ if (byts[arridx[depth] + 1] == 0) { kword[kwordlen[depth]] = NUL; return; } /* kword is getting too long, continue one level up */ --depth; } else if (++round[depth] > 2) { /* tried both fold-case and upper-case character, continue one * level up */ --depth; } else { /* * round[depth] == 1: Try using the folded-case character. * round[depth] == 2: Try using the upper-case character. */ #ifdef FEAT_MBYTE if (has_mbyte) { flen = mb_cptr2len(fword + fwordidx[depth]); ulen = mb_cptr2len(uword + uwordidx[depth]); } else #endif ulen = flen = 1; if (round[depth] == 1) { p = fword + fwordidx[depth]; l = flen; } else { p = uword + uwordidx[depth]; l = ulen; } for (tryidx = arridx[depth]; l > 0; --l) { /* Perform a binary search in the list of accepted bytes. */ len = byts[tryidx++]; c = *p++; lo = tryidx; hi = tryidx + len - 1; while (lo < hi) { m = (lo + hi) / 2; if (byts[m] > c) hi = m - 1; else if (byts[m] < c) lo = m + 1; else { lo = hi = m; break; } } /* Stop if there is no matching byte. */ if (hi < lo || byts[lo] != c) break; /* Continue at the child (if there is one). */ tryidx = idxs[lo]; } if (l == 0) { /* * Found the matching char. Copy it to "kword" and go a * level deeper. */ if (round[depth] == 1) { STRNCPY(kword + kwordlen[depth], fword + fwordidx[depth], flen); kwordlen[depth + 1] = kwordlen[depth] + flen; } else { STRNCPY(kword + kwordlen[depth], uword + uwordidx[depth], ulen); kwordlen[depth + 1] = kwordlen[depth] + ulen; } fwordidx[depth + 1] = fwordidx[depth] + flen; uwordidx[depth + 1] = uwordidx[depth] + ulen; ++depth; arridx[depth] = tryidx; round[depth] = 0; } } } /* Didn't find it: "cannot happen". */ *kword = NUL; } /* * Compute the sound-a-like score for suggestions in su->su_ga and add them to * su->su_sga. */ static void score_comp_sal(su) suginfo_T *su; { langp_T *lp; char_u badsound[MAXWLEN]; int i; suggest_T *stp; suggest_T *sstp; int score; int lpi; if (ga_grow(&su->su_sga, su->su_ga.ga_len) == FAIL) return; /* Use the sound-folding of the first language that supports it. */ for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi) { lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi); if (lp->lp_slang->sl_sal.ga_len > 0) { /* soundfold the bad word */ spell_soundfold(lp->lp_slang, su->su_fbadword, TRUE, badsound); for (i = 0; i < su->su_ga.ga_len; ++i) { stp = &SUG(su->su_ga, i); /* Case-fold the suggested word, sound-fold it and compute the * sound-a-like score. */ score = stp_sal_score(stp, su, lp->lp_slang, badsound); if (score < SCORE_MAXMAX) { /* Add the suggestion. */ sstp = &SUG(su->su_sga, su->su_sga.ga_len); sstp->st_word = vim_strsave(stp->st_word); if (sstp->st_word != NULL) { sstp->st_wordlen = stp->st_wordlen; sstp->st_score = score; sstp->st_altscore = 0; sstp->st_orglen = stp->st_orglen; ++su->su_sga.ga_len; } } } break; } } } /* * Combine the list of suggestions in su->su_ga and su->su_sga. * They are intwined. */ static void score_combine(su) suginfo_T *su; { int i; int j; garray_T ga; garray_T *gap; langp_T *lp; suggest_T *stp; char_u *p; char_u badsound[MAXWLEN]; int round; int lpi; slang_T *slang = NULL; /* Add the alternate score to su_ga. */ for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi) { lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi); if (lp->lp_slang->sl_sal.ga_len > 0) { /* soundfold the bad word */ slang = lp->lp_slang; spell_soundfold(slang, su->su_fbadword, TRUE, badsound); for (i = 0; i < su->su_ga.ga_len; ++i) { stp = &SUG(su->su_ga, i); stp->st_altscore = stp_sal_score(stp, su, slang, badsound); if (stp->st_altscore == SCORE_MAXMAX) stp->st_score = (stp->st_score * 3 + SCORE_BIG) / 4; else stp->st_score = (stp->st_score * 3 + stp->st_altscore) / 4; stp->st_salscore = FALSE; } break; } } if (slang == NULL) /* Using "double" without sound folding. */ { (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount); return; } /* Add the alternate score to su_sga. */ for (i = 0; i < su->su_sga.ga_len; ++i) { stp = &SUG(su->su_sga, i); stp->st_altscore = spell_edit_score(slang, su->su_badword, stp->st_word); if (stp->st_score == SCORE_MAXMAX) stp->st_score = (SCORE_BIG * 7 + stp->st_altscore) / 8; else stp->st_score = (stp->st_score * 7 + stp->st_altscore) / 8; stp->st_salscore = TRUE; } /* Remove bad suggestions, sort the suggestions and truncate at "maxcount" * for both lists. */ check_suggestions(su, &su->su_ga); (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount); check_suggestions(su, &su->su_sga); (void)cleanup_suggestions(&su->su_sga, su->su_maxscore, su->su_maxcount); ga_init2(&ga, (int)sizeof(suginfo_T), 1); if (ga_grow(&ga, su->su_ga.ga_len + su->su_sga.ga_len) == FAIL) return; stp = &SUG(ga, 0); for (i = 0; i < su->su_ga.ga_len || i < su->su_sga.ga_len; ++i) { /* round 1: get a suggestion from su_ga * round 2: get a suggestion from su_sga */ for (round = 1; round <= 2; ++round) { gap = round == 1 ? &su->su_ga : &su->su_sga; if (i < gap->ga_len) { /* Don't add a word if it's already there. */ p = SUG(*gap, i).st_word; for (j = 0; j < ga.ga_len; ++j) if (STRCMP(stp[j].st_word, p) == 0) break; if (j == ga.ga_len) stp[ga.ga_len++] = SUG(*gap, i); else vim_free(p); } } } ga_clear(&su->su_ga); ga_clear(&su->su_sga); /* Truncate the list to the number of suggestions that will be displayed. */ if (ga.ga_len > su->su_maxcount) { for (i = su->su_maxcount; i < ga.ga_len; ++i) vim_free(stp[i].st_word); ga.ga_len = su->su_maxcount; } su->su_ga = ga; } /* * For the goodword in "stp" compute the soundalike score compared to the * badword. */ static int stp_sal_score(stp, su, slang, badsound) suggest_T *stp; suginfo_T *su; slang_T *slang; char_u *badsound; /* sound-folded badword */ { char_u *p; char_u *pbad; char_u *pgood; char_u badsound2[MAXWLEN]; char_u fword[MAXWLEN]; char_u goodsound[MAXWLEN]; char_u goodword[MAXWLEN]; int lendiff; lendiff = (int)(su->su_badlen - stp->st_orglen); if (lendiff >= 0) pbad = badsound; else { /* soundfold the bad word with more characters following */ (void)spell_casefold(su->su_badptr, stp->st_orglen, fword, MAXWLEN); /* When joining two words the sound often changes a lot. E.g., "t he" * sounds like "t h" while "the" sounds like "@". Avoid that by * removing the space. Don't do it when the good word also contains a * space. */ if (vim_iswhite(su->su_badptr[su->su_badlen]) && *skiptowhite(stp->st_word) == NUL) for (p = fword; *(p = skiptowhite(p)) != NUL; ) STRMOVE(p, p + 1); spell_soundfold(slang, fword, TRUE, badsound2); pbad = badsound2; } if (lendiff > 0 && stp->st_wordlen + lendiff < MAXWLEN) { /* Add part of the bad word to the good word, so that we soundfold * what replaces the bad word. */ STRCPY(goodword, stp->st_word); vim_strncpy(goodword + stp->st_wordlen, su->su_badptr + su->su_badlen - lendiff, lendiff); pgood = goodword; } else pgood = stp->st_word; /* Sound-fold the word and compute the score for the difference. */ spell_soundfold(slang, pgood, FALSE, goodsound); return soundalike_score(goodsound, pbad); } /* structure used to store soundfolded words that add_sound_suggest() has * handled already. */ typedef struct { short sft_score; /* lowest score used */ char_u sft_word[1]; /* soundfolded word, actually longer */ } sftword_T; static sftword_T dumsft; #define HIKEY2SFT(p) ((sftword_T *)(p - (dumsft.sft_word - (char_u *)&dumsft))) #define HI2SFT(hi) HIKEY2SFT((hi)->hi_key) /* * Prepare for calling suggest_try_soundalike(). */ static void suggest_try_soundalike_prep() { langp_T *lp; int lpi; slang_T *slang; /* Do this for all languages that support sound folding and for which a * .sug file has been loaded. */ for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi) { lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi); slang = lp->lp_slang; if (slang->sl_sal.ga_len > 0 && slang->sl_sbyts != NULL) /* prepare the hashtable used by add_sound_suggest() */ hash_init(&slang->sl_sounddone); } } /* * Find suggestions by comparing the word in a sound-a-like form. * Note: This doesn't support postponed prefixes. */ static void suggest_try_soundalike(su) suginfo_T *su; { char_u salword[MAXWLEN]; langp_T *lp; int lpi; slang_T *slang; /* Do this for all languages that support sound folding and for which a * .sug file has been loaded. */ for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi) { lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi); slang = lp->lp_slang; if (slang->sl_sal.ga_len > 0 && slang->sl_sbyts != NULL) { /* soundfold the bad word */ spell_soundfold(slang, su->su_fbadword, TRUE, salword); /* try all kinds of inserts/deletes/swaps/etc. */ /* TODO: also soundfold the next words, so that we can try joining * and splitting */ suggest_trie_walk(su, lp, salword, TRUE); } } } /* * Finish up after calling suggest_try_soundalike(). */ static void suggest_try_soundalike_finish() { langp_T *lp; int lpi; slang_T *slang; int todo; hashitem_T *hi; /* Do this for all languages that support sound folding and for which a * .sug file has been loaded. */ for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi) { lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi); slang = lp->lp_slang; if (slang->sl_sal.ga_len > 0 && slang->sl_sbyts != NULL) { /* Free the info about handled words. */ todo = (int)slang->sl_sounddone.ht_used; for (hi = slang->sl_sounddone.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { vim_free(HI2SFT(hi)); --todo; } /* Clear the hashtable, it may also be used by another region. */ hash_clear(&slang->sl_sounddone); hash_init(&slang->sl_sounddone); } } } /* * A match with a soundfolded word is found. Add the good word(s) that * produce this soundfolded word. */ static void add_sound_suggest(su, goodword, score, lp) suginfo_T *su; char_u *goodword; int score; /* soundfold score */ langp_T *lp; { slang_T *slang = lp->lp_slang; /* language for sound folding */ int sfwordnr; char_u *nrline; int orgnr; char_u theword[MAXWLEN]; int i; int wlen; char_u *byts; idx_T *idxs; int n; int wordcount; int wc; int goodscore; hash_T hash; hashitem_T *hi; sftword_T *sft; int bc, gc; int limit; /* * It's very well possible that the same soundfold word is found several * times with different scores. Since the following is quite slow only do * the words that have a better score than before. Use a hashtable to * remember the words that have been done. */ hash = hash_hash(goodword); hi = hash_lookup(&slang->sl_sounddone, goodword, hash); if (HASHITEM_EMPTY(hi)) { sft = (sftword_T *)alloc((unsigned)(sizeof(sftword_T) + STRLEN(goodword))); if (sft != NULL) { sft->sft_score = score; STRCPY(sft->sft_word, goodword); hash_add_item(&slang->sl_sounddone, hi, sft->sft_word, hash); } } else { sft = HI2SFT(hi); if (score >= sft->sft_score) return; sft->sft_score = score; } /* * Find the word nr in the soundfold tree. */ sfwordnr = soundfold_find(slang, goodword); if (sfwordnr < 0) { EMSG2(_(e_intern2), "add_sound_suggest()"); return; } /* * go over the list of good words that produce this soundfold word */ nrline = ml_get_buf(slang->sl_sugbuf, (linenr_T)(sfwordnr + 1), FALSE); orgnr = 0; while (*nrline != NUL) { /* The wordnr was stored in a minimal nr of bytes as an offset to the * previous wordnr. */ orgnr += bytes2offset(&nrline); byts = slang->sl_fbyts; idxs = slang->sl_fidxs; /* Lookup the word "orgnr" one of the two tries. */ n = 0; wlen = 0; wordcount = 0; for (;;) { i = 1; if (wordcount == orgnr && byts[n + 1] == NUL) break; /* found end of word */ if (byts[n + 1] == NUL) ++wordcount; /* skip over the NUL bytes */ for ( ; byts[n + i] == NUL; ++i) if (i > byts[n]) /* safety check */ { STRCPY(theword + wlen, "BAD"); goto badword; } /* One of the siblings must have the word. */ for ( ; i < byts[n]; ++i) { wc = idxs[idxs[n + i]]; /* nr of words under this byte */ if (wordcount + wc > orgnr) break; wordcount += wc; } theword[wlen++] = byts[n + i]; n = idxs[n + i]; } badword: theword[wlen] = NUL; /* Go over the possible flags and regions. */ for (; i <= byts[n] && byts[n + i] == NUL; ++i) { char_u cword[MAXWLEN]; char_u *p; int flags = (int)idxs[n + i]; /* Skip words with the NOSUGGEST flag */ if (flags & WF_NOSUGGEST) continue; if (flags & WF_KEEPCAP) { /* Must find the word in the keep-case tree. */ find_keepcap_word(slang, theword, cword); p = cword; } else { flags |= su->su_badflags; if ((flags & WF_CAPMASK) != 0) { /* Need to fix case according to "flags". */ make_case_word(theword, cword, flags); p = cword; } else p = theword; } /* Add the suggestion. */ if (sps_flags & SPS_DOUBLE) { /* Add the suggestion if the score isn't too bad. */ if (score <= su->su_maxscore) add_suggestion(su, &su->su_sga, p, su->su_badlen, score, 0, FALSE, slang, FALSE); } else { /* Add a penalty for words in another region. */ if ((flags & WF_REGION) && (((unsigned)flags >> 16) & lp->lp_region) == 0) goodscore = SCORE_REGION; else goodscore = 0; /* Add a small penalty for changing the first letter from * lower to upper case. Helps for "tath" -> "Kath", which is * less common thatn "tath" -> "path". Don't do it when the * letter is the same, that has already been counted. */ gc = PTR2CHAR(p); if (SPELL_ISUPPER(gc)) { bc = PTR2CHAR(su->su_badword); if (!SPELL_ISUPPER(bc) && SPELL_TOFOLD(bc) != SPELL_TOFOLD(gc)) goodscore += SCORE_ICASE / 2; } /* Compute the score for the good word. This only does letter * insert/delete/swap/replace. REP items are not considered, * which may make the score a bit higher. * Use a limit for the score to make it work faster. Use * MAXSCORE(), because RESCORE() will change the score. * If the limit is very high then the iterative method is * inefficient, using an array is quicker. */ limit = MAXSCORE(su->su_sfmaxscore - goodscore, score); if (limit > SCORE_LIMITMAX) goodscore += spell_edit_score(slang, su->su_badword, p); else goodscore += spell_edit_score_limit(slang, su->su_badword, p, limit); /* When going over the limit don't bother to do the rest. */ if (goodscore < SCORE_MAXMAX) { /* Give a bonus to words seen before. */ goodscore = score_wordcount_adj(slang, goodscore, p, FALSE); /* Add the suggestion if the score isn't too bad. */ goodscore = RESCORE(goodscore, score); if (goodscore <= su->su_sfmaxscore) add_suggestion(su, &su->su_ga, p, su->su_badlen, goodscore, score, TRUE, slang, TRUE); } } } /* smsg("word %s (%d): %s (%d)", sftword, sftnr, theword, orgnr); */ } } /* * Find word "word" in fold-case tree for "slang" and return the word number. */ static int soundfold_find(slang, word) slang_T *slang; char_u *word; { idx_T arridx = 0; int len; int wlen = 0; int c; char_u *ptr = word; char_u *byts; idx_T *idxs; int wordnr = 0; byts = slang->sl_sbyts; idxs = slang->sl_sidxs; for (;;) { /* First byte is the number of possible bytes. */ len = byts[arridx++]; /* If the first possible byte is a zero the word could end here. * If the word ends we found the word. If not skip the NUL bytes. */ c = ptr[wlen]; if (byts[arridx] == NUL) { if (c == NUL) break; /* Skip over the zeros, there can be several. */ while (len > 0 && byts[arridx] == NUL) { ++arridx; --len; } if (len == 0) return -1; /* no children, word should have ended here */ ++wordnr; } /* If the word ends we didn't find it. */ if (c == NUL) return -1; /* Perform a binary search in the list of accepted bytes. */ if (c == TAB) /* <Tab> is handled like <Space> */ c = ' '; while (byts[arridx] < c) { /* The word count is in the first idxs[] entry of the child. */ wordnr += idxs[idxs[arridx]]; ++arridx; if (--len == 0) /* end of the bytes, didn't find it */ return -1; } if (byts[arridx] != c) /* didn't find the byte */ return -1; /* Continue at the child (if there is one). */ arridx = idxs[arridx]; ++wlen; /* One space in the good word may stand for several spaces in the * checked word. */ if (c == ' ') while (ptr[wlen] == ' ' || ptr[wlen] == TAB) ++wlen; } return wordnr; } /* * Copy "fword" to "cword", fixing case according to "flags". */ static void make_case_word(fword, cword, flags) char_u *fword; char_u *cword; int flags; { if (flags & WF_ALLCAP) /* Make it all upper-case */ allcap_copy(fword, cword); else if (flags & WF_ONECAP) /* Make the first letter upper-case */ onecap_copy(fword, cword, TRUE); else /* Use goodword as-is. */ STRCPY(cword, fword); } /* * Use map string "map" for languages "lp". */ static void set_map_str(lp, map) slang_T *lp; char_u *map; { char_u *p; int headc = 0; int c; int i; if (*map == NUL) { lp->sl_has_map = FALSE; return; } lp->sl_has_map = TRUE; /* Init the array and hash tables empty. */ for (i = 0; i < 256; ++i) lp->sl_map_array[i] = 0; #ifdef FEAT_MBYTE hash_init(&lp->sl_map_hash); #endif /* * The similar characters are stored separated with slashes: * "aaa/bbb/ccc/". Fill sl_map_array[c] with the character before c and * before the same slash. For characters above 255 sl_map_hash is used. */ for (p = map; *p != NUL; ) { #ifdef FEAT_MBYTE c = mb_cptr2char_adv(&p); #else c = *p++; #endif if (c == '/') headc = 0; else { if (headc == 0) headc = c; #ifdef FEAT_MBYTE /* Characters above 255 don't fit in sl_map_array[], put them in * the hash table. Each entry is the char, a NUL the headchar and * a NUL. */ if (c >= 256) { int cl = mb_char2len(c); int headcl = mb_char2len(headc); char_u *b; hash_T hash; hashitem_T *hi; b = alloc((unsigned)(cl + headcl + 2)); if (b == NULL) return; mb_char2bytes(c, b); b[cl] = NUL; mb_char2bytes(headc, b + cl + 1); b[cl + 1 + headcl] = NUL; hash = hash_hash(b); hi = hash_lookup(&lp->sl_map_hash, b, hash); if (HASHITEM_EMPTY(hi)) hash_add_item(&lp->sl_map_hash, hi, b, hash); else { /* This should have been checked when generating the .spl * file. */ EMSG(_("E783: duplicate char in MAP entry")); vim_free(b); } } else #endif lp->sl_map_array[c] = headc; } } } /* * Return TRUE if "c1" and "c2" are similar characters according to the MAP * lines in the .aff file. */ static int similar_chars(slang, c1, c2) slang_T *slang; int c1; int c2; { int m1, m2; #ifdef FEAT_MBYTE char_u buf[MB_MAXBYTES + 1]; hashitem_T *hi; if (c1 >= 256) { buf[mb_char2bytes(c1, buf)] = 0; hi = hash_find(&slang->sl_map_hash, buf); if (HASHITEM_EMPTY(hi)) m1 = 0; else m1 = mb_ptr2char(hi->hi_key + STRLEN(hi->hi_key) + 1); } else #endif m1 = slang->sl_map_array[c1]; if (m1 == 0) return FALSE; #ifdef FEAT_MBYTE if (c2 >= 256) { buf[mb_char2bytes(c2, buf)] = 0; hi = hash_find(&slang->sl_map_hash, buf); if (HASHITEM_EMPTY(hi)) m2 = 0; else m2 = mb_ptr2char(hi->hi_key + STRLEN(hi->hi_key) + 1); } else #endif m2 = slang->sl_map_array[c2]; return m1 == m2; } /* * Add a suggestion to the list of suggestions. * For a suggestion that is already in the list the lowest score is remembered. */ static void add_suggestion(su, gap, goodword, badlenarg, score, altscore, had_bonus, slang, maxsf) suginfo_T *su; garray_T *gap; /* either su_ga or su_sga */ char_u *goodword; int badlenarg; /* len of bad word replaced with "goodword" */ int score; int altscore; int had_bonus; /* value for st_had_bonus */ slang_T *slang; /* language for sound folding */ int maxsf; /* su_maxscore applies to soundfold score, su_sfmaxscore to the total score. */ { int goodlen; /* len of goodword changed */ int badlen; /* len of bad word changed */ suggest_T *stp; suggest_T new_sug; int i; char_u *pgood, *pbad; /* Minimize "badlen" for consistency. Avoids that changing "the the" to * "thee the" is added next to changing the first "the" the "thee". */ pgood = goodword + STRLEN(goodword); pbad = su->su_badptr + badlenarg; for (;;) { goodlen = (int)(pgood - goodword); badlen = (int)(pbad - su->su_badptr); if (goodlen <= 0 || badlen <= 0) break; mb_ptr_back(goodword, pgood); mb_ptr_back(su->su_badptr, pbad); #ifdef FEAT_MBYTE if (has_mbyte) { if (mb_ptr2char(pgood) != mb_ptr2char(pbad)) break; } else #endif if (*pgood != *pbad) break; } if (badlen == 0 && goodlen == 0) /* goodword doesn't change anything; may happen for "the the" changing * the first "the" to itself. */ return; if (gap->ga_len == 0) i = -1; else { /* Check if the word is already there. Also check the length that is * being replaced "thes," -> "these" is a different suggestion from * "thes" -> "these". */ stp = &SUG(*gap, 0); for (i = gap->ga_len; --i >= 0; ++stp) if (stp->st_wordlen == goodlen && stp->st_orglen == badlen && STRNCMP(stp->st_word, goodword, goodlen) == 0) { /* * Found it. Remember the word with the lowest score. */ if (stp->st_slang == NULL) stp->st_slang = slang; new_sug.st_score = score; new_sug.st_altscore = altscore; new_sug.st_had_bonus = had_bonus; if (stp->st_had_bonus != had_bonus) { /* Only one of the two had the soundalike score computed. * Need to do that for the other one now, otherwise the * scores can't be compared. This happens because * suggest_try_change() doesn't compute the soundalike * word to keep it fast, while some special methods set * the soundalike score to zero. */ if (had_bonus) rescore_one(su, stp); else { new_sug.st_word = stp->st_word; new_sug.st_wordlen = stp->st_wordlen; new_sug.st_slang = stp->st_slang; new_sug.st_orglen = badlen; rescore_one(su, &new_sug); } } if (stp->st_score > new_sug.st_score) { stp->st_score = new_sug.st_score; stp->st_altscore = new_sug.st_altscore; stp->st_had_bonus = new_sug.st_had_bonus; } break; } } if (i < 0 && ga_grow(gap, 1) == OK) { /* Add a suggestion. */ stp = &SUG(*gap, gap->ga_len); stp->st_word = vim_strnsave(goodword, goodlen); if (stp->st_word != NULL) { stp->st_wordlen = goodlen; stp->st_score = score; stp->st_altscore = altscore; stp->st_had_bonus = had_bonus; stp->st_orglen = badlen; stp->st_slang = slang; ++gap->ga_len; /* If we have too many suggestions now, sort the list and keep * the best suggestions. */ if (gap->ga_len > SUG_MAX_COUNT(su)) { if (maxsf) su->su_sfmaxscore = cleanup_suggestions(gap, su->su_sfmaxscore, SUG_CLEAN_COUNT(su)); else su->su_maxscore = cleanup_suggestions(gap, su->su_maxscore, SUG_CLEAN_COUNT(su)); } } } } /* * Suggestions may in fact be flagged as errors. Esp. for banned words and * for split words, such as "the the". Remove these from the list here. */ static void check_suggestions(su, gap) suginfo_T *su; garray_T *gap; /* either su_ga or su_sga */ { suggest_T *stp; int i; char_u longword[MAXWLEN + 1]; int len; hlf_T attr; stp = &SUG(*gap, 0); for (i = gap->ga_len - 1; i >= 0; --i) { /* Need to append what follows to check for "the the". */ vim_strncpy(longword, stp[i].st_word, MAXWLEN); len = stp[i].st_wordlen; vim_strncpy(longword + len, su->su_badptr + stp[i].st_orglen, MAXWLEN - len); attr = HLF_COUNT; (void)spell_check(curwin, longword, &attr, NULL, FALSE); if (attr != HLF_COUNT) { /* Remove this entry. */ vim_free(stp[i].st_word); --gap->ga_len; if (i < gap->ga_len) mch_memmove(stp + i, stp + i + 1, sizeof(suggest_T) * (gap->ga_len - i)); } } } /* * Add a word to be banned. */ static void add_banned(su, word) suginfo_T *su; char_u *word; { char_u *s; hash_T hash; hashitem_T *hi; hash = hash_hash(word); hi = hash_lookup(&su->su_banned, word, hash); if (HASHITEM_EMPTY(hi)) { s = vim_strsave(word); if (s != NULL) hash_add_item(&su->su_banned, hi, s, hash); } } /* * Recompute the score for all suggestions if sound-folding is possible. This * is slow, thus only done for the final results. */ static void rescore_suggestions(su) suginfo_T *su; { int i; if (su->su_sallang != NULL) for (i = 0; i < su->su_ga.ga_len; ++i) rescore_one(su, &SUG(su->su_ga, i)); } /* * Recompute the score for one suggestion if sound-folding is possible. */ static void rescore_one(su, stp) suginfo_T *su; suggest_T *stp; { slang_T *slang = stp->st_slang; char_u sal_badword[MAXWLEN]; char_u *p; /* Only rescore suggestions that have no sal score yet and do have a * language. */ if (slang != NULL && slang->sl_sal.ga_len > 0 && !stp->st_had_bonus) { if (slang == su->su_sallang) p = su->su_sal_badword; else { spell_soundfold(slang, su->su_fbadword, TRUE, sal_badword); p = sal_badword; } stp->st_altscore = stp_sal_score(stp, su, slang, p); if (stp->st_altscore == SCORE_MAXMAX) stp->st_altscore = SCORE_BIG; stp->st_score = RESCORE(stp->st_score, stp->st_altscore); stp->st_had_bonus = TRUE; } } static int #ifdef __BORLANDC__ _RTLENTRYF #endif sug_compare __ARGS((const void *s1, const void *s2)); /* * Function given to qsort() to sort the suggestions on st_score. * First on "st_score", then "st_altscore" then alphabetically. */ static int #ifdef __BORLANDC__ _RTLENTRYF #endif sug_compare(s1, s2) const void *s1; const void *s2; { suggest_T *p1 = (suggest_T *)s1; suggest_T *p2 = (suggest_T *)s2; int n = p1->st_score - p2->st_score; if (n == 0) { n = p1->st_altscore - p2->st_altscore; if (n == 0) n = STRICMP(p1->st_word, p2->st_word); } return n; } /* * Cleanup the suggestions: * - Sort on score. * - Remove words that won't be displayed. * Returns the maximum score in the list or "maxscore" unmodified. */ static int cleanup_suggestions(gap, maxscore, keep) garray_T *gap; int maxscore; int keep; /* nr of suggestions to keep */ { suggest_T *stp = &SUG(*gap, 0); int i; /* Sort the list. */ qsort(gap->ga_data, (size_t)gap->ga_len, sizeof(suggest_T), sug_compare); /* Truncate the list to the number of suggestions that will be displayed. */ if (gap->ga_len > keep) { for (i = keep; i < gap->ga_len; ++i) vim_free(stp[i].st_word); gap->ga_len = keep; return stp[keep - 1].st_score; } return maxscore; } #if defined(FEAT_EVAL) || defined(PROTO) /* * Soundfold a string, for soundfold(). * Result is in allocated memory, NULL for an error. */ char_u * eval_soundfold(word) char_u *word; { langp_T *lp; char_u sound[MAXWLEN]; int lpi; if (curwin->w_p_spell && *curwin->w_s->b_p_spl != NUL) /* Use the sound-folding of the first language that supports it. */ for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi) { lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi); if (lp->lp_slang->sl_sal.ga_len > 0) { /* soundfold the word */ spell_soundfold(lp->lp_slang, word, FALSE, sound); return vim_strsave(sound); } } /* No language with sound folding, return word as-is. */ return vim_strsave(word); } #endif /* * Turn "inword" into its sound-a-like equivalent in "res[MAXWLEN]". * * There are many ways to turn a word into a sound-a-like representation. The * oldest is Soundex (1918!). A nice overview can be found in "Approximate * swedish name matching - survey and test of different algorithms" by Klas * Erikson. * * We support two methods: * 1. SOFOFROM/SOFOTO do a simple character mapping. * 2. SAL items define a more advanced sound-folding (and much slower). */ static void spell_soundfold(slang, inword, folded, res) slang_T *slang; char_u *inword; int folded; /* "inword" is already case-folded */ char_u *res; { char_u fword[MAXWLEN]; char_u *word; if (slang->sl_sofo) /* SOFOFROM and SOFOTO used */ spell_soundfold_sofo(slang, inword, res); else { /* SAL items used. Requires the word to be case-folded. */ if (folded) word = inword; else { (void)spell_casefold(inword, (int)STRLEN(inword), fword, MAXWLEN); word = fword; } #ifdef FEAT_MBYTE if (has_mbyte) spell_soundfold_wsal(slang, word, res); else #endif spell_soundfold_sal(slang, word, res); } } /* * Perform sound folding of "inword" into "res" according to SOFOFROM and * SOFOTO lines. */ static void spell_soundfold_sofo(slang, inword, res) slang_T *slang; char_u *inword; char_u *res; { char_u *s; int ri = 0; int c; #ifdef FEAT_MBYTE if (has_mbyte) { int prevc = 0; int *ip; /* The sl_sal_first[] table contains the translation for chars up to * 255, sl_sal the rest. */ for (s = inword; *s != NUL; ) { c = mb_cptr2char_adv(&s); if (enc_utf8 ? utf_class(c) == 0 : vim_iswhite(c)) c = ' '; else if (c < 256) c = slang->sl_sal_first[c]; else { ip = ((int **)slang->sl_sal.ga_data)[c & 0xff]; if (ip == NULL) /* empty list, can't match */ c = NUL; else for (;;) /* find "c" in the list */ { if (*ip == 0) /* not found */ { c = NUL; break; } if (*ip == c) /* match! */ { c = ip[1]; break; } ip += 2; } } if (c != NUL && c != prevc) { ri += mb_char2bytes(c, res + ri); if (ri + MB_MAXBYTES > MAXWLEN) break; prevc = c; } } } else #endif { /* The sl_sal_first[] table contains the translation. */ for (s = inword; (c = *s) != NUL; ++s) { if (vim_iswhite(c)) c = ' '; else c = slang->sl_sal_first[c]; if (c != NUL && (ri == 0 || res[ri - 1] != c)) res[ri++] = c; } } res[ri] = NUL; } static void spell_soundfold_sal(slang, inword, res) slang_T *slang; char_u *inword; char_u *res; { salitem_T *smp; char_u word[MAXWLEN]; char_u *s = inword; char_u *t; char_u *pf; int i, j, z; int reslen; int n, k = 0; int z0; int k0; int n0; int c; int pri; int p0 = -333; int c0; /* Remove accents, if wanted. We actually remove all non-word characters. * But keep white space. We need a copy, the word may be changed here. */ if (slang->sl_rem_accents) { t = word; while (*s != NUL) { if (vim_iswhite(*s)) { *t++ = ' '; s = skipwhite(s); } else { if (spell_iswordp_nmw(s)) *t++ = *s; ++s; } } *t = NUL; } else vim_strncpy(word, s, MAXWLEN - 1); smp = (salitem_T *)slang->sl_sal.ga_data; /* * This comes from Aspell phonet.cpp. Converted from C++ to C. * Changed to keep spaces. */ i = reslen = z = 0; while ((c = word[i]) != NUL) { /* Start with the first rule that has the character in the word. */ n = slang->sl_sal_first[c]; z0 = 0; if (n >= 0) { /* check all rules for the same letter */ for (; (s = smp[n].sm_lead)[0] == c; ++n) { /* Quickly skip entries that don't match the word. Most * entries are less then three chars, optimize for that. */ k = smp[n].sm_leadlen; if (k > 1) { if (word[i + 1] != s[1]) continue; if (k > 2) { for (j = 2; j < k; ++j) if (word[i + j] != s[j]) break; if (j < k) continue; } } if ((pf = smp[n].sm_oneof) != NULL) { /* Check for match with one of the chars in "sm_oneof". */ while (*pf != NUL && *pf != word[i + k]) ++pf; if (*pf == NUL) continue; ++k; } s = smp[n].sm_rules; pri = 5; /* default priority */ p0 = *s; k0 = k; while (*s == '-' && k > 1) { k--; s++; } if (*s == '<') s++; if (VIM_ISDIGIT(*s)) { /* determine priority */ pri = *s - '0'; s++; } if (*s == '^' && *(s + 1) == '^') s++; if (*s == NUL || (*s == '^' && (i == 0 || !(word[i - 1] == ' ' || spell_iswordp(word + i - 1, curwin))) && (*(s + 1) != '$' || (!spell_iswordp(word + i + k0, curwin)))) || (*s == '$' && i > 0 && spell_iswordp(word + i - 1, curwin) && (!spell_iswordp(word + i + k0, curwin)))) { /* search for followup rules, if: */ /* followup and k > 1 and NO '-' in searchstring */ c0 = word[i + k - 1]; n0 = slang->sl_sal_first[c0]; if (slang->sl_followup && k > 1 && n0 >= 0 && p0 != '-' && word[i + k] != NUL) { /* test follow-up rule for "word[i + k]" */ for ( ; (s = smp[n0].sm_lead)[0] == c0; ++n0) { /* Quickly skip entries that don't match the word. * */ k0 = smp[n0].sm_leadlen; if (k0 > 1) { if (word[i + k] != s[1]) continue; if (k0 > 2) { pf = word + i + k + 1; for (j = 2; j < k0; ++j) if (*pf++ != s[j]) break; if (j < k0) continue; } } k0 += k - 1; if ((pf = smp[n0].sm_oneof) != NULL) { /* Check for match with one of the chars in * "sm_oneof". */ while (*pf != NUL && *pf != word[i + k0]) ++pf; if (*pf == NUL) continue; ++k0; } p0 = 5; s = smp[n0].sm_rules; while (*s == '-') { /* "k0" gets NOT reduced because * "if (k0 == k)" */ s++; } if (*s == '<') s++; if (VIM_ISDIGIT(*s)) { p0 = *s - '0'; s++; } if (*s == NUL /* *s == '^' cuts */ || (*s == '$' && !spell_iswordp(word + i + k0, curwin))) { if (k0 == k) /* this is just a piece of the string */ continue; if (p0 < pri) /* priority too low */ continue; /* rule fits; stop search */ break; } } if (p0 >= pri && smp[n0].sm_lead[0] == c0) continue; } /* replace string */ s = smp[n].sm_to; if (s == NULL) s = (char_u *)""; pf = smp[n].sm_rules; p0 = (vim_strchr(pf, '<') != NULL) ? 1 : 0; if (p0 == 1 && z == 0) { /* rule with '<' is used */ if (reslen > 0 && *s != NUL && (res[reslen - 1] == c || res[reslen - 1] == *s)) reslen--; z0 = 1; z = 1; k0 = 0; while (*s != NUL && word[i + k0] != NUL) { word[i + k0] = *s; k0++; s++; } if (k > k0) STRMOVE(word + i + k0, word + i + k); /* new "actual letter" */ c = word[i]; } else { /* no '<' rule used */ i += k - 1; z = 0; while (*s != NUL && s[1] != NUL && reslen < MAXWLEN) { if (reslen == 0 || res[reslen - 1] != *s) res[reslen++] = *s; s++; } /* new "actual letter" */ c = *s; if (strstr((char *)pf, "^^") != NULL) { if (c != NUL) res[reslen++] = c; STRMOVE(word, word + i + 1); i = 0; z0 = 1; } } break; } } } else if (vim_iswhite(c)) { c = ' '; k = 1; } if (z0 == 0) { if (k && !p0 && reslen < MAXWLEN && c != NUL && (!slang->sl_collapse || reslen == 0 || res[reslen - 1] != c)) /* condense only double letters */ res[reslen++] = c; i++; z = 0; k = 0; } } res[reslen] = NUL; } #ifdef FEAT_MBYTE /* * Turn "inword" into its sound-a-like equivalent in "res[MAXWLEN]". * Multi-byte version of spell_soundfold(). */ static void spell_soundfold_wsal(slang, inword, res) slang_T *slang; char_u *inword; char_u *res; { salitem_T *smp = (salitem_T *)slang->sl_sal.ga_data; int word[MAXWLEN]; int wres[MAXWLEN]; int l; char_u *s; int *ws; char_u *t; int *pf; int i, j, z; int reslen; int n, k = 0; int z0; int k0; int n0; int c; int pri; int p0 = -333; int c0; int did_white = FALSE; int wordlen; /* * Convert the multi-byte string to a wide-character string. * Remove accents, if wanted. We actually remove all non-word characters. * But keep white space. */ wordlen = 0; for (s = inword; *s != NUL; ) { t = s; c = mb_cptr2char_adv(&s); if (slang->sl_rem_accents) { if (enc_utf8 ? utf_class(c) == 0 : vim_iswhite(c)) { if (did_white) continue; c = ' '; did_white = TRUE; } else { did_white = FALSE; if (!spell_iswordp_nmw(t)) continue; } } word[wordlen++] = c; } word[wordlen] = NUL; /* * This algorithm comes from Aspell phonet.cpp. * Converted from C++ to C. Added support for multi-byte chars. * Changed to keep spaces. */ i = reslen = z = 0; while ((c = word[i]) != NUL) { /* Start with the first rule that has the character in the word. */ n = slang->sl_sal_first[c & 0xff]; z0 = 0; if (n >= 0) { /* Check all rules for the same index byte. * If c is 0x300 need extra check for the end of the array, as * (c & 0xff) is NUL. */ for (; ((ws = smp[n].sm_lead_w)[0] & 0xff) == (c & 0xff) && ws[0] != NUL; ++n) { /* Quickly skip entries that don't match the word. Most * entries are less then three chars, optimize for that. */ if (c != ws[0]) continue; k = smp[n].sm_leadlen; if (k > 1) { if (word[i + 1] != ws[1]) continue; if (k > 2) { for (j = 2; j < k; ++j) if (word[i + j] != ws[j]) break; if (j < k) continue; } } if ((pf = smp[n].sm_oneof_w) != NULL) { /* Check for match with one of the chars in "sm_oneof". */ while (*pf != NUL && *pf != word[i + k]) ++pf; if (*pf == NUL) continue; ++k; } s = smp[n].sm_rules; pri = 5; /* default priority */ p0 = *s; k0 = k; while (*s == '-' && k > 1) { k--; s++; } if (*s == '<') s++; if (VIM_ISDIGIT(*s)) { /* determine priority */ pri = *s - '0'; s++; } if (*s == '^' && *(s + 1) == '^') s++; if (*s == NUL || (*s == '^' && (i == 0 || !(word[i - 1] == ' ' || spell_iswordp_w(word + i - 1, curwin))) && (*(s + 1) != '$' || (!spell_iswordp_w(word + i + k0, curwin)))) || (*s == '$' && i > 0 && spell_iswordp_w(word + i - 1, curwin) && (!spell_iswordp_w(word + i + k0, curwin)))) { /* search for followup rules, if: */ /* followup and k > 1 and NO '-' in searchstring */ c0 = word[i + k - 1]; n0 = slang->sl_sal_first[c0 & 0xff]; if (slang->sl_followup && k > 1 && n0 >= 0 && p0 != '-' && word[i + k] != NUL) { /* Test follow-up rule for "word[i + k]"; loop over * all entries with the same index byte. */ for ( ; ((ws = smp[n0].sm_lead_w)[0] & 0xff) == (c0 & 0xff); ++n0) { /* Quickly skip entries that don't match the word. */ if (c0 != ws[0]) continue; k0 = smp[n0].sm_leadlen; if (k0 > 1) { if (word[i + k] != ws[1]) continue; if (k0 > 2) { pf = word + i + k + 1; for (j = 2; j < k0; ++j) if (*pf++ != ws[j]) break; if (j < k0) continue; } } k0 += k - 1; if ((pf = smp[n0].sm_oneof_w) != NULL) { /* Check for match with one of the chars in * "sm_oneof". */ while (*pf != NUL && *pf != word[i + k0]) ++pf; if (*pf == NUL) continue; ++k0; } p0 = 5; s = smp[n0].sm_rules; while (*s == '-') { /* "k0" gets NOT reduced because * "if (k0 == k)" */ s++; } if (*s == '<') s++; if (VIM_ISDIGIT(*s)) { p0 = *s - '0'; s++; } if (*s == NUL /* *s == '^' cuts */ || (*s == '$' && !spell_iswordp_w(word + i + k0, curwin))) { if (k0 == k) /* this is just a piece of the string */ continue; if (p0 < pri) /* priority too low */ continue; /* rule fits; stop search */ break; } } if (p0 >= pri && (smp[n0].sm_lead_w[0] & 0xff) == (c0 & 0xff)) continue; } /* replace string */ ws = smp[n].sm_to_w; s = smp[n].sm_rules; p0 = (vim_strchr(s, '<') != NULL) ? 1 : 0; if (p0 == 1 && z == 0) { /* rule with '<' is used */ if (reslen > 0 && ws != NULL && *ws != NUL && (wres[reslen - 1] == c || wres[reslen - 1] == *ws)) reslen--; z0 = 1; z = 1; k0 = 0; if (ws != NULL) while (*ws != NUL && word[i + k0] != NUL) { word[i + k0] = *ws; k0++; ws++; } if (k > k0) mch_memmove(word + i + k0, word + i + k, sizeof(int) * (wordlen - (i + k) + 1)); /* new "actual letter" */ c = word[i]; } else { /* no '<' rule used */ i += k - 1; z = 0; if (ws != NULL) while (*ws != NUL && ws[1] != NUL && reslen < MAXWLEN) { if (reslen == 0 || wres[reslen - 1] != *ws) wres[reslen++] = *ws; ws++; } /* new "actual letter" */ if (ws == NULL) c = NUL; else c = *ws; if (strstr((char *)s, "^^") != NULL) { if (c != NUL) wres[reslen++] = c; mch_memmove(word, word + i + 1, sizeof(int) * (wordlen - (i + 1) + 1)); i = 0; z0 = 1; } } break; } } } else if (vim_iswhite(c)) { c = ' '; k = 1; } if (z0 == 0) { if (k && !p0 && reslen < MAXWLEN && c != NUL && (!slang->sl_collapse || reslen == 0 || wres[reslen - 1] != c)) /* condense only double letters */ wres[reslen++] = c; i++; z = 0; k = 0; } } /* Convert wide characters in "wres" to a multi-byte string in "res". */ l = 0; for (n = 0; n < reslen; ++n) { l += mb_char2bytes(wres[n], res + l); if (l + MB_MAXBYTES > MAXWLEN) break; } res[l] = NUL; } #endif /* * Compute a score for two sound-a-like words. * This permits up to two inserts/deletes/swaps/etc. to keep things fast. * Instead of a generic loop we write out the code. That keeps it fast by * avoiding checks that will not be possible. */ static int soundalike_score(goodstart, badstart) char_u *goodstart; /* sound-folded good word */ char_u *badstart; /* sound-folded bad word */ { char_u *goodsound = goodstart; char_u *badsound = badstart; int goodlen; int badlen; int n; char_u *pl, *ps; char_u *pl2, *ps2; int score = 0; /* Adding/inserting "*" at the start (word starts with vowel) shouldn't be * counted so much, vowels halfway the word aren't counted at all. */ if ((*badsound == '*' || *goodsound == '*') && *badsound != *goodsound) { if ((badsound[0] == NUL && goodsound[1] == NUL) || (goodsound[0] == NUL && badsound[1] == NUL)) /* changing word with vowel to word without a sound */ return SCORE_DEL; if (badsound[0] == NUL || goodsound[0] == NUL) /* more than two changes */ return SCORE_MAXMAX; if (badsound[1] == goodsound[1] || (badsound[1] != NUL && goodsound[1] != NUL && badsound[2] == goodsound[2])) { /* handle like a substitute */ } else { score = 2 * SCORE_DEL / 3; if (*badsound == '*') ++badsound; else ++goodsound; } } goodlen = (int)STRLEN(goodsound); badlen = (int)STRLEN(badsound); /* Return quickly if the lengths are too different to be fixed by two * changes. */ n = goodlen - badlen; if (n < -2 || n > 2) return SCORE_MAXMAX; if (n > 0) { pl = goodsound; /* goodsound is longest */ ps = badsound; } else { pl = badsound; /* badsound is longest */ ps = goodsound; } /* Skip over the identical part. */ while (*pl == *ps && *pl != NUL) { ++pl; ++ps; } switch (n) { case -2: case 2: /* * Must delete two characters from "pl". */ ++pl; /* first delete */ while (*pl == *ps) { ++pl; ++ps; } /* strings must be equal after second delete */ if (STRCMP(pl + 1, ps) == 0) return score + SCORE_DEL * 2; /* Failed to compare. */ break; case -1: case 1: /* * Minimal one delete from "pl" required. */ /* 1: delete */ pl2 = pl + 1; ps2 = ps; while (*pl2 == *ps2) { if (*pl2 == NUL) /* reached the end */ return score + SCORE_DEL; ++pl2; ++ps2; } /* 2: delete then swap, then rest must be equal */ if (pl2[0] == ps2[1] && pl2[1] == ps2[0] && STRCMP(pl2 + 2, ps2 + 2) == 0) return score + SCORE_DEL + SCORE_SWAP; /* 3: delete then substitute, then the rest must be equal */ if (STRCMP(pl2 + 1, ps2 + 1) == 0) return score + SCORE_DEL + SCORE_SUBST; /* 4: first swap then delete */ if (pl[0] == ps[1] && pl[1] == ps[0]) { pl2 = pl + 2; /* swap, skip two chars */ ps2 = ps + 2; while (*pl2 == *ps2) { ++pl2; ++ps2; } /* delete a char and then strings must be equal */ if (STRCMP(pl2 + 1, ps2) == 0) return score + SCORE_SWAP + SCORE_DEL; } /* 5: first substitute then delete */ pl2 = pl + 1; /* substitute, skip one char */ ps2 = ps + 1; while (*pl2 == *ps2) { ++pl2; ++ps2; } /* delete a char and then strings must be equal */ if (STRCMP(pl2 + 1, ps2) == 0) return score + SCORE_SUBST + SCORE_DEL; /* Failed to compare. */ break; case 0: /* * Lengths are equal, thus changes must result in same length: An * insert is only possible in combination with a delete. * 1: check if for identical strings */ if (*pl == NUL) return score; /* 2: swap */ if (pl[0] == ps[1] && pl[1] == ps[0]) { pl2 = pl + 2; /* swap, skip two chars */ ps2 = ps + 2; while (*pl2 == *ps2) { if (*pl2 == NUL) /* reached the end */ return score + SCORE_SWAP; ++pl2; ++ps2; } /* 3: swap and swap again */ if (pl2[0] == ps2[1] && pl2[1] == ps2[0] && STRCMP(pl2 + 2, ps2 + 2) == 0) return score + SCORE_SWAP + SCORE_SWAP; /* 4: swap and substitute */ if (STRCMP(pl2 + 1, ps2 + 1) == 0) return score + SCORE_SWAP + SCORE_SUBST; } /* 5: substitute */ pl2 = pl + 1; ps2 = ps + 1; while (*pl2 == *ps2) { if (*pl2 == NUL) /* reached the end */ return score + SCORE_SUBST; ++pl2; ++ps2; } /* 6: substitute and swap */ if (pl2[0] == ps2[1] && pl2[1] == ps2[0] && STRCMP(pl2 + 2, ps2 + 2) == 0) return score + SCORE_SUBST + SCORE_SWAP; /* 7: substitute and substitute */ if (STRCMP(pl2 + 1, ps2 + 1) == 0) return score + SCORE_SUBST + SCORE_SUBST; /* 8: insert then delete */ pl2 = pl; ps2 = ps + 1; while (*pl2 == *ps2) { ++pl2; ++ps2; } if (STRCMP(pl2 + 1, ps2) == 0) return score + SCORE_INS + SCORE_DEL; /* 9: delete then insert */ pl2 = pl + 1; ps2 = ps; while (*pl2 == *ps2) { ++pl2; ++ps2; } if (STRCMP(pl2, ps2 + 1) == 0) return score + SCORE_INS + SCORE_DEL; /* Failed to compare. */ break; } return SCORE_MAXMAX; } /* * Compute the "edit distance" to turn "badword" into "goodword". The less * deletes/inserts/substitutes/swaps are required the lower the score. * * The algorithm is described by Du and Chang, 1992. * The implementation of the algorithm comes from Aspell editdist.cpp, * edit_distance(). It has been converted from C++ to C and modified to * support multi-byte characters. */ static int spell_edit_score(slang, badword, goodword) slang_T *slang; char_u *badword; char_u *goodword; { int *cnt; int badlen, goodlen; /* lengths including NUL */ int j, i; int t; int bc, gc; int pbc, pgc; #ifdef FEAT_MBYTE char_u *p; int wbadword[MAXWLEN]; int wgoodword[MAXWLEN]; if (has_mbyte) { /* Get the characters from the multi-byte strings and put them in an * int array for easy access. */ for (p = badword, badlen = 0; *p != NUL; ) wbadword[badlen++] = mb_cptr2char_adv(&p); wbadword[badlen++] = 0; for (p = goodword, goodlen = 0; *p != NUL; ) wgoodword[goodlen++] = mb_cptr2char_adv(&p); wgoodword[goodlen++] = 0; } else #endif { badlen = (int)STRLEN(badword) + 1; goodlen = (int)STRLEN(goodword) + 1; } /* We use "cnt" as an array: CNT(badword_idx, goodword_idx). */ #define CNT(a, b) cnt[(a) + (b) * (badlen + 1)] cnt = (int *)lalloc((long_u)(sizeof(int) * (badlen + 1) * (goodlen + 1)), TRUE); if (cnt == NULL) return 0; /* out of memory */ CNT(0, 0) = 0; for (j = 1; j <= goodlen; ++j) CNT(0, j) = CNT(0, j - 1) + SCORE_INS; for (i = 1; i <= badlen; ++i) { CNT(i, 0) = CNT(i - 1, 0) + SCORE_DEL; for (j = 1; j <= goodlen; ++j) { #ifdef FEAT_MBYTE if (has_mbyte) { bc = wbadword[i - 1]; gc = wgoodword[j - 1]; } else #endif { bc = badword[i - 1]; gc = goodword[j - 1]; } if (bc == gc) CNT(i, j) = CNT(i - 1, j - 1); else { /* Use a better score when there is only a case difference. */ if (SPELL_TOFOLD(bc) == SPELL_TOFOLD(gc)) CNT(i, j) = SCORE_ICASE + CNT(i - 1, j - 1); else { /* For a similar character use SCORE_SIMILAR. */ if (slang != NULL && slang->sl_has_map && similar_chars(slang, gc, bc)) CNT(i, j) = SCORE_SIMILAR + CNT(i - 1, j - 1); else CNT(i, j) = SCORE_SUBST + CNT(i - 1, j - 1); } if (i > 1 && j > 1) { #ifdef FEAT_MBYTE if (has_mbyte) { pbc = wbadword[i - 2]; pgc = wgoodword[j - 2]; } else #endif { pbc = badword[i - 2]; pgc = goodword[j - 2]; } if (bc == pgc && pbc == gc) { t = SCORE_SWAP + CNT(i - 2, j - 2); if (t < CNT(i, j)) CNT(i, j) = t; } } t = SCORE_DEL + CNT(i - 1, j); if (t < CNT(i, j)) CNT(i, j) = t; t = SCORE_INS + CNT(i, j - 1); if (t < CNT(i, j)) CNT(i, j) = t; } } } i = CNT(badlen - 1, goodlen - 1); vim_free(cnt); return i; } typedef struct { int badi; int goodi; int score; } limitscore_T; /* * Like spell_edit_score(), but with a limit on the score to make it faster. * May return SCORE_MAXMAX when the score is higher than "limit". * * This uses a stack for the edits still to be tried. * The idea comes from Aspell leditdist.cpp. Rewritten in C and added support * for multi-byte characters. */ static int spell_edit_score_limit(slang, badword, goodword, limit) slang_T *slang; char_u *badword; char_u *goodword; int limit; { limitscore_T stack[10]; /* allow for over 3 * 2 edits */ int stackidx; int bi, gi; int bi2, gi2; int bc, gc; int score; int score_off; int minscore; int round; #ifdef FEAT_MBYTE /* Multi-byte characters require a bit more work, use a different function * to avoid testing "has_mbyte" quite often. */ if (has_mbyte) return spell_edit_score_limit_w(slang, badword, goodword, limit); #endif /* * The idea is to go from start to end over the words. So long as * characters are equal just continue, this always gives the lowest score. * When there is a difference try several alternatives. Each alternative * increases "score" for the edit distance. Some of the alternatives are * pushed unto a stack and tried later, some are tried right away. At the * end of the word the score for one alternative is known. The lowest * possible score is stored in "minscore". */ stackidx = 0; bi = 0; gi = 0; score = 0; minscore = limit + 1; for (;;) { /* Skip over an equal part, score remains the same. */ for (;;) { bc = badword[bi]; gc = goodword[gi]; if (bc != gc) /* stop at a char that's different */ break; if (bc == NUL) /* both words end */ { if (score < minscore) minscore = score; goto pop; /* do next alternative */ } ++bi; ++gi; } if (gc == NUL) /* goodword ends, delete badword chars */ { do { if ((score += SCORE_DEL) >= minscore) goto pop; /* do next alternative */ } while (badword[++bi] != NUL); minscore = score; } else if (bc == NUL) /* badword ends, insert badword chars */ { do { if ((score += SCORE_INS) >= minscore) goto pop; /* do next alternative */ } while (goodword[++gi] != NUL); minscore = score; } else /* both words continue */ { /* If not close to the limit, perform a change. Only try changes * that may lead to a lower score than "minscore". * round 0: try deleting a char from badword * round 1: try inserting a char in badword */ for (round = 0; round <= 1; ++round) { score_off = score + (round == 0 ? SCORE_DEL : SCORE_INS); if (score_off < minscore) { if (score_off + SCORE_EDIT_MIN >= minscore) { /* Near the limit, rest of the words must match. We * can check that right now, no need to push an item * onto the stack. */ bi2 = bi + 1 - round; gi2 = gi + round; while (goodword[gi2] == badword[bi2]) { if (goodword[gi2] == NUL) { minscore = score_off; break; } ++bi2; ++gi2; } } else { /* try deleting/inserting a character later */ stack[stackidx].badi = bi + 1 - round; stack[stackidx].goodi = gi + round; stack[stackidx].score = score_off; ++stackidx; } } } if (score + SCORE_SWAP < minscore) { /* If swapping two characters makes a match then the * substitution is more expensive, thus there is no need to * try both. */ if (gc == badword[bi + 1] && bc == goodword[gi + 1]) { /* Swap two characters, that is: skip them. */ gi += 2; bi += 2; score += SCORE_SWAP; continue; } } /* Substitute one character for another which is the same * thing as deleting a character from both goodword and badword. * Use a better score when there is only a case difference. */ if (SPELL_TOFOLD(bc) == SPELL_TOFOLD(gc)) score += SCORE_ICASE; else { /* For a similar character use SCORE_SIMILAR. */ if (slang != NULL && slang->sl_has_map && similar_chars(slang, gc, bc)) score += SCORE_SIMILAR; else score += SCORE_SUBST; } if (score < minscore) { /* Do the substitution. */ ++gi; ++bi; continue; } } pop: /* * Get here to try the next alternative, pop it from the stack. */ if (stackidx == 0) /* stack is empty, finished */ break; /* pop an item from the stack */ --stackidx; gi = stack[stackidx].goodi; bi = stack[stackidx].badi; score = stack[stackidx].score; } /* When the score goes over "limit" it may actually be much higher. * Return a very large number to avoid going below the limit when giving a * bonus. */ if (minscore > limit) return SCORE_MAXMAX; return minscore; } #ifdef FEAT_MBYTE /* * Multi-byte version of spell_edit_score_limit(). * Keep it in sync with the above! */ static int spell_edit_score_limit_w(slang, badword, goodword, limit) slang_T *slang; char_u *badword; char_u *goodword; int limit; { limitscore_T stack[10]; /* allow for over 3 * 2 edits */ int stackidx; int bi, gi; int bi2, gi2; int bc, gc; int score; int score_off; int minscore; int round; char_u *p; int wbadword[MAXWLEN]; int wgoodword[MAXWLEN]; /* Get the characters from the multi-byte strings and put them in an * int array for easy access. */ bi = 0; for (p = badword; *p != NUL; ) wbadword[bi++] = mb_cptr2char_adv(&p); wbadword[bi++] = 0; gi = 0; for (p = goodword; *p != NUL; ) wgoodword[gi++] = mb_cptr2char_adv(&p); wgoodword[gi++] = 0; /* * The idea is to go from start to end over the words. So long as * characters are equal just continue, this always gives the lowest score. * When there is a difference try several alternatives. Each alternative * increases "score" for the edit distance. Some of the alternatives are * pushed unto a stack and tried later, some are tried right away. At the * end of the word the score for one alternative is known. The lowest * possible score is stored in "minscore". */ stackidx = 0; bi = 0; gi = 0; score = 0; minscore = limit + 1; for (;;) { /* Skip over an equal part, score remains the same. */ for (;;) { bc = wbadword[bi]; gc = wgoodword[gi]; if (bc != gc) /* stop at a char that's different */ break; if (bc == NUL) /* both words end */ { if (score < minscore) minscore = score; goto pop; /* do next alternative */ } ++bi; ++gi; } if (gc == NUL) /* goodword ends, delete badword chars */ { do { if ((score += SCORE_DEL) >= minscore) goto pop; /* do next alternative */ } while (wbadword[++bi] != NUL); minscore = score; } else if (bc == NUL) /* badword ends, insert badword chars */ { do { if ((score += SCORE_INS) >= minscore) goto pop; /* do next alternative */ } while (wgoodword[++gi] != NUL); minscore = score; } else /* both words continue */ { /* If not close to the limit, perform a change. Only try changes * that may lead to a lower score than "minscore". * round 0: try deleting a char from badword * round 1: try inserting a char in badword */ for (round = 0; round <= 1; ++round) { score_off = score + (round == 0 ? SCORE_DEL : SCORE_INS); if (score_off < minscore) { if (score_off + SCORE_EDIT_MIN >= minscore) { /* Near the limit, rest of the words must match. We * can check that right now, no need to push an item * onto the stack. */ bi2 = bi + 1 - round; gi2 = gi + round; while (wgoodword[gi2] == wbadword[bi2]) { if (wgoodword[gi2] == NUL) { minscore = score_off; break; } ++bi2; ++gi2; } } else { /* try deleting a character from badword later */ stack[stackidx].badi = bi + 1 - round; stack[stackidx].goodi = gi + round; stack[stackidx].score = score_off; ++stackidx; } } } if (score + SCORE_SWAP < minscore) { /* If swapping two characters makes a match then the * substitution is more expensive, thus there is no need to * try both. */ if (gc == wbadword[bi + 1] && bc == wgoodword[gi + 1]) { /* Swap two characters, that is: skip them. */ gi += 2; bi += 2; score += SCORE_SWAP; continue; } } /* Substitute one character for another which is the same * thing as deleting a character from both goodword and badword. * Use a better score when there is only a case difference. */ if (SPELL_TOFOLD(bc) == SPELL_TOFOLD(gc)) score += SCORE_ICASE; else { /* For a similar character use SCORE_SIMILAR. */ if (slang != NULL && slang->sl_has_map && similar_chars(slang, gc, bc)) score += SCORE_SIMILAR; else score += SCORE_SUBST; } if (score < minscore) { /* Do the substitution. */ ++gi; ++bi; continue; } } pop: /* * Get here to try the next alternative, pop it from the stack. */ if (stackidx == 0) /* stack is empty, finished */ break; /* pop an item from the stack */ --stackidx; gi = stack[stackidx].goodi; bi = stack[stackidx].badi; score = stack[stackidx].score; } /* When the score goes over "limit" it may actually be much higher. * Return a very large number to avoid going below the limit when giving a * bonus. */ if (minscore > limit) return SCORE_MAXMAX; return minscore; } #endif /* * ":spellinfo" */ void ex_spellinfo(eap) exarg_T *eap UNUSED; { int lpi; langp_T *lp; char_u *p; if (no_spell_checking(curwin)) return; msg_start(); for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len && !got_int; ++lpi) { lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi); msg_puts((char_u *)"file: "); msg_puts(lp->lp_slang->sl_fname); msg_putchar('\n'); p = lp->lp_slang->sl_info; if (p != NULL) { msg_puts(p); msg_putchar('\n'); } } msg_end(); } #define DUMPFLAG_KEEPCASE 1 /* round 2: keep-case tree */ #define DUMPFLAG_COUNT 2 /* include word count */ #define DUMPFLAG_ICASE 4 /* ignore case when finding matches */ #define DUMPFLAG_ONECAP 8 /* pattern starts with capital */ #define DUMPFLAG_ALLCAP 16 /* pattern is all capitals */ /* * ":spelldump" */ void ex_spelldump(eap) exarg_T *eap; { if (no_spell_checking(curwin)) return; /* Create a new empty buffer by splitting the window. */ do_cmdline_cmd((char_u *)"new"); if (!bufempty() || !buf_valid(curbuf)) return; spell_dump_compl(NULL, 0, NULL, eap->forceit ? DUMPFLAG_COUNT : 0); /* Delete the empty line that we started with. */ if (curbuf->b_ml.ml_line_count > 1) ml_delete(curbuf->b_ml.ml_line_count, FALSE); redraw_later(NOT_VALID); } /* * Go through all possible words and: * 1. When "pat" is NULL: dump a list of all words in the current buffer. * "ic" and "dir" are not used. * 2. When "pat" is not NULL: add matching words to insert mode completion. */ void spell_dump_compl(pat, ic, dir, dumpflags_arg) char_u *pat; /* leading part of the word */ int ic; /* ignore case */ int *dir; /* direction for adding matches */ int dumpflags_arg; /* DUMPFLAG_* */ { langp_T *lp; slang_T *slang; idx_T arridx[MAXWLEN]; int curi[MAXWLEN]; char_u word[MAXWLEN]; int c; char_u *byts; idx_T *idxs; linenr_T lnum = 0; int round; int depth; int n; int flags; char_u *region_names = NULL; /* region names being used */ int do_region = TRUE; /* dump region names and numbers */ char_u *p; int lpi; int dumpflags = dumpflags_arg; int patlen; /* When ignoring case or when the pattern starts with capital pass this on * to dump_word(). */ if (pat != NULL) { if (ic) dumpflags |= DUMPFLAG_ICASE; else { n = captype(pat, NULL); if (n == WF_ONECAP) dumpflags |= DUMPFLAG_ONECAP; else if (n == WF_ALLCAP #ifdef FEAT_MBYTE && (int)STRLEN(pat) > mb_ptr2len(pat) #else && (int)STRLEN(pat) > 1 #endif ) dumpflags |= DUMPFLAG_ALLCAP; } } /* Find out if we can support regions: All languages must support the same * regions or none at all. */ for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi) { lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi); p = lp->lp_slang->sl_regions; if (p[0] != 0) { if (region_names == NULL) /* first language with regions */ region_names = p; else if (STRCMP(region_names, p) != 0) { do_region = FALSE; /* region names are different */ break; } } } if (do_region && region_names != NULL) { if (pat == NULL) { vim_snprintf((char *)IObuff, IOSIZE, "/regions=%s", region_names); ml_append(lnum++, IObuff, (colnr_T)0, FALSE); } } else do_region = FALSE; /* * Loop over all files loaded for the entries in 'spelllang'. */ for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi) { lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi); slang = lp->lp_slang; if (slang->sl_fbyts == NULL) /* reloading failed */ continue; if (pat == NULL) { vim_snprintf((char *)IObuff, IOSIZE, "# file: %s", slang->sl_fname); ml_append(lnum++, IObuff, (colnr_T)0, FALSE); } /* When matching with a pattern and there are no prefixes only use * parts of the tree that match "pat". */ if (pat != NULL && slang->sl_pbyts == NULL) patlen = (int)STRLEN(pat); else patlen = -1; /* round 1: case-folded tree * round 2: keep-case tree */ for (round = 1; round <= 2; ++round) { if (round == 1) { dumpflags &= ~DUMPFLAG_KEEPCASE; byts = slang->sl_fbyts; idxs = slang->sl_fidxs; } else { dumpflags |= DUMPFLAG_KEEPCASE; byts = slang->sl_kbyts; idxs = slang->sl_kidxs; } if (byts == NULL) continue; /* array is empty */ depth = 0; arridx[0] = 0; curi[0] = 1; while (depth >= 0 && !got_int && (pat == NULL || !compl_interrupted)) { if (curi[depth] > byts[arridx[depth]]) { /* Done all bytes at this node, go up one level. */ --depth; line_breakcheck(); ins_compl_check_keys(50); } else { /* Do one more byte at this node. */ n = arridx[depth] + curi[depth]; ++curi[depth]; c = byts[n]; if (c == 0) { /* End of word, deal with the word. * Don't use keep-case words in the fold-case tree, * they will appear in the keep-case tree. * Only use the word when the region matches. */ flags = (int)idxs[n]; if ((round == 2 || (flags & WF_KEEPCAP) == 0) && (flags & WF_NEEDCOMP) == 0 && (do_region || (flags & WF_REGION) == 0 || (((unsigned)flags >> 16) & lp->lp_region) != 0)) { word[depth] = NUL; if (!do_region) flags &= ~WF_REGION; /* Dump the basic word if there is no prefix or * when it's the first one. */ c = (unsigned)flags >> 24; if (c == 0 || curi[depth] == 2) { dump_word(slang, word, pat, dir, dumpflags, flags, lnum); if (pat == NULL) ++lnum; } /* Apply the prefix, if there is one. */ if (c != 0) lnum = dump_prefixes(slang, word, pat, dir, dumpflags, flags, lnum); } } else { /* Normal char, go one level deeper. */ word[depth++] = c; arridx[depth] = idxs[n]; curi[depth] = 1; /* Check if this characters matches with the pattern. * If not skip the whole tree below it. * Always ignore case here, dump_word() will check * proper case later. This isn't exactly right when * length changes for multi-byte characters with * ignore case... */ if (depth <= patlen && MB_STRNICMP(word, pat, depth) != 0) --depth; } } } } } } /* * Dump one word: apply case modifications and append a line to the buffer. * When "lnum" is zero add insert mode completion. */ static void dump_word(slang, word, pat, dir, dumpflags, wordflags, lnum) slang_T *slang; char_u *word; char_u *pat; int *dir; int dumpflags; int wordflags; linenr_T lnum; { int keepcap = FALSE; char_u *p; char_u *tw; char_u cword[MAXWLEN]; char_u badword[MAXWLEN + 10]; int i; int flags = wordflags; if (dumpflags & DUMPFLAG_ONECAP) flags |= WF_ONECAP; if (dumpflags & DUMPFLAG_ALLCAP) flags |= WF_ALLCAP; if ((dumpflags & DUMPFLAG_KEEPCASE) == 0 && (flags & WF_CAPMASK) != 0) { /* Need to fix case according to "flags". */ make_case_word(word, cword, flags); p = cword; } else { p = word; if ((dumpflags & DUMPFLAG_KEEPCASE) && ((captype(word, NULL) & WF_KEEPCAP) == 0 || (flags & WF_FIXCAP) != 0)) keepcap = TRUE; } tw = p; if (pat == NULL) { /* Add flags and regions after a slash. */ if ((flags & (WF_BANNED | WF_RARE | WF_REGION)) || keepcap) { STRCPY(badword, p); STRCAT(badword, "/"); if (keepcap) STRCAT(badword, "="); if (flags & WF_BANNED) STRCAT(badword, "!"); else if (flags & WF_RARE) STRCAT(badword, "?"); if (flags & WF_REGION) for (i = 0; i < 7; ++i) if (flags & (0x10000 << i)) sprintf((char *)badword + STRLEN(badword), "%d", i + 1); p = badword; } if (dumpflags & DUMPFLAG_COUNT) { hashitem_T *hi; /* Include the word count for ":spelldump!". */ hi = hash_find(&slang->sl_wordcount, tw); if (!HASHITEM_EMPTY(hi)) { vim_snprintf((char *)IObuff, IOSIZE, "%s\t%d", tw, HI2WC(hi)->wc_count); p = IObuff; } } ml_append(lnum, p, (colnr_T)0, FALSE); } else if (((dumpflags & DUMPFLAG_ICASE) ? MB_STRNICMP(p, pat, STRLEN(pat)) == 0 : STRNCMP(p, pat, STRLEN(pat)) == 0) && ins_compl_add_infercase(p, (int)STRLEN(p), p_ic, NULL, *dir, 0) == OK) /* if dir was BACKWARD then honor it just once */ *dir = FORWARD; } /* * For ":spelldump": Find matching prefixes for "word". Prepend each to * "word" and append a line to the buffer. * When "lnum" is zero add insert mode completion. * Return the updated line number. */ static linenr_T dump_prefixes(slang, word, pat, dir, dumpflags, flags, startlnum) slang_T *slang; char_u *word; /* case-folded word */ char_u *pat; int *dir; int dumpflags; int flags; /* flags with prefix ID */ linenr_T startlnum; { idx_T arridx[MAXWLEN]; int curi[MAXWLEN]; char_u prefix[MAXWLEN]; char_u word_up[MAXWLEN]; int has_word_up = FALSE; int c; char_u *byts; idx_T *idxs; linenr_T lnum = startlnum; int depth; int n; int len; int i; /* If the word starts with a lower-case letter make the word with an * upper-case letter in word_up[]. */ c = PTR2CHAR(word); if (SPELL_TOUPPER(c) != c) { onecap_copy(word, word_up, TRUE); has_word_up = TRUE; } byts = slang->sl_pbyts; idxs = slang->sl_pidxs; if (byts != NULL) /* array not is empty */ { /* * Loop over all prefixes, building them byte-by-byte in prefix[]. * When at the end of a prefix check that it supports "flags". */ depth = 0; arridx[0] = 0; curi[0] = 1; while (depth >= 0 && !got_int) { n = arridx[depth]; len = byts[n]; if (curi[depth] > len) { /* Done all bytes at this node, go up one level. */ --depth; line_breakcheck(); } else { /* Do one more byte at this node. */ n += curi[depth]; ++curi[depth]; c = byts[n]; if (c == 0) { /* End of prefix, find out how many IDs there are. */ for (i = 1; i < len; ++i) if (byts[n + i] != 0) break; curi[depth] += i - 1; c = valid_word_prefix(i, n, flags, word, slang, FALSE); if (c != 0) { vim_strncpy(prefix + depth, word, MAXWLEN - depth - 1); dump_word(slang, prefix, pat, dir, dumpflags, (c & WF_RAREPFX) ? (flags | WF_RARE) : flags, lnum); if (lnum != 0) ++lnum; } /* Check for prefix that matches the word when the * first letter is upper-case, but only if the prefix has * a condition. */ if (has_word_up) { c = valid_word_prefix(i, n, flags, word_up, slang, TRUE); if (c != 0) { vim_strncpy(prefix + depth, word_up, MAXWLEN - depth - 1); dump_word(slang, prefix, pat, dir, dumpflags, (c & WF_RAREPFX) ? (flags | WF_RARE) : flags, lnum); if (lnum != 0) ++lnum; } } } else { /* Normal char, go one level deeper. */ prefix[depth++] = c; arridx[depth] = idxs[n]; curi[depth] = 1; } } } } return lnum; } /* * Move "p" to the end of word "start". * Uses the spell-checking word characters. */ char_u * spell_to_word_end(start, win) char_u *start; win_T *win; { char_u *p = start; while (*p != NUL && spell_iswordp(p, win)) mb_ptr_adv(p); return p; } #if defined(FEAT_INS_EXPAND) || defined(PROTO) /* * For Insert mode completion CTRL-X s: * Find start of the word in front of column "startcol". * We don't check if it is badly spelled, with completion we can only change * the word in front of the cursor. * Returns the column number of the word. */ int spell_word_start(startcol) int startcol; { char_u *line; char_u *p; int col = 0; if (no_spell_checking(curwin)) return startcol; /* Find a word character before "startcol". */ line = ml_get_curline(); for (p = line + startcol; p > line; ) { mb_ptr_back(line, p); if (spell_iswordp_nmw(p)) break; } /* Go back to start of the word. */ while (p > line) { col = (int)(p - line); mb_ptr_back(line, p); if (!spell_iswordp(p, curwin)) break; col = 0; } return col; } /* * Need to check for 'spellcapcheck' now, the word is removed before * expand_spelling() is called. Therefore the ugly global variable. */ static int spell_expand_need_cap; void spell_expand_check_cap(col) colnr_T col; { spell_expand_need_cap = check_need_cap(curwin->w_cursor.lnum, col); } /* * Get list of spelling suggestions. * Used for Insert mode completion CTRL-X ?. * Returns the number of matches. The matches are in "matchp[]", array of * allocated strings. */ int expand_spelling(lnum, pat, matchp) linenr_T lnum UNUSED; char_u *pat; char_u ***matchp; { garray_T ga; spell_suggest_list(&ga, pat, 100, spell_expand_need_cap, TRUE); *matchp = ga.ga_data; return ga.ga_len; } #endif #endif /* FEAT_SPELL */
zyz2011-vim
src/spell.c
C
gpl2
423,040
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. */ /* * Farsi characters are categorized into following types: * * TyA (for capital letter representation) * TyB (for types that look like _X e.g. AYN) * TyC (for types that look like X_ e.g. YE_) * TyD (for types that look like _X_ e.g. _AYN_) * TyE (for types that look like X e.g. RE) */ /* * Farsi character set definition */ /* * Begin of the non-standard part */ #define TEE_ 0x80 #define ALEF_U_H_ 0x81 #define ALEF_ 0x82 #define _BE 0x83 #define _PE 0x84 #define _TE 0x85 #define _SE 0x86 #define _JIM 0x87 #define _CHE 0x88 #define _HE_J 0x89 #define _XE 0x8a #define _SIN 0x8b #define _SHIN 0x8c #define _SAD 0x8d #define _ZAD 0x8e #define _AYN 0x8f #define _AYN_ 0x90 #define AYN_ 0x91 #define _GHAYN 0x92 #define _GHAYN_ 0x93 #define GHAYN_ 0x94 #define _FE 0x95 #define _GHAF 0x96 #define _KAF 0x97 #define _GAF 0x98 #define _LAM 0x99 #define LA 0x9a #define _MIM 0x9b #define _NOON 0x9c #define _HE 0x9d #define _HE_ 0x9e #define _YE 0x9f #define _IE 0xec #define IE_ 0xed #define IE 0xfb #define _YEE 0xee #define YEE_ 0xef #define YE_ 0xff /* * End of the non-standard part */ /* * Standard part */ #define F_BLANK 0xa0 /* Farsi ' ' (SP) character */ #define F_PSP 0xa1 /* PSP for capitalizing of a character */ #define F_PCN 0xa2 /* PCN for redefining of the hamye meaning */ #define F_EXCL 0xa3 /* Farsi ! character */ #define F_CURRENCY 0xa4 /* Farsi Rial character */ #define F_PERCENT 0xa5 /* Farsi % character */ #define F_PERIOD 0xa6 /* Farsi '.' character */ #define F_COMMA 0xa7 /* Farsi ',' character */ #define F_LPARENT 0xa8 /* Farsi '(' character */ #define F_RPARENT 0xa9 /* Farsi ')' character */ #define F_MUL 0xaa /* Farsi 'x' character */ #define F_PLUS 0xab /* Farsi '+' character */ #define F_BCOMMA 0xac /* Farsi comma character */ #define F_MINUS 0xad /* Farsi '-' character */ #define F_DIVIDE 0xae /* Farsi divide (/) character */ #define F_SLASH 0xaf /* Farsi '/' character */ #define FARSI_0 0xb0 #define FARSI_1 0xb1 #define FARSI_2 0xb2 #define FARSI_3 0xb3 #define FARSI_4 0xb4 #define FARSI_5 0xb5 #define FARSI_6 0xb6 #define FARSI_7 0xb7 #define FARSI_8 0xb8 #define FARSI_9 0xb9 #define F_DCOLON 0xba /* Farsi ':' character */ #define F_SEMICOLON 0xbb /* Farsi ';' character */ #define F_GREATER 0xbc /* Farsi '>' character */ #define F_EQUALS 0xbd /* Farsi '=' character */ #define F_LESS 0xbe /* Farsi '<' character */ #define F_QUESTION 0xbf /* Farsi ? character */ #define ALEF_A 0xc0 #define ALEF 0xc1 #define HAMZE 0xc2 #define BE 0xc3 #define PE 0xc4 #define TE 0xc5 #define SE 0xc6 #define JIM 0xc7 #define CHE 0xc8 #define HE_J 0xc9 #define XE 0xca #define DAL 0xcb #define ZAL 0xcc #define RE 0xcd #define ZE 0xce #define JE 0xcf #define SIN 0xd0 #define SHIN 0xd1 #define SAD 0xd2 #define ZAD 0xd3 #define _TA 0xd4 #define _ZA 0xd5 #define AYN 0xd6 #define GHAYN 0xd7 #define FE 0xd8 #define GHAF 0xd9 #define KAF 0xda #define GAF 0xdb #define LAM 0xdc #define MIM 0xdd #define NOON 0xde #define WAW 0xdf #define F_HE 0xe0 /* F_ added for name clash with Perl */ #define YE 0xe1 #define TEE 0xfc #define _KAF_H 0xfd #define YEE 0xfe #define F_LBRACK 0xe2 /* Farsi '[' character */ #define F_RBRACK 0xe3 /* Farsi ']' character */ #define F_LBRACE 0xe4 /* Farsi '{' character */ #define F_RBRACE 0xe5 /* Farsi '}' character */ #define F_LQUOT 0xe6 /* Farsi left quotation character */ #define F_RQUOT 0xe7 /* Farsi right quotation character */ #define F_STAR 0xe8 /* Farsi '*' character */ #define F_UNDERLINE 0xe9 /* Farsi '_' character */ #define F_PIPE 0xea /* Farsi '|' character */ #define F_BSLASH 0xeb /* Farsi '\' character */ #define MAD 0xf0 #define JAZR 0xf1 #define OW 0xf2 #define MAD_N 0xf3 #define JAZR_N 0xf4 #define OW_OW 0xf5 #define TASH 0xf6 #define OO 0xf7 #define ALEF_U_H 0xf8 #define WAW_H 0xf9 #define ALEF_D_H 0xfa /* * global definitions * ================== */ #define SRC_EDT 0 #define SRC_CMD 1 #define AT_CURSOR 0 /* * definitions for the window dependent functions (w_farsi). */ #define W_CONV 0x1 #define W_R_L 0x2 /* special Farsi text messages */ EXTERN char_u farsi_text_1[] #ifdef DO_INIT = { YE_, _SIN, RE, ALEF_, _FE, ' ', 'V', 'I', 'M', ' ', F_HE, _BE, ' ', SHIN, RE, _GAF, DAL,' ', NOON, ALEF_, _YE, ALEF_, _PE, '\0'} #endif ; EXTERN char_u farsi_text_2[] #ifdef DO_INIT = { YE_, _SIN, RE, ALEF_, _FE, ' ', FARSI_3, FARSI_3, FARSI_4, FARSI_2, ' ', DAL, RE, ALEF, DAL, _NOON, ALEF_, _TE, _SIN, ALEF, ' ', F_HE, _BE, ' ', SHIN, RE, _GAF, DAL, ' ', NOON, ALEF_, _YE, ALEF_, _PE, '\0'} #endif ; EXTERN char_u farsi_text_3[] #ifdef DO_INIT = { DAL, WAW, _SHIN, _YE, _MIM, _NOON, ' ', YE_, _NOON, ALEF_,_BE, _YE, _TE, _SHIN, _PE, ' ', 'R','E','P','L', 'A','C','E', ' ', NOON, ALEF_, _MIM, RE, _FE, ZE, ALEF, ' ', 'R', 'E', 'V', 'E', 'R', 'S', 'E', ' ', 'I', 'N', 'S', 'E', 'R', 'T', ' ', SHIN, WAW, RE, ' ', ALEF_, _BE, ' ', YE_, _SIN, RE, ALEF_, _FE, ' ', RE, DAL, ' ', RE, ALEF_, _KAF,' ', MIM, ALEF_, _GAF, _NOON, _HE, '\0'} #endif ; #if 0 /* not used */ EXTERN char_u farsi_text_4[] #ifdef DO_INIT = { DAL, WAW, _SHIN, _YE, _MIM, _NOON, ' ', YE_, _NOON, ALEF_, _BE, _YE, _TE, _SHIN, _PE, ' ', '<', 'C','T','R', 'L','-','B','>', ' ', NOON, ALEF_, _MIM, RE, _FE, ZE, ALEF, ' ', YE_, _SIN, RE, ALEF_, _FE, ' ', RE, DAL, ' ', RE, ALEF_, _KAF,' ', MIM, ALEF_, _GAF, _NOON, _HE, '\0'} #endif ; #endif EXTERN char_u farsi_text_5[] #ifdef DO_INIT = { ' ', YE_, _SIN, RE, ALEF_, _FE, '\0'} #endif ;
zyz2011-vim
src/farsi.h
C
gpl2
5,850
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * os_msdos.c * * MSDOS system-dependent routines. * A cheap plastic imitation of the amiga dependent code. * A lot in this file was made by Juergen Weigert (jw). * * DJGPP changes by Gert van Antwerpen * Faster text screens by John Lange (jlange@zilker.net) * Windows clipboard functionality added by David Kotchan (dk) * * Some functions are also used for Win16 (MS-Windows 3.1). */ #include "vim.h" #include <conio.h> /* * MS-DOS only code, not used for Win16. */ #ifndef WIN16 #include <bios.h> #ifdef DJGPP # include <dpmi.h> # include <signal.h> # include <sys/movedata.h> # include <crt0.h> # ifdef FEAT_CLIPBOARD # include <sys/segments.h> # endif #else # include <alloc.h> #endif #if defined(DJGPP) || defined(PROTO) # define _cdecl /* DJGPP doesn't have this */ #endif static int cbrk_pressed = FALSE; /* set by ctrl-break interrupt */ static int ctrlc_pressed = FALSE; /* set when ctrl-C or ctrl-break detected */ static int delayed_redraw = FALSE; /* set when ctrl-C detected */ static int bioskey_read = _NKEYBRD_READ; /* bioskey() argument: read key */ static int bioskey_ready = _NKEYBRD_READY; /* bioskey() argument: key ready? */ #ifdef FEAT_MOUSE static int mouse_avail = FALSE; /* mouse present */ static int mouse_active; /* mouse enabled */ static int mouse_hidden; /* mouse not shown */ static int mouse_click = -1; /* mouse status */ static int mouse_last_click = -1; /* previous status at click */ static int mouse_x = -1; /* mouse x coordinate */ static int mouse_y = -1; /* mouse y coordinate */ static long mouse_click_time = 0; /* biostime() of last click */ static int mouse_click_count = 0; /* count for multi-clicks */ static int mouse_click_x = 0; /* x of previous mouse click */ static int mouse_click_y = 0; /* y of previous mouse click */ static linenr_T mouse_topline = 0; /* w_topline at previous mouse click */ #ifdef FEAT_DIFF static int mouse_topfill = 0; /* w_topfill at previous mouse click */ #endif static int mouse_x_div = 8; /* column = x coord / mouse_x_div */ static int mouse_y_div = 8; /* line = y coord / mouse_y_div */ #endif #define BIOSTICK 55 /* biostime() increases one tick about every 55 msec */ static int orig_attr = 0x0700; /* video attributes when starting */ static int S_iLeft = 0; /* Scroll window; these are 1 offset */ static int S_iTop = 0; static int S_iRight = 0; static int S_iBottom = 0; /* * Need to remember the values, because we set horizontal and vertical * edges separately. */ static void mywindow(int iLeft, int iTop, int iRight, int iBottom) { S_iLeft = iLeft; S_iTop = iTop; S_iRight = iRight; S_iBottom = iBottom; window(iLeft, iTop, iRight, iBottom); } #ifdef DJGPP /* * For DJGPP, use our own functions for fast text screens. JML 1/18/98 */ unsigned long S_ulScreenBase = 0xb8000; unsigned short S_uiAttribute = 0; int S_iCurrentRow = 0; /* These are 0 offset */ int S_iCurrentColumn = 0; short S_selVideo; /* Selector for DJGPP direct video transfers */ /* * Use burst writes to improve mch_write speed - VJN 01/10/99 */ unsigned short S_linebuffer[8000]; /* <VN> enough for 160x50 */ unsigned short S_blankbuffer[256]; /* <VN> max length of console line */ unsigned short *S_linebufferpos = S_linebuffer; int S_iBufferRow; int S_iBufferColumn; static void myflush(void) { if (S_linebufferpos != S_linebuffer) { _dosmemputw(S_linebuffer, (S_linebufferpos - S_linebuffer), S_ulScreenBase + S_iBufferRow * (Columns << 1) + (S_iBufferColumn << 1)); S_linebufferpos = S_linebuffer; } } static void mygotoxy(int x, int y) { S_iCurrentRow = y - 1; S_iCurrentColumn = x - 1; } /* * Set the system cursor to our cursor position. */ static void set_sys_cursor(void) { if (term_console && full_screen) { myflush(); gotoxy(S_iCurrentColumn + 1, S_iCurrentRow + 1); } } static void setblankbuffer(unsigned short uiValue) { int i; static unsigned short olduiValue = 0; if (olduiValue != uiValue) { /* Load blank line buffer with spaces */ for (i = 0; i < Columns; ++i) S_blankbuffer[i] = uiValue; olduiValue = uiValue; } } static void myclreol(void) { /* Clear to end of line */ setblankbuffer(S_uiAttribute | ' '); _dosmemputw(S_blankbuffer, S_iRight - S_iCurrentColumn, S_ulScreenBase + (S_iCurrentRow) * (Columns << 1) + (S_iCurrentColumn << 1)); } static void myclrscr(void) { /* Clear whole screen */ short iColumn; int endpoint = (Rows * Columns) << 1; setblankbuffer(S_uiAttribute | ' '); for (iColumn = 0; iColumn < endpoint; iColumn += (Columns << 1)) _dosmemputw(S_blankbuffer, Columns, S_ulScreenBase + iColumn); } static void mydelline(void) { short iRow, iColumn; iColumn = (S_iLeft - 1) << 1; /* Copy the lines underneath */ for (iRow = S_iCurrentRow; iRow < S_iBottom - 1; iRow++) movedata(S_selVideo, (((iRow + 1) * Columns) << 1) + iColumn, S_selVideo, ((iRow * Columns) << 1) + iColumn, (S_iRight - S_iLeft + 1) << 1); /* Clear the new row */ setblankbuffer(S_uiAttribute | ' '); _dosmemputw(S_blankbuffer, (S_iRight - S_iLeft) + 1, S_ulScreenBase + (S_iBottom - 1) * (Columns << 1) + iColumn); } static void myinsline(void) { short iRow, iColumn; iColumn = (S_iLeft - 1) << 1; /* Copy the lines underneath */ for (iRow = S_iBottom - 1; iRow >= S_iTop; iRow--) movedata(S_selVideo, (((iRow - 1) * Columns) << 1) + iColumn, S_selVideo, ((iRow * Columns) << 1) + iColumn, (S_iRight - S_iLeft + 1) << 1); /* Clear the new row */ setblankbuffer(S_uiAttribute | ' '); _dosmemputw(S_blankbuffer, (S_iRight - S_iLeft) + 1, S_ulScreenBase + (S_iTop - 1) * (Columns << 1) + iColumn); } /* * Scroll the screen one line up, clear the last line. */ static void myscroll(void) { short iRow, iColumn; iColumn = (S_iLeft - 1) << 1; /* Copy the screen */ for (iRow = S_iTop; iRow < S_iBottom; iRow++) movedata(S_selVideo, ((iRow * Columns) << 1) + iColumn, S_selVideo, (((iRow - 1) * Columns) << 1) + iColumn, (S_iRight - S_iLeft + 1) << 1); /* Clear the bottom row */ setblankbuffer(S_uiAttribute | ' '); _dosmemputw(S_blankbuffer, (S_iRight - S_iLeft) + 1, S_ulScreenBase + (S_iBottom - 1) * (Columns << 1) + iColumn); } static int myputch(int iChar) { unsigned short uiValue; if (iChar == '\n') { myflush(); if (S_iCurrentRow >= S_iBottom - S_iTop) myscroll(); else { S_iCurrentColumn = S_iLeft - 1; S_iCurrentRow++; } } else if (iChar == '\r') { myflush(); S_iCurrentColumn = S_iLeft - 1; } else if (iChar == '\b') { myflush(); if (S_iCurrentColumn >= S_iLeft) S_iCurrentColumn--; } else if (iChar == 7) { sound(440); /* short beep */ delay(200); nosound(); } else { uiValue = S_uiAttribute | (unsigned char)iChar; /* * Normal char - are we starting to buffer? */ if (S_linebufferpos == S_linebuffer) { S_iBufferColumn = S_iCurrentColumn; S_iBufferRow = S_iCurrentRow; } *S_linebufferpos++ = uiValue; S_iCurrentColumn++; if (S_iCurrentColumn >= S_iRight && S_iCurrentRow >= S_iBottom - S_iTop) { myflush(); myscroll(); S_iCurrentColumn = S_iLeft - 1; S_iCurrentRow++; } } return 0; } static void mytextinit(struct text_info *pTextinfo) { S_selVideo = __dpmi_segment_to_descriptor(S_ulScreenBase >> 4); S_uiAttribute = pTextinfo->normattr << 8; } static void get_screenbase(void) { static union REGS regs; /* old Hercules grafic card has different base address (Macewicz) */ regs.h.ah = 0x0f; (void)int86(0x10, &regs, &regs); /* int 10 0f */ if (regs.h.al == 0x07) /* video mode 7 -- hercules mono */ S_ulScreenBase = 0xb0000; else S_ulScreenBase = 0xb8000; } static void mytextattr(int iAttribute) { S_uiAttribute = (unsigned short)iAttribute << 8; } static void mynormvideo(void) { mytextattr(orig_attr); } static void mytextcolor(int iTextColor) { S_uiAttribute = (unsigned short)((S_uiAttribute & 0xf000) | (unsigned short)iTextColor << 8); } static void mytextbackground(int iBkgColor) { S_uiAttribute = (unsigned short)((S_uiAttribute & 0x0f00) | (unsigned short)(iBkgColor << 12)); } /* * Getdigits: Get a number from a string and skip over it. * Note: the argument is a pointer to a char_u pointer! */ static long mygetdigits(pp) char_u **pp; { char_u *p; long retval = 0; p = *pp; if (*p == '-') /* skip negative sign */ ++p; while (VIM_ISDIGIT(*p)) { retval = (retval * 10) + (*p - '0'); ++p; } if (**pp == '-') /* process negative sign */ retval = -retval; *pp = p; return retval; } #else # define mygotoxy gotoxy # define myputch putch # define myscroll scroll # define mynormvideo normvideo # define mytextattr textattr # define mytextcolor textcolor # define mytextbackground textbackground # define mygetdigits getdigits # define myclreol clreol # define myclrscr clrscr # define myinsline insline # define mydelline delline #endif static const struct { char_u scancode; char_u metakey; } altkey_table[] = { {0x1e, 0xe1}, /* a */ {0x30, 0xe2}, /* b */ {0x2e, 0xe3}, /* c */ {0x20, 0xe4}, /* d */ {0x12, 0xe5}, /* e */ {0x21, 0xe6}, /* f */ {0x22, 0xe7}, /* g */ {0x23, 0xe8}, /* h */ {0x17, 0xe9}, /* i */ {0x24, 0xea}, /* j */ {0x25, 0xeb}, /* k */ {0x26, 0xec}, /* l */ {0x32, 0xed}, /* m */ {0x31, 0xee}, /* n */ {0x18, 0xef}, /* o */ {0x19, 0xf0}, /* p */ {0x10, 0xf1}, /* q */ {0x13, 0xf2}, /* r */ {0x1f, 0xf3}, /* s */ {0x14, 0xf4}, /* t */ {0x16, 0xf5}, /* u */ {0x2f, 0xf6}, /* v */ {0x11, 0xf7}, /* w */ {0x2d, 0xf8}, /* x */ {0x15, 0xf9}, /* y */ {0x2c, 0xfa}, /* z */ {0x78, 0xb1}, /* 1 */ {0x79, 0xb2}, /* 2 */ {0x7a, 0xb3}, /* 3 */ {0x7b, 0xb4}, /* 4 */ {0x7c, 0xb5}, /* 5 */ {0x7d, 0xb6}, /* 6 */ {0x7e, 0xb7}, /* 7 */ {0x7f, 0xb8}, /* 8 */ {0x80, 0xb9}, /* 9 */ {0x81, 0xb0}, /* 0 */ }; /* * Translate extended keycodes into meta-chars where applicable */ static int translate_altkeys(int rawkey) { int i, c; if ((rawkey & 0xff) == 0) { c = (rawkey >> 8); for (i = sizeof(altkey_table) / sizeof(altkey_table[0]); --i >= 0; ) { if (c == altkey_table[i].scancode) return (int)altkey_table[i].metakey; } } return rawkey; } /* * Set normal fg/bg color, based on T_ME. Called when t_me has been set. */ void mch_set_normal_colors() { char_u *p; int n; cterm_normal_fg_color = (orig_attr & 0xf) + 1; cterm_normal_bg_color = ((orig_attr >> 4) & 0xf) + 1; if (T_ME[0] == ESC && T_ME[1] == '|') { p = T_ME + 2; n = getdigits(&p); if (*p == 'm' && n > 0) { cterm_normal_fg_color = (n & 0xf) + 1; cterm_normal_bg_color = ((n >> 4) & 0xf) + 1; } } } #if defined(MCH_CURSOR_SHAPE) || defined(PROTO) /* * Save/restore the shape of the cursor. * call with FALSE to save, TRUE to restore */ static void mch_restore_cursor_shape(int restore) { static union REGS regs; static int saved = FALSE; if (restore) { if (saved) regs.h.ah = 0x01; /* Set Cursor */ else return; } else { regs.h.ah = 0x03; /* Get Cursor */ regs.h.bh = 0x00; /* Page */ saved = TRUE; } (void)int86(0x10, &regs, &regs); } /* * Set the shape of the cursor. * 'thickness' can be from 0 (thin) to 7 (block) */ static void mch_set_cursor_shape(int thickness) { union REGS regs; regs.h.ch = 7 - thickness; /* Starting Line */ regs.h.cl = 7; /* Ending Line */ regs.h.ah = 0x01; /* Set Cursor */ (void)int86(0x10, &regs, &regs); } void mch_update_cursor(void) { int idx; int thickness; /* * How the cursor is drawn depends on the current mode. */ idx = get_shape_idx(FALSE); if (shape_table[idx].shape == SHAPE_BLOCK) thickness = 7; else thickness = (7 * shape_table[idx].percentage + 90) / 100; mch_set_cursor_shape(thickness); } #endif /* * Return amount of memory currently available. */ long_u mch_avail_mem(int special) { #ifdef DJGPP return _go32_dpmi_remaining_virtual_memory(); #else return coreleft(); #endif } #ifdef FEAT_MOUSE /* * Set area where mouse can be moved to: The whole screen. * Rows and Columns must be valid when calling! */ static void mouse_area(void) { union REGS regs; if (mouse_avail) { regs.x.cx = 0; /* mouse visible between cx and dx */ regs.x.dx = Columns * mouse_x_div - 1; regs.x.ax = 7; (void)int86(0x33, &regs, &regs); regs.x.cx = 0; /* mouse visible between cx and dx */ regs.x.dx = Rows * mouse_y_div - 1; regs.x.ax = 8; (void)int86(0x33, &regs, &regs); } } static void show_mouse(int on) { static int was_on = FALSE; union REGS regs; if (mouse_avail) { if (!mouse_active || mouse_hidden) on = FALSE; /* * Careful: Each switch on must be compensated by exactly one switch * off */ if ((on && !was_on) || (!on && was_on)) { was_on = on; regs.x.ax = on ? 1 : 2; int86(0x33, &regs, &regs); /* show mouse */ if (on) mouse_area(); } } } #endif /* * Version of kbhit() and getch() that use direct console I/O. * This avoids trouble with CTRL-P and the like, and should work over a telnet * connection (it works for Xvi). */ static int cons_key = -1; /* * Try to get one character directly from the console. * If there is a key, it is stored in cons_key. * Only call when cons_key is -1! */ static void cons_getkey(void) { union REGS regs; /* call DOS function 6: Direct console I/O */ regs.h.ah = 0x06; regs.h.dl = 0xff; (void)intdos(&regs, &regs); if ((regs.x.flags & 0x40) == 0) /* zero flag not set? */ cons_key = (regs.h.al & 0xff); } /* * Return TRUE if a character is available. */ static int cons_kbhit(void) { if (cons_key < 0) cons_getkey(); return (cons_key >= 0); } /* * Return a character from the console. * Should only be called when vim_kbhit() returns TRUE. */ static int cons_getch(void) { int c = -1; if (cons_key < 0) cons_getkey(); c = cons_key; cons_key = -1; return c; } #ifdef DJGPP /* * DJGPP provides a kbhit() function that goes to the BIOS instead of DOS. * This doesn't work for terminals connected to a serial port. * Redefine kbhit() here to make it work. */ static int vim_kbhit(void) { union REGS regs; regs.h.ah = 0x0b; (void)intdos(&regs, &regs); return regs.h.al; } #ifdef kbhit # undef kbhit /* might have been defined in conio.h */ #endif #define kbhit() vim_kbhit() #endif /* * Simulate WaitForChar() by slowly polling with bioskey(1) or kbhit(). * * If Vim should work over the serial line after a 'ctty com1' we must use * kbhit() and getch(). (jw) * Usually kbhit() is not used, because then CTRL-C and CTRL-P * will be catched by DOS (mool). * * return TRUE if a character is available, FALSE otherwise */ #define FOREVER 1999999999L static int WaitForChar(long msec) { long starttime = 0; if (msec != 0) starttime = biostime(0, 0L); for (;;) { #ifdef FEAT_MOUSE long clicktime; static int old_status = 0; union REGS regs; int x, y; if (mouse_avail && mouse_active && mouse_click < 0) { regs.x.ax = 3; int86(0x33, &regs, &regs); /* check mouse status */ /* only recognize button-down and button-up event */ x = regs.x.cx / mouse_x_div; y = regs.x.dx / mouse_y_div; if ((old_status == 0) != (regs.x.bx == 0)) { if (old_status) /* button up */ mouse_click = MOUSE_RELEASE; else /* button down */ { /* * Translate MSDOS mouse events to Vim mouse events. * TODO: should handle middle mouse button, by pressing * left and right at the same time. */ if (regs.x.bx & MSDOS_MOUSE_LEFT) mouse_click = MOUSE_LEFT; else if (regs.x.bx & MSDOS_MOUSE_RIGHT) mouse_click = MOUSE_RIGHT; else if (regs.x.bx & MSDOS_MOUSE_MIDDLE) mouse_click = MOUSE_MIDDLE; /* * Find out if this is a multi-click */ clicktime = biostime(0, 0L); if (mouse_click_x == x && mouse_click_y == y && mouse_topline == curwin->w_topline #ifdef FEAT_DIFF && mouse_topfill == curwin->w_topfill #endif && mouse_click_count != 4 && mouse_click == mouse_last_click && clicktime < mouse_click_time + p_mouset / BIOSTICK) ++mouse_click_count; else mouse_click_count = 1; mouse_click_time = clicktime; mouse_last_click = mouse_click; mouse_click_x = x; mouse_click_y = y; mouse_topline = curwin->w_topline; #ifdef FEAT_DIFF mouse_topfill = curwin->w_topfill; #endif SET_NUM_MOUSE_CLICKS(mouse_click, mouse_click_count); } } else if (old_status && (x != mouse_x || y != mouse_y)) mouse_click = MOUSE_DRAG; old_status = regs.x.bx; if (mouse_hidden && mouse_x >= 0 && (mouse_x != x || mouse_y != y)) { mouse_hidden = FALSE; show_mouse(TRUE); } mouse_x = x; mouse_y = y; } #endif if ((p_consk ? cons_kbhit() : p_biosk ? bioskey(bioskey_ready) : kbhit()) || cbrk_pressed #ifdef FEAT_MOUSE || mouse_click >= 0 #endif ) return TRUE; /* * Use biostime() to wait until our time is done. * We busy-wait here. Unfortunately, delay() and usleep() have been * reported to give problems with the original Windows 95. This is * fixed in service pack 1, but not everybody installed that. * The DJGPP implementation of usleep() uses a busy-wait loop too. */ if (msec == 0 || (msec != FOREVER && biostime(0, 0L) > starttime + msec / BIOSTICK)) break; #ifdef DJGPP /* Yield the CPU to the next process. */ __dpmi_yield(); #endif } return FALSE; } /* * don't do anything for about "msec" msec */ void mch_delay( long msec, int ignoreinput) { long starttime; if (ignoreinput) { /* * We busy-wait here. Unfortunately, delay() and usleep() have been * reported to give problems with the original Windows 95. This is * fixed in service pack 1, but not everybody installed that. */ starttime = biostime(0, 0L); while (biostime(0, 0L) < starttime + msec / BIOSTICK) ; } else WaitForChar(msec); } /* * mch_write(): write the output buffer to the screen */ void mch_write( char_u *s, int len) { char_u *p; int row, col; if (term_console && full_screen) while (len--) { /* translate ESC | sequences into bios calls */ if (p_wd) /* testing: wait a bit for each char */ WaitForChar(p_wd); if (s[0] == '\n') #ifdef DJGPP { myflush(); S_iCurrentColumn = S_iLeft - 1; } #else myputch('\r'); #endif else if (s[0] == ESC && len > 1 && s[1] == '|') { switch (s[2]) { #ifdef DJGPP case 'B': ScreenVisualBell(); goto got3; #endif case 'J': #ifdef DJGPP myflush(); #endif myclrscr(); goto got3; case 'K': #ifdef DJGPP myflush(); #endif myclreol(); goto got3; case 'L': #ifdef DJGPP myflush(); #endif myinsline(); goto got3; case 'M': #ifdef DJGPP myflush(); #endif mydelline(); got3: s += 3; len -= 2; continue; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': p = s + 2; row = mygetdigits(&p); /* no check for length! */ if (p > s + len) break; if (*p == ';') { ++p; col = mygetdigits(&p); /* no check for length! */ if (p > s + len) break; if (*p == 'H' || *p == 'r' || *p == 'V') { #ifdef DJGPP myflush(); #endif if (*p == 'H') /* set cursor position */ mygotoxy(col, row); else if (*p == 'V') mywindow(row, S_iTop, col, S_iBottom); else /* set scroll region */ mywindow(S_iLeft, row, S_iRight, col); len -= p - s; s = p + 1; continue; } } else if (*p == 'm' || *p == 'f' || *p == 'b') { if (*p == 'm') /* set color */ { if (row == 0) mynormvideo();/* reset color */ else mytextattr(row); } else if (*p == 'f') /* set foreground color */ mytextcolor(row); else /* set background color */ mytextbackground(row); len -= p - s; s = p + 1; continue; } } } myputch(*s++); } else { write(1, s, (unsigned)len); } } /* * mch_inchar(): low level input funcion. * Get a characters from the keyboard. * If time == 0 do not wait for characters. * If time == n wait a short time for characters. * If time == -1 wait forever for characters. * * return the number of characters obtained */ int mch_inchar( char_u *buf, int maxlen, long time, int tb_change_cnt) { int len = 0; int c; int tmp_c; static int nextchar = 0; /* may keep character when maxlen == 1 */ /* * if we got a ctrl-C when we were busy, there will be a "^C" somewhere * on the sceen, so we need to redisplay it. */ if (delayed_redraw) { delayed_redraw = FALSE; update_screen(CLEAR); setcursor(); out_flush(); } /* return remaining character from last call */ if (nextchar) { *buf = nextchar; nextchar = 0; return 1; } #ifdef FEAT_MOUSE if (time != 0) show_mouse(TRUE); #endif #ifdef DJGPP set_sys_cursor(); #endif if (time >= 0) { if (WaitForChar(time) == 0) /* no character available */ { #ifdef FEAT_MOUSE show_mouse(FALSE); #endif return 0; } } else /* time == -1 */ { /* * If there is no character available within 2 seconds (default) * write the autoscript file to disk. Or cause the CursorHold event * to be triggered. */ if (WaitForChar(p_ut) == 0) { #ifdef FEAT_AUTOCMD if (trigger_cursorhold() && maxlen >= 3) { buf[0] = K_SPECIAL; buf[1] = KS_EXTRA; buf[2] = (int)KE_CURSORHOLD; return 3; } #endif before_blocking(); } } WaitForChar(FOREVER); /* wait for key or mouse click */ /* * Try to read as many characters as there are, until the buffer is full. */ /* * we will get at least one key. Get more if they are available * After a ctrl-break we have to read a 0 (!) from the buffer. * bioskey(1) will return 0 if no key is available and when a * ctrl-break was typed. When ctrl-break is hit, this does not always * implies a key hit. */ cbrk_pressed = FALSE; #ifdef FEAT_MOUSE if (mouse_click >= 0 && maxlen >= 5) { len = 5; *buf++ = ESC + 128; *buf++ = 'M'; *buf++ = mouse_click; *buf++ = mouse_x + '!'; *buf++ = mouse_y + '!'; mouse_click = -1; } else #endif { #ifdef FEAT_MOUSE mouse_hidden = TRUE; #endif if (p_biosk && !p_consk) { while ((len == 0 || bioskey(bioskey_ready)) && len < maxlen) { c = translate_altkeys(bioskey(bioskey_read)); /* get the key */ /* * translate a few things for inchar(): * 0x0000 == CTRL-break -> 3 (CTRL-C) * 0x0300 == CTRL-@ -> NUL * 0xnn00 == extended key code -> K_NUL, nn * 0xnne0 == enhanced keyboard -> K_NUL, nn * K_NUL -> K_NUL, 3 */ if (c == 0) c = 3; else if (c == 0x0300) c = NUL; else if ((c & 0xff) == 0 || c == K_NUL || c == 0x4e2b || c == 0x4a2d || c == 0x372a || ((c & 0xff) == 0xe0 && c != 0xe0)) { if (c == K_NUL) c = 3; else c >>= 8; *buf++ = K_NUL; ++len; } if (len < maxlen) { *buf++ = c; len++; #ifdef FEAT_MBYTE /* Convert from 'termencoding' to 'encoding'. Only * translate normal characters, not key codes. */ if (input_conv.vc_type != CONV_NONE && (len == 1 || buf[-2] != K_NUL)) len += convert_input(buf - 1, 1, maxlen - len + 1) - 1; #endif } else nextchar = c; } } else { while ((len == 0 || (p_consk ? cons_kbhit() : kbhit())) && len < maxlen) { switch (c = (p_consk ? cons_getch() : getch())) { case 0: /* NUL means that there is another character. * Get it immediately, because kbhit() doesn't always * return TRUE for the second character. */ if (p_consk) c = cons_getch(); else c = getch(); tmp_c = translate_altkeys(c << 8); if (tmp_c == (c << 8)) { *buf++ = K_NUL; ++len; } else c = tmp_c; break; case K_NUL: *buf++ = K_NUL; ++len; c = 3; break; case 3: cbrk_pressed = TRUE; /*FALLTHROUGH*/ default: break; } if (len < maxlen) { *buf++ = c; ++len; } else nextchar = c; } } } #ifdef FEAT_MOUSE show_mouse(FALSE); #endif beep_count = 0; /* may beep again now that we got some chars */ return len; } /* * return non-zero if a character is available */ int mch_char_avail(void) { return WaitForChar(0L); } #ifdef DJGPP # define INT_ARG int #else # define INT_ARG #endif /* * function for ctrl-break interrupt */ static void interrupt #ifdef DJGPP catch_cbrk(int a) #else catch_cbrk(void) #endif { cbrk_pressed = TRUE; ctrlc_pressed = TRUE; } #ifndef DJGPP /* * ctrl-break handler for DOS. Never called when a ctrl-break is typed, because * we catch interrupt 1b. If you type ctrl-C while Vim is waiting for a * character this function is not called. When a ctrl-C is typed while Vim is * busy this function may be called. By that time a ^C has been displayed on * the screen, so we have to redisplay the screen. We can't do that here, * because we may be called by DOS. The redraw is in mch_inchar(). */ static int _cdecl cbrk_handler(void) { delayed_redraw = TRUE; return 1; /* resume operation after ctrl-break */ } /* * function for critical error interrupt * For DOS 1 and 2 return 0 (Ignore). * For DOS 3 and later return 3 (Fail) */ static void interrupt catch_cint(bp, di, si, ds, es, dx, cx, bx, ax) unsigned bp, di, si, ds, es, dx, cx, bx, ax; { ax = (ax & 0xff00); /* set AL to 0 */ if (_osmajor >= 3) ax |= 3; /* set AL to 3 */ } #endif /* * Set the interrupt vectors for use with Vim on or off. * on == TRUE means as used within Vim */ static void set_interrupts(int on) { static int saved_cbrk; #ifndef DJGPP static void interrupt (*old_cint)(); #endif static void interrupt (*old_cbrk)(INT_ARG); if (on) { saved_cbrk = getcbrk(); /* save old ctrl-break setting */ setcbrk(0); /* do not check for ctrl-break */ #ifdef DJGPP old_cbrk = signal(SIGINT, catch_cbrk); /* critical error interrupt */ #else old_cint = getvect(0x24); /* save old critical error interrupt */ setvect(0x24, catch_cint); /* install our critical error interrupt */ old_cbrk = getvect(0x1B); /* save old ctrl-break interrupt */ setvect(0x1B, catch_cbrk); /* install our ctrl-break interrupt */ ctrlbrk(cbrk_handler); /* vim's ctrl-break handler */ #endif if (term_console) out_str(T_ME); /* set colors */ } else { setcbrk(saved_cbrk); /* restore ctrl-break setting */ #ifdef DJGPP signal(SIGINT,old_cbrk); /* critical error interrupt */ #else setvect(0x24, old_cint); /* restore critical error interrupt */ setvect(0x1B, old_cbrk); /* restore ctrl-break interrupt */ #endif /* restore ctrl-break handler, how ??? */ if (term_console) mynormvideo(); /* restore screen colors */ } } /* * We have no job control, fake it by starting a new shell. */ void mch_suspend(void) { suspend_shell(); } extern int _fmode; /* * Prepare window for use by Vim. */ void mch_init(void) { union REGS regs; #if defined(DJGPP) && defined(FEAT_CLIPBOARD) __dpmi_regs dpmi_regs; #endif /* * Get the video attributes at the cursor. These will be used as the * default attributes. */ regs.h.ah = 0x08; regs.h.bh = 0x00; /* video page 0 */ int86(0x10, &regs, &regs); orig_attr = regs.h.ah; mynormvideo(); if (cterm_normal_fg_color == 0) cterm_normal_fg_color = (orig_attr & 0xf) + 1; if (cterm_normal_bg_color == 0) cterm_normal_bg_color = ((orig_attr >> 4) & 0xf) + 1; term_console = TRUE; /* assume using the console for the things here */ _fmode = O_BINARY; /* we do our own CR-LF translation */ out_flush(); set_interrupts(TRUE); /* catch interrupts */ #ifdef DJGPP /* * Use Long File Names by default, if $LFN not set. */ if (getenv("LFN") == NULL) putenv("LFN=y"); get_screenbase(); #endif #ifdef FEAT_MOUSE /* find out if a MS compatible mouse is available */ regs.x.ax = 0; (void)int86(0x33, &regs, &regs); mouse_avail = regs.x.ax; /* best guess for mouse coordinate computations */ mch_get_shellsize(); if (Columns <= 40) mouse_x_div = 16; if (Rows == 30) mouse_y_div = 16; #endif /* * Try switching to 16 colors for background, instead of 8 colors and * blinking. Does this always work? Can the old value be restored? */ regs.x.ax = 0x1003; regs.h.bl = 0x00; regs.h.bh = 0x00; int86(0x10, &regs, &regs); /* * Test if we have an enhanced AT keyboard. Write 0xFFFF to the keyboard * buffer and try to read it back. If we can't in 16 tries, it's an old * type XT keyboard. */ regs.h.ah = 0x05; regs.x.cx = 0xffff; int86(0x16, &regs, &regs); if (regs.h.al != 1) /* skip this when keyboard buffer is full */ { int i; for (i = 0; i < 16; ++i) { regs.h.ah = 0x10; int86(0x16, &regs, &regs); if (regs.x.ax == 0xffff) break; } if (i == 16) /* 0xffff not read, must be old keyboard */ { bioskey_read = 0; bioskey_ready = 1; } } #ifdef MCH_CURSOR_SHAPE /* Save the old cursor shape */ mch_restore_cursor_shape(FALSE); /* Initialise the cursor shape */ mch_update_cursor(); #endif #if defined(DJGPP) && defined(FEAT_CLIPBOARD) /* * Check to see if the Windows clipboard is available, ie. are we * running from a DOS session within Windows. Obviously, the Windows * clipboard will not be available if we're running under pure DOS. * * int 0x2f, AX = 0x1700 identifies the Windows version we're running * under. Upon return from the interrupt, if AX is unchanged, we're * running under pure DOS and no Windows clipboard is available. * * Remark: could use int86() here but __dpmi_int() is recommended in * the DJGPP docs, since int86() doesn't cover all available interrupts. */ dpmi_regs.x.ax = 0x1700; if (__dpmi_int(0x2f, &dpmi_regs) == -1) /* real-mode interrupt failed? */ dpmi_regs.x.ax = 0x1700; /* force failure */ if (dpmi_regs.x.ax == 0x1700) /* no change in AX? */ clip_init(FALSE); /* no clipboard available, too bad */ else /* else, running under Windows, OK */ clip_init(TRUE); /* clipboard is available */ #endif } int mch_check_win( int argc, char **argv) { /* store argv[0], may be used for $VIM */ if (*argv[0] != NUL) exe_name = FullName_save((char_u *)argv[0], FALSE); /* * Try the DOS search path. The executable may in * fact be called differently, so try this last. */ if (exe_name == NULL || *exe_name == NUL) exe_name = searchpath("vim.exe"); if (isatty(1)) return OK; return FAIL; } /* * Return TRUE if the input comes from a terminal, FALSE otherwise. */ int mch_input_isatty(void) { if (isatty(read_cmd_fd)) return TRUE; return FALSE; } #if defined(USE_FNAME_CASE) || defined(PROTO) /* * fname_case(): Set the case of the file name, if it already exists. * TODO: should expand short to long file names. Need to use DOS interrupts, * see DJGPP sources libc/dos/dir/findfirs.c. */ void fname_case(char_u *name, int len) { char_u *tail; struct ffblk fb; slash_adjust(name); if (findfirst(name, &fb, 0) == 0) { tail = gettail(name); if (len == 0 ? STRLEN(tail) == STRLEN(fb.ff_name) : (tail - name) + STRLEN(fb.ff_name) < len) STRCPY(tail, fb.ff_name); } } #endif /* * return process ID */ long mch_get_pid(void) { return (long)0; } /* * Change default drive (just like _chdrive of Borland C 3.1) */ static int change_drive(int drive) { union REGS regs; regs.h.ah = 0x0e; regs.h.dl = drive - 1; intdos(&regs, &regs); /* set default drive */ regs.h.ah = 0x19; intdos(&regs, &regs); /* get default drive */ if (regs.h.al == drive - 1) return 0; return -1; } /* * Get absolute file name into buffer 'buf' of length 'len' bytes. * All slashes are replaced with backslashes, to avoid trouble when comparing * file names. When 'shellslash' set do it the other way around. * * return FAIL for failure, OK otherwise */ int mch_FullName( char_u *fname, char_u *buf, int len, int force) { if (!force && mch_isFullName(fname)) /* already expanded */ { vim_strncpy(buf, fname, len - 1); slash_adjust(buf); return OK; } #ifdef __BORLANDC__ /* Only Borland C++ has this */ if (_fullpath((char *)buf, (char *)fname, len - 1) == NULL) return FAIL; return OK; #else /* almost the same as mch_FullName() in os_unix.c */ { # if 1 char_u fullpath[MAXPATHL]; if (!_truename(fname, fullpath)) return FAIL; slash_adjust(fullpath); /* Only needed when 'shellslash' set */ vim_strncpy(buf, fullpath, len - 1); return OK; # else /* Old code, to be deleted... */ int l; char_u olddir[MAXPATHL]; char_u *p, *q; int c; int retval = OK; *buf = 0; /* * change to the directory for a moment, * and then do the getwd() (and get back to where we were). * This will get the correct path name with "../" things. */ p = vim_strrchr(fname, '/'); q = vim_strrchr(fname, '\\'); if (q != NULL && (p == NULL || q > p)) p = q; q = vim_strrchr(fname, ':'); if (q != NULL && (p == NULL || q > p)) p = q; if (p != NULL) { if (getcwd(olddir, MAXPATHL) == NULL) { p = NULL; /* can't get current dir: don't chdir */ retval = FAIL; } else { if (p == fname) /* /fname */ q = p + 1; /* -> / */ else if (q + 1 == p) /* ... c:\foo */ q = p + 1; /* -> c:\ */ else /* but c:\foo\bar */ q = p; /* -> c:\foo */ c = *q; /* truncate at start of fname */ *q = NUL; # ifdef DJGPP STRCPY(buf, fname); slash_adjust(buf); /* needed when fname starts with \ */ if (mch_chdir(buf)) /* change to the directory */ # else if (mch_chdir(fname)) /* change to the directory */ # endif retval = FAIL; else { fname = q; if (c == psepc) /* if we cut the name at a */ fname++; /* '\', don't add it again */ } *q = c; } } if (getcwd(buf, len) == NULL) { retval = FAIL; *buf = NUL; } # ifdef USE_FNAME_CASE else { char_u *head; char_u *tail; struct ffblk fb; int c; int added; /* Apparently "longna~1" isn't expanded by getcwd(), at least not * for DJGPP. Expand it here. Have to do each dirname * separately. */ slash_adjust(buf); head = buf; if (isalpha(*head) && head[1] == ':') head += 2; /* skip "c:" */ while (*head != NUL) { /* Advance "head" to the start of a dirname and "tail" to just * after it. */ while (*head == '/' || *head == '\\') ++head; for (tail = head; *tail != NUL; ++tail) if (*tail == '/' || *tail == '\\') break; c = *tail; *tail = NUL; if (findfirst(buf, &fb, FA_DIREC) == 0) { added = STRLEN(fb.ff_name); if ((head - buf) + added + STRLEN(tail + 1) + 2 < len) { added -= (tail - head); if (added != 0) STRMOVE(tail + 1 + added, tail + 1); STRCPY(head, fb.ff_name); tail += added; } } *tail = c; head = tail; } } # endif if (p != NULL) mch_chdir(olddir); /* * Concatenate the file name to the path. */ if (*fname != NUL) { l = STRLEN(buf); if (l > 0 && buf[l - 1] != '/' && buf[l - 1] != '\\') strcat(buf, pseps); strcat(buf, fname); } return retval; # endif } #endif } /* * Replace all slashes by backslashes. * This used to be the other way around, but MS-DOS sometimes has problems * with slashes (e.g. in a command name). We can't have mixed slashes and * backslashes, because comparing file names will not work correctly. The * commands that use a file name should try to avoid the need to type a * backslash twice. * When 'shellslash' set do it the other way around. */ void slash_adjust(char_u *p) { #ifdef OLD_DJGPP /* this seems to have been fixed in DJGPP 2.01 */ /* DJGPP can't handle a file name that starts with a backslash, and when it * starts with a slash there should be no backslashes */ if (*p == '\\' || *p == '/') while (*p) { if (*p == '\\') *p = '/'; mb_ptr_adv(p); } else #endif while (*p) { if (*p == psepcN) *p = psepc; mb_ptr_adv(p); } } /* * Return TRUE if "fname" does not depend on the current directory. */ int mch_isFullName(char_u *fname) { /* A name like "d:/foo" and "//server/share" is absolute */ return (fname[0] != NUL && fname[1] == ':' && (fname[2] == '/' || fname[2] == '\\')) || (fname[0] == fname[1] && (fname[0] == '/' || fname[0] == '\\')); } void mch_early_init(void) { } /* * Careful: mch_exit() may be called before mch_init()! */ void mch_exit(int r) { settmode(TMODE_COOK); stoptermcap(); set_interrupts(FALSE); /* restore interrupts */ #ifdef DJGPP set_sys_cursor(); #endif /* Somehow outputting CR-NL causes the original colors to be restored */ out_char('\r'); out_char('\n'); out_flush(); ml_close_all(TRUE); /* remove all memfiles */ #ifdef MCH_CURSOR_SHAPE mch_restore_cursor_shape(TRUE); #endif exit(r); } /* * set the tty in (raw) ? "raw" : "cooked" mode * Does not change the tty, as bioskey() and kbhit() work raw all the time. */ void mch_settmode(int tmode) { } #ifdef FEAT_MOUSE void mch_setmouse(int on) { mouse_active = on; mouse_hidden = TRUE; /* dont show it until moved */ } #endif /* * set screen mode * return FAIL for failure, OK otherwise */ int mch_screenmode(char_u *arg) { int mode; int i; static char *(names[]) = {"BW40", "C40", "BW80", "C80", "MONO", "C4350"}; static int modes[] = { BW40, C40, BW80, C80, MONO, C4350}; mode = -1; if (VIM_ISDIGIT(*arg)) /* mode number given */ mode = atoi((char *)arg); else { for (i = 0; i < sizeof(names) / sizeof(char_u *); ++i) if (stricmp(names[i], (char *)arg) == 0) { mode = modes[i]; break; } } if (mode == -1) { EMSG("E362: Unsupported screen mode"); return FAIL; } textmode(mode); /* use Borland function */ #ifdef DJGPP /* base address may have changed */ get_screenbase(); #endif /* Screen colors may have changed. */ out_str(T_ME); #ifdef FEAT_MOUSE if (mode <= 1 || mode == 4 || mode == 5 || mode == 13 || mode == 0x13) mouse_x_div = 16; else mouse_x_div = 8; if (mode == 0x11 || mode == 0x12) mouse_y_div = 16; else if (mode == 0x10) mouse_y_div = 14; else mouse_y_div = 8; shell_resized(); #endif return OK; } /* * Structure used by Turbo-C/Borland-C to store video parameters. */ #ifndef DJGPP extern struct text_info _video; #endif /* * try to get the real window size * return FAIL for failure, OK otherwise */ int mch_get_shellsize(void) { struct text_info textinfo; /* * The screenwidth is returned by the BIOS OK. * The screenheight is in a location in the bios RAM, if the display is * EGA or VGA. */ if (!term_console) return FAIL; gettextinfo(&textinfo); Columns = textinfo.screenwidth; Rows = textinfo.screenheight; #ifndef DJGPP if (textinfo.currmode > 10) Rows = *(char far *)MK_FP(0x40, 0x84) + 1; #endif if (Columns < MIN_COLUMNS || Rows < MIN_LINES) { /* these values are overwritten by termcap size or default */ Columns = 80; Rows = 25; return FAIL; } #ifdef DJGPP mytextinit(&textinfo); /* Added by JML, 1/15/98 */ #endif return OK; } /* * Set the active window for delline/insline. */ static void set_window(void) { if (term_console) { #ifndef DJGPP _video.screenheight = Rows; #endif mywindow(1, 1, Columns, Rows); } screen_start(); } void mch_set_shellsize(void) { /* Should try to set the window size to Rows and Columns. * May involve switching display mode.... * We assume the user knows the size and just use it. */ } /* * Rows and/or Columns has changed. */ void mch_new_shellsize() { #ifdef FEAT_MOUSE /* best guess for mouse coordinate computations */ if (Columns <= 40) mouse_x_div = 16; if (Rows == 30) mouse_y_div = 16; #endif set_window(); #ifdef FEAT_MOUSE mouse_area(); /* set area where mouse can go */ #endif } #if defined(DJGPP) || defined(PROTO) /* * Check the number of Columns with a BIOS call. This avoids a crash of the * DOS console when 'columns' is set to a too large value. */ void mch_check_columns() { static union REGS regs; regs.h.ah = 0x0f; (void)int86(0x10, &regs, &regs); if ((unsigned)Columns > (unsigned)regs.h.ah) Columns = (unsigned)regs.h.ah; } #endif /* * call shell, return FAIL for failure, OK otherwise * options: SHELL_*, see vim.h. */ int mch_call_shell( char_u *cmd, int options) { int x; int tmode = cur_tmode; #ifndef DJGPP char_u *newcmd; #endif out_flush(); #ifdef DJGPP set_sys_cursor(); #endif if (options & SHELL_COOKED) settmode(TMODE_COOK); /* set to normal mode */ set_interrupts(FALSE); /* restore interrupts */ #ifdef DJGPP /* ignore signals while external command is running */ signal(SIGINT, SIG_IGN); signal(SIGHUP, SIG_IGN); signal(SIGQUIT, SIG_IGN); signal(SIGTERM, SIG_IGN); #endif if (cmd == NULL) x = system((char *)p_sh); else { #ifdef DJGPP /* * Use 'shell' for system(). */ setenv("SHELL", (char *)p_sh, 1); x = system(cmd); #else /* we use "command" to start the shell, slow but easy */ newcmd = alloc(STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 3); if (newcmd == NULL) x = -1; else { sprintf((char *)newcmd, "%s %s %s", p_sh, p_shcf, cmd); x = system((char *)newcmd); vim_free(newcmd); } #endif } #ifdef DJGPP signal(SIGINT, SIG_DFL); signal(SIGHUP, SIG_DFL); signal(SIGQUIT, SIG_DFL); signal(SIGTERM, SIG_DFL); #endif if (tmode == TMODE_RAW) settmode(TMODE_RAW); /* set to raw mode */ set_interrupts(TRUE); /* catch interrupts */ if (x && !(options & SHELL_SILENT) && !emsg_silent) { MSG_PUTS("\nshell returned "); msg_outnum((long)x); msg_putchar('\n'); } return x; } /* * check for an "interrupt signal": CTRL-break or CTRL-C */ void mch_breakcheck(void) { if (ctrlc_pressed) { ctrlc_pressed = FALSE; got_int = TRUE; } } /* * Return TRUE if "p" contain a wildcard that can be expanded by * dos_expandpath(). */ int mch_has_exp_wildcard(char_u *p) { for ( ; *p; mb_ptr_adv(p)) { if (vim_strchr((char_u *)"?*[", *p) != NULL || (*p == '~' && p[1] != NUL)) return TRUE; } return FALSE; } /* * Return TRUE if "p" contain a wildcard or a "~1" kind of thing (could be a * shortened file name). */ int mch_has_wildcard(char_u *p) { for ( ; *p; mb_ptr_adv(p)) { if (vim_strchr((char_u *) # ifdef VIM_BACKTICK "?*$[`" # else "?*$[" # endif , *p) != NULL || (*p == '~' && p[1] != NUL)) return TRUE; } return FALSE; } /* * Change directory to "path". * The normal chdir() does not change the default drive. This one does. * Return 0 for success, -1 for failure. */ int mch_chdir(char *path) { if (path[0] == NUL) /* just checking... */ return 0; if (p_verbose >= 5) { verbose_enter(); smsg((char_u *)"chdir(%s)", path); verbose_leave(); } if (path[1] == ':') /* has a drive name */ { if (change_drive(TOLOWER_ASC(path[0]) - 'a' + 1)) return -1; /* invalid drive name */ path += 2; } if (*path == NUL) /* drive name only */ return 0; return chdir(path); /* let the normal chdir() do the rest */ } #ifdef DJGPP /* * mch_rename() works around a bug in rename (aka MoveFile) in * Windows 95: rename("foo.bar", "foo.bar~") will generate a * file whose short file name is "FOO.BAR" (its long file name will * be correct: "foo.bar~"). Because a file can be accessed by * either its SFN or its LFN, "foo.bar" has effectively been * renamed to "foo.bar", which is not at all what was wanted. This * seems to happen only when renaming files with three-character * extensions by appending a suffix that does not include ".". * Windows NT gets it right, however, with an SFN of "FOO~1.BAR". * This works like mch_rename in os_win32.c, but is a bit simpler. * * Like rename(), returns 0 upon success, non-zero upon failure. * Should probably set errno appropriately when errors occur. */ int mch_rename(const char *OldFile, const char *NewFile) { char_u *TempFile; int retval; int fd; /* rename() works correctly without long file names, so use that */ if (!_USE_LFN) return rename(OldFile, NewFile); if ((TempFile = alloc((unsigned)(STRLEN(OldFile) + 13))) == NULL) return -1; STRCPY(TempFile, OldFile); STRCPY(gettail(TempFile), "axlqwqhy.ba~"); if (rename(OldFile, TempFile)) retval = -1; else { /* now create an empty file called OldFile; this prevents * the operating system using OldFile as an alias (SFN) * if we're renaming within the same directory. For example, * we're editing a file called filename.asc.txt by its SFN, * filena~1.txt. If we rename filena~1.txt to filena~1.txt~ * (i.e., we're making a backup while writing it), the SFN * for filena~1.txt~ will be filena~1.txt, by default, which * will cause all sorts of problems later in buf_write(). So, we * create an empty file called filena~1.txt and the system will have * to find some other SFN for filena~1.txt~, such as filena~2.txt */ if ((fd = open(OldFile, O_RDWR|O_CREAT|O_EXCL, 0444)) < 0) return -1; retval = rename(TempFile, NewFile); close(fd); mch_remove((char_u *)OldFile); /* If renaming to NewFile failed, rename TempFile back to OldFile, so * that it looks like nothing happened. */ if (retval) rename(TempFile, OldFile); } vim_free(TempFile); return retval; /* success */ } #endif #if defined(DJGPP) || defined(PROTO) /* * setlocale() for DJGPP with MS-DOS codepage support * Author: Cyril Slobin <slobin@fe.msk.ru> * * Scaled down a lot for use by Vim: Only support setlocale(LC_ALL, ""). */ #undef setlocale #include <go32.h> #include <inlines/ctype.ha> #include <locale.h> #define UPCASE (__dj_ISALNUM | __dj_ISALPHA | __dj_ISGRAPH | __dj_ISPRINT | __dj_ISUPPER) #define LOCASE (__dj_ISALNUM | __dj_ISALPHA | __dj_ISGRAPH | __dj_ISPRINT | __dj_ISLOWER) char * djgpp_setlocale(void) { __dpmi_regs regs; struct { char id; unsigned short off, seg; } __attribute__ ((packed)) info; unsigned char buffer[0x82], lower, upper; int i; regs.x.ax = 0x6502; regs.x.bx = 0xffff; regs.x.dx = 0xffff; regs.x.cx = 5; regs.x.es = __tb >> 4; regs.x.di = __tb & 0xf; __dpmi_int(0x21, &regs); if (regs.x.flags & 1) return NULL; dosmemget(__tb, 5, &info); dosmemget((info.seg << 4) + info.off, 0x82, buffer); if (*(short *)buffer != 0x80) return NULL; /* Fix problem of underscores being replaced with y-umlaut. (Levin) */ if (buffer[26] == 0x5f) buffer[26] = 0x98; for (i = 0; i < 0x80; i++) { lower = i + 0x80; upper = (buffer+2)[i]; if (lower != upper) { __dj_ctype_flags[lower+1] = LOCASE; __dj_ctype_toupper[lower+1] = upper; if (__dj_ctype_flags[upper+1] == 0) __dj_ctype_flags[upper+1] = UPCASE; if (__dj_ctype_tolower[upper+1] == upper) __dj_ctype_tolower[upper+1] = lower; } } return "C"; } #if defined(FEAT_CLIPBOARD) || defined(PROTO) /* * Clipboard stuff, for cutting and pasting text to other windows. * * Implementation of DOS/Windows clipboard data transfer * by David Kotchan (dkotchan@sympatico.ca) */ #define CF_TEXT 0x01 /* Windows clipboard format: Windows (ANSI) text */ #define CF_OEMTEXT 0x07 /* Windows clipboard format: OEM (DOS) text */ #define CF_VIMCLIP 0x04 /* trick: SYLK clipboard format for VimClipboard */ static int Win16OpenClipboard(void); static int Win16CloseClipboard(void); static int Win16EmptyClipboard(void); static char_u *Win16GetClipboardData(int clip_data_format); static int Win16SetClipboardData(int clip_data_format, char_u *clip_data, int clip_data_size, int clip_data_type); /* * Make vim the owner of the current selection. Return OK upon success. */ int clip_mch_own_selection(VimClipboard *cbd) { /* * Never actually own the clipboard. If another application sets the * clipboard, we don't want to think that we still own it. */ return FAIL; } /* * Make vim NOT the owner of the current selection. */ void clip_mch_lose_selection(VimClipboard *cbd) { /* Nothing needs to be done here */ } /* * Read the Windows clipboard text and put it in Vim's clipboard register. */ void clip_mch_request_selection(VimClipboard *cbd) { int type = MAUTO; char_u *pAllocated = NULL; char_u *pClipText = NULL; int clip_data_format = 0; if (Win16OpenClipboard()) { /* Check for Vim's own clipboard format first. The CF_VIMCLIP format * is just ordinary text (like CF_TEXT) except prepended by the * selection type (as a single character). Note that under DOS we * actually cannot define a custom CF_VIMCLIP clipboard format; we * use instead one of the existing Windows-defined formats, usually * "DIF" or "SYLK". See Win16GetClipboardData() for details. * * Note that Win16GetClipboardData() returns the address of the memory * block it allocated. This is not necessary the start of the * clipboard text data: there may be other bytes ahead of the * text (particularly for CF_VIMCLIP) which are used for data * management. So pClipText is not necessarily == pAllocated. */ if ((pAllocated = Win16GetClipboardData(CF_VIMCLIP)) != NULL) { clip_data_format = CF_VIMCLIP; pClipText = pAllocated; switch (*pClipText++) /* after ++, pClipText points to text */ { default: case 'L': type = MLINE; break; case 'C': type = MCHAR; break; #ifdef FEAT_VISUAL case 'B': type = MBLOCK; break; #endif } } /* Otherwise, check for the normal Windows text formats. There are * two of these: CF_TEXT (common) and CF_OEMTEXT (used for DOS * compatibility). Experiments show that, under the DOS/Windows * clipboard interface, writing CF_TEXT data to the clipboard * automatically creates a CF_OEMTEXT format as well. */ else if ((pAllocated = Win16GetClipboardData(CF_TEXT)) != NULL) { clip_data_format = CF_TEXT; pClipText = pAllocated; } else if ((pAllocated = Win16GetClipboardData(CF_OEMTEXT)) != NULL) { clip_data_format = CF_OEMTEXT; pClipText = pAllocated; } /* Did we get anything? */ if (pClipText != NULL) { char_u *pDest; char_u *pStart; char_u *pEnd; long_u clip_data_size = 0; /* The Windows clipboard normally stores its text lines terminated * by <CR><NL>. But Vim uses only <NL>, so translate the <CR><NL> * into <NL>. Also, watch for possible null bytes at the end of * pClipText. These are padding added by "get_clipboard_data" * (int 0x2f, AX= 0x1705) in order to round the data size up to the * next multiple of 32 bytes. See Win16GetClipboardData() for * details. */ pDest = strstr( pClipText, "\r\n" ); /* find first <CR><NL> */ if (pDest != NULL) /* found one? */ { pStart = pDest + 1; /* points to <NL> after <CR> */ pEnd = strstr( pStart, "\r\n" );/* find next <CR><NL> */ while (pEnd != NULL) /* found one? */ { memmove(pDest, pStart, (long)(pEnd - pStart)); /* exclude <CR> */ pDest += (long)(pEnd - pStart); /* new destination */ pStart = pEnd + 1; /* new starting point */ pEnd = strstr(pStart, "\r\n"); /* find next <CR><NL> */ } /* Fell out of while() loop: no more <CR><NL> pairs. Just copy * the rest of the data, up to the first null byte. */ pEnd = strchr(pStart, '\0'); /* find first null */ memmove(pDest, pStart, (long)(pEnd - pStart)); /* exclude nul */ pDest += (long)(pEnd - pStart); *pDest = '\0'; /* terminate */ /* Now that all <CR><NL> pairs have been "compressed" into just * <NL>'s, determine the true text length. */ clip_data_size = (long_u)(pDest - pClipText); } else { /* no <CR><NL> pairs at all */ /* Since the data may have been padded with trailing nulls, * determine the true string length. */ clip_data_size = STRLEN(pClipText); /* true data length */ } /* Copy the cleaned-up data over to Vim's clipboard "*" register. */ clip_yank_selection(type, pClipText, clip_data_size, cbd); /* Free the memory that Win16GetClipboardData() allocated. */ vim_free(pAllocated); } Win16CloseClipboard(); } // end if (Win16OpenClipboard()) } /* * Send the currently selected Vim text to the Windows clipboard. */ void clip_mch_set_selection( VimClipboard *cbd ) { char_u *pClipData = NULL; long_u clip_data_size; int clip_data_type; /* If the '*' register isn't already filled in, fill it in now. */ cbd->owned = TRUE; clip_get_selection(cbd); cbd->owned = FALSE; /* * clip_convert_selection() returns a pointer to a buffer containing * the text to send to the Windows clipboard, together with a count * of the number of characters (bytes) in the buffer. The function's * return value is the 'type' of selection: MLINE, MCHAR, or MBLOCK; * or -1 for failure. */ clip_data_type = clip_convert_selection(&pClipData, &clip_data_size, cbd); if (clip_data_type < 0) /* could not convert? */ return; /* early exit */ if (Win16OpenClipboard()) { if (Win16EmptyClipboard()) { int sentOK; sentOK = Win16SetClipboardData(CF_TEXT, pClipData, clip_data_size, clip_data_type); sentOK = Win16SetClipboardData(CF_VIMCLIP, pClipData, clip_data_size, clip_data_type) && sentOK; if (!sentOK) { /* one or both of Win16SetClipboardData() failed. */ /* Technically we don't know why Win16SetClipboardData() * failed, but almost always it will be because there wasn't * enough DOS memory to buffer the data, so report that as the * problem. * * We report the error here (instead of in * Win16SetClipboardData()) because we don't want the error * reported twice. */ EMSG("E450: Selection too large, cannot allocate DOS buffer"); } } Win16CloseClipboard(); } /* release memory allocated by clip_convert_selection() */ vim_free(pClipData); return; } /* * Win16OpenClipboard: open the Windows clipboard. The clipboard must be open * before it can be communicated with at all. Return TRUE on success, * FALSE on failure. */ static int Win16OpenClipboard(void) { __dpmi_regs dpmi_regs; long start_time; int tick_count; /* int 02xf, AX = 0x1701 attempts to open the Windows clipboard. Upon * return from the interrupt, if AX is non-zero, the clipboard was * successfully opened. If AX is zero, the clipboard could not be opened * because it is currently in use by another process. * * Remark: other DOS programs I (dk) have written that use the Windows * clipboard sometimes encounter the problem that the clipboard cannot * be opened even though it is demonstrably not in use by any other * process. In all cases, repeated attempts to open the clipboard * eventually succeed, but the initial attempt occasionally fails. * * The problem is intermittent and appears to be related to DOS being * "busy" at certain unpredictable times. DOS maintains two internal * flags that indicate whether it's busy: InDOS and CritErr. The * location of InDOS can be found by calling int 0x21, AH = 0x34. The * location of CritErr can be found by calling int 0x21, AX = 0x5d06. * If either of these flags is set, DOS is "busy" and cannot be * interrupted. See "Undocumented DOS" by Schulman et al for details. * * However here I take the easier approach that if the first call to open * the clipboard does not succeed, just try again. In fact, try once per * biostime() clock tick, up to 18 times (about one second). */ tick_count = 0; dpmi_regs.x.ax = 0x1701; /* open Windows clipboard */ if (__dpmi_int(0x2f, &dpmi_regs) == -1) { /* real-mode interrupt failed? */ return FALSE; /* FALSE --> clipboard not open */ } /* wait up to one second */ while (dpmi_regs.x.ax == 0 && tick_count++ < 18) { /* Wait one clock tick (18.2 ticks/sec = 55 msec per tick). * * We busy-wait here. Unfortunately, delay() and usleep() have been * reported to give problems with the original Windows 95. This is * fixed in service pack 1, but not everybody installed that. */ start_time = biostime(0, 0L); while (biostime(0, 0L) == start_time) ; dpmi_regs.x.ax = 0x1701; /* open Windows clipboard */ if (__dpmi_int(0x2f, &dpmi_regs) == -1) { /* real-mode interrupt failed? */ return FALSE; /* FALSE --> clipboard not open */ } } /* Couldn't open the clipboard, even after 18 attempts? */ if (tick_count >= 18 && dpmi_regs.x.ax == 0) return FALSE; /* FALSE --> clipboard not open */ return TRUE; /* TRUE --> clipboard opened successfully, OK */ } /* * Win16CloseClipboard: close the Windows clipboard. Return TRUE on * success, FALSE on failure. This function can always be called, * whether the clipboard is open or not. */ static int Win16CloseClipboard(void) { __dpmi_regs dpmi_regs; /* Close the clipboard. This interrupt can always be called, even * if the clipboard is already closed. */ dpmi_regs.x.ax = 0x1708; /* close the clipboard */ if (__dpmi_int(0x2f, &dpmi_regs) == -1) { /* real-mode interrupt failed? */ return FALSE; /* FALSE --> clipboard could not be closed */ } return TRUE; /* TRUE --> clipboard closed successfully, OK */ } /* * Win16EmptyClipboard: empty the (previously opened) Windows clipboard. * Return TRUE on success, FALSE on failure. */ static int Win16EmptyClipboard(void) { __dpmi_regs dpmi_regs; /* int 02xf, AX = 0x1702 attempts to empty the Windows clipboard. Upon * return from the interrupt, if AX == 0, the clipboard could not be * emptied (for some reason). */ dpmi_regs.x.ax = 0x1702; /* empty the Windows clipboard */ if (__dpmi_int(0x2f, &dpmi_regs) == -1) { /* real-mode interrupt failed? */ return FALSE; /* FALSE --> clipboard could not be emptied */ } /* Did we succeed in clearing the clipboard? */ if (dpmi_regs.x.ax == 0) return FALSE; /* FALSE --> clipboard could not be emptied */ return TRUE; /* TRUE --> clipboard was emptied, OK */ } /* * FreeDOSMemory: a helper function to free memory previously * allocated by a call to __dpmi_allocate_dos_memory(). */ static void FreeDOSMemory(int protected_mode_selector) { /* Free the DOS buffer and release the DPMI prot-mode selector. * * It's important that DOS memory be properly released because * there's only a limited amount of it. Therefore, if the call * to __dpmi_free_dos_memory() fails, emit an error message * unconditionally. */ if (__dpmi_free_dos_memory(protected_mode_selector) == -1) EMSG("E451: could not free DOS memory buffer (DJGPP)"); } /* * Win16GetClipboardData: query the Windows clipboard as to whether data * is available in a particular clipboard format. If data is * available, allocate a buffer for it and read the data from the * clipboard into the buffer. Return a pointer to the buffer. If * no data is available in the requested format, return NULL. * * This routine allocates memory to hold the retrieved clipboard * data. It's the caller's responsibility to free this memory * once it's finished using it. The memory should be freed by * calling vim_free(). */ static char_u * Win16GetClipboardData(int clip_data_format) { __dpmi_regs dpmi_regs; int real_mode_segment_address; int protected_mode_selector; char_u *clip_data_buffer; long_u clip_data_size; /* We only handle clipboard formats we recognize, others are ignored. * * It's not possible to create a custom clipboard format for VimClipboard * data under DOS, so one of the predefined Windows formats had to be * used for CF_VIMCLIP. Two obscure formats, popular when Windows 3.0 * came out but no longer in much use today, are the DIF and SYLK formats. * DIF is the Data Interchange Format, SYLK is the Symbolic Link format. * They are both text formats and either one can be hijacked for use as * "the VimClipboard format". Of course, this conflicts with anyone who * still *is* using DIF or SYLK data formats, but that will be very few * people. * * I (dk) chose SYLK as the more obscure format because it was used * mostly for Microsoft Multiplan (the pre-cursor to Excel) and it's not * likely Multiplan is used anywhere much anymore. Mind you, Excel can * still export to both DIF and SYLK formats. */ switch (clip_data_format) { case CF_VIMCLIP: /* Vim's own special clipboard format */ case CF_TEXT: /* Windows text */ case CF_OEMTEXT: /* DOS (OEM) text */ /* int 02xf, AX = 0x1704 returns the number of bytes of data currently * on the Windows clipboard, for the specified format. Upon return * from the interrupt, DX:AX = the number of bytes, rounded up to the * nearest multiple of 32. */ dpmi_regs.x.ax = 0x1704; /* get size of clipbd data */ dpmi_regs.x.dx = clip_data_format; if (__dpmi_int(0x2f, &dpmi_regs) == -1) { /* real-mode interrupt failed? */ return NULL; /* early exit */ } /* Did we get anything? If not, this is not an error. */ if (dpmi_regs.x.dx == 0 && dpmi_regs.x.ax == 0) { /* no CF_VIMCLIP data? */ return NULL; /* early exit */ } /* There is data available in the requested clipboard format. * * Calculate data size. Remember this is rounded up to the nearest * multiple of 32, so clip_data_size is actually an upper limit. * The extra bytes, if any, are set to null (0x00) when the data is * read from the clipboard. (Later:) actually I'm no longer sure * this is strictly true: the end-of-data is marked by a null, but * the extra bytes appear to sometimes be null, sometimes not. * They may just be garbage. */ clip_data_size = dpmi_regs.x.ax + (dpmi_regs.x.dx << 16); /* Allocate memory to retrieve the data. The buffer has to lie in the * DOS memory region (in the first 1 MByte of address space) because * the Windows clipboard interface expects a 16-bit segment:offset * pointer to a buffer address within the DOS region. Must therefore * use __dpmi_allocate_dos_memory() instead of lalloc() or alloc(). */ real_mode_segment_address = __dpmi_allocate_dos_memory( (clip_data_size + 15) >> 4, /* buffer size, in 16-byte paragraphs */ &protected_mode_selector); /* prot-mode selector for the address */ if (real_mode_segment_address == -1) { /* memory allocation failed. */ /* Technically we don't know why the allocation failed, but * almost always it will be because there wasn't enough DOS * memory to satisfy the request, so report that as the problem. * On my system, DJGPP is able to satisfy a DOS allocation request * up to about 600K in size. This depends on your HIMEM.SYS and * EMM386.EXE settings however. */ EMSG("E452: Clipboard data too large, cannot allocate DOS buffer"); return NULL; /* early exit */ } /* Copy data from the clipboard into the buffer. Experiments show that * the Windows clipboard is smart enough to handle data transfers * larger than 64K properly, even though the buffer address is a 16-bit * segment:offset (which would normally limit the block size to 64K * unless ES gets incremented). */ dpmi_regs.x.ax = 0x1705; /* get clipboard data */ dpmi_regs.x.dx = clip_data_format; /* CF_VIMCLIP */ dpmi_regs.x.es = real_mode_segment_address; /* buffer ad: segment */ dpmi_regs.x.bx = 0; /* buffer ad: offset */ if (__dpmi_int( 0x2f, &dpmi_regs) == -1) { /* real-mode interrupt failed? */ EMSG("E453: could not copy clipboard data to DOS buffer"); FreeDOSMemory(protected_mode_selector); /* clean up DOS mem */ return NULL; /* early exit */ } /* Clipboard data is now in DOS memory in the buffer pointed to by * ES:BX. Copy this into ordinary memory that Vim can access (ie. * prot-mode memory). Allocate one extra byte to ensure the text * is terminated properly (in case it was somehow corrupted). */ clip_data_buffer = (char_u *)lalloc(clip_data_size + 1, TRUE); if (clip_data_buffer == NULL) { /* allocation failed? */ EMSG("E454: could not allocate clipboard memory buffer"); FreeDOSMemory(protected_mode_selector); /* clean up DOS mem */ return NULL; /* early exit */ } *(clip_data_buffer + clip_data_size) = '\0'; /* ensure terminated */ /* Copy the data from DOS memory to Vim-accessible memory. */ movedata( /* DJGPP version of memcpy() */ protected_mode_selector, 0, /* source: DOS ad (via selector) */ _my_ds(), (unsigned)clip_data_buffer, /* target: normal mem address */ clip_data_size); /* how many bytes */ /* Free the DOS buffer and release the DPMI prot-mode selector. */ FreeDOSMemory(protected_mode_selector); /* clean up DOS memory */ return clip_data_buffer; /* return pointer to allocated buffer */ default: /* unknown clipboard format */ return NULL; } } /* * Win16SetClipboardData: send 'clip_data_size' bytes of data from the buffer * pointed to by 'clip_data', to the Windows clipboard. The data is * registered with the clipboard as being in the 'clip_data_format' * format. */ static int Win16SetClipboardData( int clip_data_format, char_u *clip_data, int clip_data_size, int clip_data_type) { __dpmi_regs dpmi_regs; int real_mode_segment_address; int protected_mode_selector; long_u protected_mode_offset = 0L; int total_size = clip_data_size; char_u *clip_sel_type; /* If we're using the CF_VIMCLIP custom format, allocate an extra * byte for clip_sel_type, which is a character indicating the type * of text selection: MLINE, MCHAR, or MBLOCK. */ if (clip_data_format == CF_VIMCLIP) total_size++; /* extra byte for marker */ /* Data cannot be sent directly from a Vim string (pClipData) to * the Windows clipboard, because the Windows clipboard interface * expects a 16-bit (DOS) segment:offset address for the source * buffer. Therefore we must create a "transfer buffer" in the DOS * memory region (in the first 1 MByte of address space) and copy * the Vim string into that. From there, the data can then be sent * to the Windows clipboard. * * To allocate DOS memory, we must use __dpmi_allocate_dos_memory() * instead of lalloc() or alloc(). If the allocation fails, it will * almost invariably be because there is not enough DOS memory * available to accommodate the size of clip_data. There is nothing * we can do about this, we simply have to fail. */ real_mode_segment_address = __dpmi_allocate_dos_memory( (total_size + 15) >> 4, /* buffer size, in 16-byte paragraphs */ &protected_mode_selector); /* prot-mode selector for the address */ if (real_mode_segment_address == -1) { /* memory allocation failed. */ /* Technically we don't know why the allocation failed, but * almost always it will be because there wasn't enough DOS * memory to satisfy the request. On my system, DJGPP is able * to satisfy a DOS allocation request up to about 600K in size. * This depends however on HIMEM.SYS and EMM386.EXE settings. */ return FALSE; /* early exit */ } /* Copy data from Vim's buffer (clip_data) into the DOS transfer buffer. * This can be larger than 64K; movedata() takes care of crossing any * 16-bit segment boundaries. * * If we're using Vim's custom clipboard format, we must copy one extra * byte to indicate the type of selection: line, character, or block. */ if (clip_data_format == CF_VIMCLIP) { switch (clip_data_type) { default: case MLINE: clip_sel_type = "L"; break; case MCHAR: clip_sel_type = "C"; break; #ifdef FEAT_VISUAL case MBLOCK: clip_sel_type = "B"; break; #endif } movedata( _my_ds(), (unsigned)clip_sel_type, /* source: normal memory address */ protected_mode_selector, 0, /* target: DOS ad (via selector) */ 1); /* how many bytes to copy */ protected_mode_offset += STRLEN(clip_sel_type); /* allow for marker */ } movedata( _my_ds(), (unsigned)clip_data, /* source: normal memory address */ protected_mode_selector, /* target: DOS address (via selector) */ protected_mode_offset, /* non-zero, if using clip_sel_type */ clip_data_size); /* how many bytes to copy */ /* Send data from the DOS transfer buffer to the Windows clipboard. * int 02xf, AX = 0x1703 sends SI:CX bytes of data from the buffer * at ES:BX, to the clipboard. */ dpmi_regs.x.ax = 0x1703; /* send clipboard data */ dpmi_regs.x.dx = clip_data_format; /* flag: format of the data */ dpmi_regs.x.si = ((total_size >> 16) & 0x0000ffffL); /* hi word of data size */ dpmi_regs.x.cx = (total_size & 0x0000ffffL); /* lo word of data size */ dpmi_regs.x.es = real_mode_segment_address; /* buffer address: segment */ dpmi_regs.x.bx = 0; /* buffer address: offset */ if (__dpmi_int(0x2f, &dpmi_regs) == -1) { /* real-mode interrupt failed. */ FreeDOSMemory(protected_mode_selector); /* clean up DOS memory */ return FALSE; /* early exit */ } /* Free the DOS buffer and release the DPMI prot-mode selector. */ FreeDOSMemory(protected_mode_selector); /* clean up DOS memory */ return TRUE; /* TRUE --> data successfully sent to clipboard */ } #endif /* FEAT_CLIPBOARD */ #endif /* DJGPP */ /* * End of MS-DOS only code */ #endif /* WIN16 */ /* common MS-DOS and Win16 code follows */ static int vim_chmod(char_u *name) { char_u *p; int f; int c = 0; /* chmod() can't handle a file name with a trailing slash, remove it. * But don't remove it for "/" or "c:/". */ p = name + STRLEN(name); if (p > name) --p; if (p > name && (*p == '\\' || *p == '/') && p[-1] != ':') { c = *p; /* remove trailing (back)slash */ *p = NUL; } else p = NULL; #if defined(__BORLANDC__) && (__BORLANDC__ > 0x410) /* this also sets the archive bit, supported by Borland C 4.0 and later, * where __BORLANDC__ is 0x450 (3.1 is 0x410) */ f = _rtl_chmod((char *)name, 0, 0); #else f = _chmod((char *)name, 0, 0); #endif if (p != NULL) *p = c; /* put back (back)slash */ return f; } /* * get file permissions for 'name' * Returns -1 for error. * Returns FA_attributes defined in dos.h */ long mch_getperm(char_u *name) { return (long)vim_chmod(name); /* get file mode */ } /* * set file permission for 'name' to 'perm' * * return FAIL for failure, OK otherwise */ int mch_setperm( char_u *name, long perm) { perm |= FA_ARCH; /* file has changed, set archive bit */ #if defined(__BORLANDC__) && (__BORLANDC__ > 0x410) return (_rtl_chmod((char *)name, 1, (int)perm) == -1 ? FAIL : OK); #else return (_chmod((char *)name, 1, (int)perm) == -1 ? FAIL : OK); #endif } /* * Set hidden flag for "name". */ void mch_hide(char_u *name) { /* DOS 6.2 share.exe causes "seek error on file write" errors when making * the swap file hidden. Thus don't do it. */ } /* * return TRUE if "name" is a directory * return FALSE if "name" is not a directory * return FALSE for error * * beware of a trailing (back)slash */ int mch_isdir(char_u *name) { int f; f = vim_chmod(name); if (f == -1) return FALSE; /* file does not exist at all */ if ((f & FA_DIREC) == 0) return FALSE; /* not a directory */ return TRUE; } /* * Return 1 if "name" can be executed, 0 if not. * Return -1 if unknown. */ int mch_can_exe(name) char_u *name; { char *p; p = searchpath(name); if (p == NULL || mch_isdir(p)) return FALSE; return TRUE; } /* * Check what "name" is: * NODE_NORMAL: file or directory (or doesn't exist) * NODE_WRITABLE: writable device, socket, fifo, etc. * NODE_OTHER: non-writable things */ int mch_nodetype(char_u *name) { if (STRICMP(name, "AUX") == 0 || STRICMP(name, "CON") == 0 || STRICMP(name, "CLOCK$") == 0 || STRICMP(name, "NUL") == 0 || STRICMP(name, "PRN") == 0 || ((STRNICMP(name, "COM", 3) == 0 || STRNICMP(name, "LPT", 3) == 0) && VIM_ISDIGIT(name[3]) && name[4] == NUL)) return NODE_WRITABLE; /* TODO: NODE_OTHER? */ return NODE_NORMAL; } /* * Get name of current directory into buffer 'buf' of length 'len' bytes. * Return OK for success, FAIL for failure. */ int mch_dirname( char_u *buf, int len) { #ifdef DJGPP if (getcwd((char *)buf, len) == NULL) return FAIL; /* turn the '/'s returned by DJGPP into '\'s */ slash_adjust(buf); return OK; #else return (getcwd((char *)buf, len) != NULL ? OK : FAIL); #endif } /* * this version of remove is not scared by a readonly (backup) file * * returns -1 on error, 0 otherwise (just like remove()) */ int mch_remove(char_u *name) { (void)mch_setperm(name, 0); /* default permissions */ return unlink((char *)name); } /* * Special version of getenv(): Use uppercase name. */ char_u * mch_getenv(char_u *name) { int i; #define MAXENVLEN 50 char_u var_copy[MAXENVLEN + 1]; char_u *p; char_u *res; /* * Take a copy of the argument, and force it to upper case before passing * to getenv(). On DOS systems, getenv() doesn't like lower-case argument * (unlike Win32 et al.) If the name is too long to fit in var_copy[] * allocate memory. */ if ((i = STRLEN(name)) > MAXENVLEN) p = alloc(i + 1); else p = var_copy; if (p == NULL) p = name; /* out of memory, fall back to unmodified name */ else { for (i = 0; name[i] != NUL; ++i) p[i] = toupper(name[i]); p[i] = NUL; } res = (char_u *)getenv((char *)p); if (p != var_copy && p != name) vim_free(p); return res; } /* * Insert user name in s[len]. */ int mch_get_user_name( char_u *s, int len) { *s = NUL; return FAIL; } /* * Insert host name is s[len]. */ void mch_get_host_name( char_u *s, int len) { #ifdef DJGPP vim_strncpy(s, "PC (32 bits Vim)", len - 1); #else vim_strncpy(s, "PC (16 bits Vim)", len - 1); #endif }
zyz2011-vim
src/os_msdos.c
C
gpl2
76,883
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * fileio.c: read from and write to a file */ #include "vim.h" #if defined(__TANDEM) || defined(__MINT__) # include <limits.h> /* for SSIZE_MAX */ #endif #if defined(HAVE_UTIME) && defined(HAVE_UTIME_H) # include <utime.h> /* for struct utimbuf */ #endif #define BUFSIZE 8192 /* size of normal write buffer */ #define SMBUFSIZE 256 /* size of emergency write buffer */ #ifdef FEAT_CRYPT /* crypt_magic[0] is pkzip crypt, crypt_magic[1] is sha2+blowfish */ static char *crypt_magic[] = {"VimCrypt~01!", "VimCrypt~02!"}; static char crypt_magic_head[] = "VimCrypt~"; # define CRYPT_MAGIC_LEN 12 /* must be multiple of 4! */ /* For blowfish, after the magic header, we store 8 bytes of salt and then 8 * bytes of seed (initialisation vector). */ static int crypt_salt_len[] = {0, 8}; static int crypt_seed_len[] = {0, 8}; #define CRYPT_SALT_LEN_MAX 8 #define CRYPT_SEED_LEN_MAX 8 #endif /* Is there any system that doesn't have access()? */ #define USE_MCH_ACCESS #if defined(sun) && defined(S_ISCHR) # define OPEN_CHR_FILES static int is_dev_fd_file(char_u *fname); #endif #ifdef FEAT_MBYTE static char_u *next_fenc __ARGS((char_u **pp)); # ifdef FEAT_EVAL static char_u *readfile_charconvert __ARGS((char_u *fname, char_u *fenc, int *fdp)); # endif #endif #ifdef FEAT_VIMINFO static void check_marks_read __ARGS((void)); #endif #ifdef FEAT_CRYPT static int crypt_method_from_magic __ARGS((char *ptr, int len)); static char_u *check_for_cryptkey __ARGS((char_u *cryptkey, char_u *ptr, long *sizep, off_t *filesizep, int newfile, char_u *fname, int *did_ask)); #endif #ifdef UNIX static void set_file_time __ARGS((char_u *fname, time_t atime, time_t mtime)); #endif static int set_rw_fname __ARGS((char_u *fname, char_u *sfname)); static int msg_add_fileformat __ARGS((int eol_type)); static void msg_add_eol __ARGS((void)); static int check_mtime __ARGS((buf_T *buf, struct stat *s)); static int time_differs __ARGS((long t1, long t2)); #ifdef FEAT_AUTOCMD static int apply_autocmds_exarg __ARGS((event_T event, char_u *fname, char_u *fname_io, int force, buf_T *buf, exarg_T *eap)); static int au_find_group __ARGS((char_u *name)); # define AUGROUP_DEFAULT -1 /* default autocmd group */ # define AUGROUP_ERROR -2 /* erroneous autocmd group */ # define AUGROUP_ALL -3 /* all autocmd groups */ #endif #if defined(FEAT_CRYPT) || defined(FEAT_MBYTE) # define HAS_BW_FLAGS # define FIO_LATIN1 0x01 /* convert Latin1 */ # define FIO_UTF8 0x02 /* convert UTF-8 */ # define FIO_UCS2 0x04 /* convert UCS-2 */ # define FIO_UCS4 0x08 /* convert UCS-4 */ # define FIO_UTF16 0x10 /* convert UTF-16 */ # ifdef WIN3264 # define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */ # define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */ # define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */ # endif # ifdef MACOS_X # define FIO_MACROMAN 0x20 /* convert MacRoman */ # endif # define FIO_ENDIAN_L 0x80 /* little endian */ # define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */ # define FIO_NOCONVERT 0x2000 /* skip encoding conversion */ # define FIO_UCSBOM 0x4000 /* check for BOM at start of file */ # define FIO_ALL -1 /* allow all formats */ #endif /* When converting, a read() or write() may leave some bytes to be converted * for the next call. The value is guessed... */ #define CONV_RESTLEN 30 /* We have to guess how much a sequence of bytes may expand when converting * with iconv() to be able to allocate a buffer. */ #define ICONV_MULT 8 /* * Structure to pass arguments from buf_write() to buf_write_bytes(). */ struct bw_info { int bw_fd; /* file descriptor */ char_u *bw_buf; /* buffer with data to be written */ int bw_len; /* length of data */ #ifdef HAS_BW_FLAGS int bw_flags; /* FIO_ flags */ #endif #ifdef FEAT_MBYTE char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */ int bw_restlen; /* nr of bytes in bw_rest[] */ int bw_first; /* first write call */ char_u *bw_conv_buf; /* buffer for writing converted chars */ int bw_conv_buflen; /* size of bw_conv_buf */ int bw_conv_error; /* set for conversion error */ linenr_T bw_conv_error_lnum; /* first line with error or zero */ linenr_T bw_start_lnum; /* line number at start of buffer */ # ifdef USE_ICONV iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */ # endif #endif }; static int buf_write_bytes __ARGS((struct bw_info *ip)); #ifdef FEAT_MBYTE static linenr_T readfile_linenr __ARGS((linenr_T linecnt, char_u *p, char_u *endp)); static int ucs2bytes __ARGS((unsigned c, char_u **pp, int flags)); static int need_conversion __ARGS((char_u *fenc)); static int get_fio_flags __ARGS((char_u *ptr)); static char_u *check_for_bom __ARGS((char_u *p, long size, int *lenp, int flags)); static int make_bom __ARGS((char_u *buf, char_u *name)); # ifdef WIN3264 static int get_win_fio_flags __ARGS((char_u *ptr)); # endif # ifdef MACOS_X static int get_mac_fio_flags __ARGS((char_u *ptr)); # endif #endif static int move_lines __ARGS((buf_T *frombuf, buf_T *tobuf)); #ifdef TEMPDIRNAMES static void vim_settempdir __ARGS((char_u *tempdir)); #endif #ifdef FEAT_AUTOCMD static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name"); #endif void filemess(buf, name, s, attr) buf_T *buf; char_u *name; char_u *s; int attr; { int msg_scroll_save; if (msg_silent != 0) return; msg_add_fname(buf, name); /* put file name in IObuff with quotes */ /* If it's extremely long, truncate it. */ if (STRLEN(IObuff) > IOSIZE - 80) IObuff[IOSIZE - 80] = NUL; STRCAT(IObuff, s); /* * For the first message may have to start a new line. * For further ones overwrite the previous one, reset msg_scroll before * calling filemess(). */ msg_scroll_save = msg_scroll; if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0) msg_scroll = FALSE; if (!msg_scroll) /* wait a bit when overwriting an error msg */ check_for_delay(FALSE); msg_start(); msg_scroll = msg_scroll_save; msg_scrolled_ign = TRUE; /* may truncate the message to avoid a hit-return prompt */ msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr); msg_clr_eos(); out_flush(); msg_scrolled_ign = FALSE; } /* * Read lines from file "fname" into the buffer after line "from". * * 1. We allocate blocks with lalloc, as big as possible. * 2. Each block is filled with characters from the file with a single read(). * 3. The lines are inserted in the buffer with ml_append(). * * (caller must check that fname != NULL, unless READ_STDIN is used) * * "lines_to_skip" is the number of lines that must be skipped * "lines_to_read" is the number of lines that are appended * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM. * * flags: * READ_NEW starting to edit a new buffer * READ_FILTER reading filter output * READ_STDIN read from stdin instead of a file * READ_BUFFER read from curbuf instead of a file (converting after reading * stdin) * READ_DUMMY read into a dummy buffer (to check if file contents changed) * READ_KEEP_UNDO don't clear undo info or read it from a file * * return FAIL for failure, OK otherwise */ int readfile(fname, sfname, from, lines_to_skip, lines_to_read, eap, flags) char_u *fname; char_u *sfname; linenr_T from; linenr_T lines_to_skip; linenr_T lines_to_read; exarg_T *eap; /* can be NULL! */ int flags; { int fd = 0; int newfile = (flags & READ_NEW); int check_readonly; int filtering = (flags & READ_FILTER); int read_stdin = (flags & READ_STDIN); int read_buffer = (flags & READ_BUFFER); int set_options = newfile || read_buffer || (eap != NULL && eap->read_edit); linenr_T read_buf_lnum = 1; /* next line to read from curbuf */ colnr_T read_buf_col = 0; /* next char to read from this line */ char_u c; linenr_T lnum = from; char_u *ptr = NULL; /* pointer into read buffer */ char_u *buffer = NULL; /* read buffer */ char_u *new_buffer = NULL; /* init to shut up gcc */ char_u *line_start = NULL; /* init to shut up gcc */ int wasempty; /* buffer was empty before reading */ colnr_T len; long size = 0; char_u *p; off_t filesize = 0; int skip_read = FALSE; #ifdef FEAT_CRYPT char_u *cryptkey = NULL; int did_ask_for_key = FALSE; int crypt_method_used; #endif #ifdef FEAT_PERSISTENT_UNDO context_sha256_T sha_ctx; int read_undo_file = FALSE; #endif int split = 0; /* number of split lines */ #define UNKNOWN 0x0fffffff /* file size is unknown */ linenr_T linecnt; int error = FALSE; /* errors encountered */ int ff_error = EOL_UNKNOWN; /* file format with errors */ long linerest = 0; /* remaining chars in line */ #ifdef UNIX int perm = 0; int swap_mode = -1; /* protection bits for swap file */ #else int perm; #endif int fileformat = 0; /* end-of-line format */ int keep_fileformat = FALSE; struct stat st; int file_readonly; linenr_T skip_count = 0; linenr_T read_count = 0; int msg_save = msg_scroll; linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of * last read was missing the eol */ int try_mac = (vim_strchr(p_ffs, 'm') != NULL); int try_dos = (vim_strchr(p_ffs, 'd') != NULL); int try_unix = (vim_strchr(p_ffs, 'x') != NULL); int file_rewind = FALSE; #ifdef FEAT_MBYTE int can_retry; linenr_T conv_error = 0; /* line nr with conversion error */ linenr_T illegal_byte = 0; /* line nr with illegal byte */ int keep_dest_enc = FALSE; /* don't retry when char doesn't fit in destination encoding */ int bad_char_behavior = BAD_REPLACE; /* BAD_KEEP, BAD_DROP or character to * replace with */ char_u *tmpname = NULL; /* name of 'charconvert' output file */ int fio_flags = 0; char_u *fenc; /* fileencoding to use */ int fenc_alloced; /* fenc_next is in allocated memory */ char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */ int advance_fenc = FALSE; long real_size = 0; # ifdef USE_ICONV iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */ # ifdef FEAT_EVAL int did_iconv = FALSE; /* TRUE when iconv() failed and trying 'charconvert' next */ # endif # endif int converted = FALSE; /* TRUE if conversion done */ int notconverted = FALSE; /* TRUE if conversion wanted but it wasn't possible */ char_u conv_rest[CONV_RESTLEN]; int conv_restlen = 0; /* nr of bytes in conv_rest[] */ #endif #ifdef FEAT_AUTOCMD buf_T *old_curbuf; char_u *old_b_ffname; char_u *old_b_fname; int using_b_ffname; int using_b_fname; #endif curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */ /* * If there is no file name yet, use the one for the read file. * BF_NOTEDITED is set to reflect this. * Don't do this for a read from a filter. * Only do this when 'cpoptions' contains the 'f' flag. */ if (curbuf->b_ffname == NULL && !filtering && fname != NULL && vim_strchr(p_cpo, CPO_FNAMER) != NULL && !(flags & READ_DUMMY)) { if (set_rw_fname(fname, sfname) == FAIL) return FAIL; } #ifdef FEAT_AUTOCMD /* Remember the initial values of curbuf, curbuf->b_ffname and * curbuf->b_fname to detect whether they are altered as a result of * executing nasty autocommands. Also check if "fname" and "sfname" * point to one of these values. */ old_curbuf = curbuf; old_b_ffname = curbuf->b_ffname; old_b_fname = curbuf->b_fname; using_b_ffname = (fname == curbuf->b_ffname) || (sfname == curbuf->b_ffname); using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname); #endif /* After reading a file the cursor line changes but we don't want to * display the line. */ ex_no_reprint = TRUE; /* don't display the file info for another buffer now */ need_fileinfo = FALSE; /* * For Unix: Use the short file name whenever possible. * Avoids problems with networks and when directory names are changed. * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to * another directory, which we don't detect. */ if (sfname == NULL) sfname = fname; #if defined(UNIX) || defined(__EMX__) fname = sfname; #endif #ifdef FEAT_AUTOCMD /* * The BufReadCmd and FileReadCmd events intercept the reading process by * executing the associated commands instead. */ if (!filtering && !read_stdin && !read_buffer) { pos_T pos; pos = curbuf->b_op_start; /* Set '[ mark to the line above where the lines go (line 1 if zero). */ curbuf->b_op_start.lnum = ((from == 0) ? 1 : from); curbuf->b_op_start.col = 0; if (newfile) { if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname, FALSE, curbuf, eap)) #ifdef FEAT_EVAL return aborting() ? FAIL : OK; #else return OK; #endif } else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname, FALSE, NULL, eap)) #ifdef FEAT_EVAL return aborting() ? FAIL : OK; #else return OK; #endif curbuf->b_op_start = pos; } #endif if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0) msg_scroll = FALSE; /* overwrite previous file message */ else msg_scroll = TRUE; /* don't overwrite previous file message */ /* * If the name ends in a path separator, we can't open it. Check here, * because reading the file may actually work, but then creating the swap * file may destroy it! Reported on MS-DOS and Win 95. * If the name is too long we might crash further on, quit here. */ if (fname != NULL && *fname != NUL) { p = fname + STRLEN(fname); if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL) { filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0); msg_end(); msg_scroll = msg_save; return FAIL; } } #ifdef UNIX /* * On Unix it is possible to read a directory, so we have to * check for it before the mch_open(). */ if (!read_stdin && !read_buffer) { perm = mch_getperm(fname); if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */ # ifdef S_ISFIFO && !S_ISFIFO(perm) /* ... or fifo */ # endif # ifdef S_ISSOCK && !S_ISSOCK(perm) /* ... or socket */ # endif # ifdef OPEN_CHR_FILES && !(S_ISCHR(perm) && is_dev_fd_file(fname)) /* ... or a character special file named /dev/fd/<n> */ # endif ) { if (S_ISDIR(perm)) filemess(curbuf, fname, (char_u *)_("is a directory"), 0); else filemess(curbuf, fname, (char_u *)_("is not a file"), 0); msg_end(); msg_scroll = msg_save; return FAIL; } # if defined(MSDOS) || defined(MSWIN) || defined(OS2) /* * MS-Windows allows opening a device, but we will probably get stuck * trying to read it. */ if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE) { filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0); msg_end(); msg_scroll = msg_save; return FAIL; } # endif } #endif /* set default 'fileformat' */ if (set_options) { if (eap != NULL && eap->force_ff != 0) set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL); else if (*p_ffs != NUL) set_fileformat(default_fileformat(), OPT_LOCAL); } /* set or reset 'binary' */ if (eap != NULL && eap->force_bin != 0) { int oldval = curbuf->b_p_bin; curbuf->b_p_bin = (eap->force_bin == FORCE_BIN); set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL); } /* * When opening a new file we take the readonly flag from the file. * Default is r/w, can be set to r/o below. * Don't reset it when in readonly mode * Only set/reset b_p_ro when BF_CHECK_RO is set. */ check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO)); if (check_readonly && !readonlymode) curbuf->b_p_ro = FALSE; if (newfile && !read_stdin && !read_buffer) { /* Remember time of file. */ if (mch_stat((char *)fname, &st) >= 0) { buf_store_time(curbuf, &st, fname); curbuf->b_mtime_read = curbuf->b_mtime; #ifdef UNIX /* * Use the protection bits of the original file for the swap file. * This makes it possible for others to read the name of the * edited file from the swapfile, but only if they can read the * edited file. * Remove the "write" and "execute" bits for group and others * (they must not write the swapfile). * Add the "read" and "write" bits for the user, otherwise we may * not be able to write to the file ourselves. * Setting the bits is done below, after creating the swap file. */ swap_mode = (st.st_mode & 0644) | 0600; #endif #ifdef FEAT_CW_EDITOR /* Get the FSSpec on MacOS * TODO: Update it properly when the buffer name changes */ (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec); #endif #ifdef VMS curbuf->b_fab_rfm = st.st_fab_rfm; curbuf->b_fab_rat = st.st_fab_rat; curbuf->b_fab_mrs = st.st_fab_mrs; #endif } else { curbuf->b_mtime = 0; curbuf->b_mtime_read = 0; curbuf->b_orig_size = 0; curbuf->b_orig_mode = 0; } /* Reset the "new file" flag. It will be set again below when the * file doesn't exist. */ curbuf->b_flags &= ~(BF_NEW | BF_NEW_W); } /* * for UNIX: check readonly with perm and mch_access() * for MSDOS and Amiga: check readonly by trying to open the file for writing */ file_readonly = FALSE; if (read_stdin) { #if defined(MSDOS) || defined(MSWIN) || defined(OS2) /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */ setmode(0, O_BINARY); #endif } else if (!read_buffer) { #ifdef USE_MCH_ACCESS if ( # ifdef UNIX !(perm & 0222) || # endif mch_access((char *)fname, W_OK)) file_readonly = TRUE; fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0); #else if (!newfile || readonlymode || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0) { file_readonly = TRUE; /* try to open ro */ fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0); } #endif } if (fd < 0) /* cannot open at all */ { #ifndef UNIX int isdir_f; #endif msg_scroll = msg_save; #ifndef UNIX /* * On MSDOS and Amiga we can't open a directory, check here. */ isdir_f = (mch_isdir(fname)); perm = mch_getperm(fname); /* check if the file exists */ if (isdir_f) { filemess(curbuf, sfname, (char_u *)_("is a directory"), 0); curbuf->b_p_ro = TRUE; /* must use "w!" now */ } else #endif if (newfile) { if (perm < 0 #ifdef ENOENT && errno == ENOENT #endif ) { /* * Set the 'new-file' flag, so that when the file has * been created by someone else, a ":w" will complain. */ curbuf->b_flags |= BF_NEW; /* Create a swap file now, so that other Vims are warned * that we are editing this file. Don't do this for a * "nofile" or "nowrite" buffer type. */ #ifdef FEAT_QUICKFIX if (!bt_dontwrite(curbuf)) #endif { check_need_swap(newfile); #ifdef FEAT_AUTOCMD /* SwapExists autocommand may mess things up */ if (curbuf != old_curbuf || (using_b_ffname && (old_b_ffname != curbuf->b_ffname)) || (using_b_fname && (old_b_fname != curbuf->b_fname))) { EMSG(_(e_auchangedbuf)); return FAIL; } #endif } if (dir_of_file_exists(fname)) filemess(curbuf, sfname, (char_u *)_("[New File]"), 0); else filemess(curbuf, sfname, (char_u *)_("[New DIRECTORY]"), 0); #ifdef FEAT_VIMINFO /* Even though this is a new file, it might have been * edited before and deleted. Get the old marks. */ check_marks_read(); #endif #ifdef FEAT_MBYTE if (eap != NULL && eap->force_enc != 0) { /* set forced 'fileencoding' */ fenc = enc_canonize(eap->cmd + eap->force_enc); if (fenc != NULL) set_string_option_direct((char_u *)"fenc", -1, fenc, OPT_FREE|OPT_LOCAL, 0); vim_free(fenc); } #endif #ifdef FEAT_AUTOCMD apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname, FALSE, curbuf, eap); #endif /* remember the current fileformat */ save_file_ff(curbuf); #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL) if (aborting()) /* autocmds may abort script processing */ return FAIL; #endif return OK; /* a new file is not an error */ } else { filemess(curbuf, sfname, (char_u *)( # ifdef EFBIG (errno == EFBIG) ? _("[File too big]") : # endif # ifdef EOVERFLOW (errno == EOVERFLOW) ? _("[File too big]") : # endif _("[Permission Denied]")), 0); curbuf->b_p_ro = TRUE; /* must use "w!" now */ } } return FAIL; } /* * Only set the 'ro' flag for readonly files the first time they are * loaded. Help files always get readonly mode */ if ((check_readonly && file_readonly) || curbuf->b_help) curbuf->b_p_ro = TRUE; if (set_options) { /* Don't change 'eol' if reading from buffer as it will already be * correctly set when reading stdin. */ if (!read_buffer) { curbuf->b_p_eol = TRUE; curbuf->b_start_eol = TRUE; } #ifdef FEAT_MBYTE curbuf->b_p_bomb = FALSE; curbuf->b_start_bomb = FALSE; #endif } /* Create a swap file now, so that other Vims are warned that we are * editing this file. * Don't do this for a "nofile" or "nowrite" buffer type. */ #ifdef FEAT_QUICKFIX if (!bt_dontwrite(curbuf)) #endif { check_need_swap(newfile); #ifdef FEAT_AUTOCMD if (!read_stdin && (curbuf != old_curbuf || (using_b_ffname && (old_b_ffname != curbuf->b_ffname)) || (using_b_fname && (old_b_fname != curbuf->b_fname)))) { EMSG(_(e_auchangedbuf)); if (!read_buffer) close(fd); return FAIL; } #endif #ifdef UNIX /* Set swap file protection bits after creating it. */ if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL && curbuf->b_ml.ml_mfp->mf_fname != NULL) (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode); #endif } #if defined(HAS_SWAP_EXISTS_ACTION) /* If "Quit" selected at ATTENTION dialog, don't load the file */ if (swap_exists_action == SEA_QUIT) { if (!read_buffer && !read_stdin) close(fd); return FAIL; } #endif ++no_wait_return; /* don't wait for return yet */ /* * Set '[ mark to the line above where the lines go (line 1 if zero). */ curbuf->b_op_start.lnum = ((from == 0) ? 1 : from); curbuf->b_op_start.col = 0; #ifdef FEAT_AUTOCMD if (!read_buffer) { int m = msg_scroll; int n = msg_scrolled; /* * The file must be closed again, the autocommands may want to change * the file before reading it. */ if (!read_stdin) close(fd); /* ignore errors */ /* * The output from the autocommands should not overwrite anything and * should not be overwritten: Set msg_scroll, restore its value if no * output was done. */ msg_scroll = TRUE; if (filtering) apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname, FALSE, curbuf, eap); else if (read_stdin) apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname, FALSE, curbuf, eap); else if (newfile) apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname, FALSE, curbuf, eap); else apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname, FALSE, NULL, eap); if (msg_scrolled == n) msg_scroll = m; #ifdef FEAT_EVAL if (aborting()) /* autocmds may abort script processing */ { --no_wait_return; msg_scroll = msg_save; curbuf->b_p_ro = TRUE; /* must use "w!" now */ return FAIL; } #endif /* * Don't allow the autocommands to change the current buffer. * Try to re-open the file. * * Don't allow the autocommands to change the buffer name either * (cd for example) if it invalidates fname or sfname. */ if (!read_stdin && (curbuf != old_curbuf || (using_b_ffname && (old_b_ffname != curbuf->b_ffname)) || (using_b_fname && (old_b_fname != curbuf->b_fname)) || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0)) { --no_wait_return; msg_scroll = msg_save; if (fd < 0) EMSG(_("E200: *ReadPre autocommands made the file unreadable")); else EMSG(_("E201: *ReadPre autocommands must not change current buffer")); curbuf->b_p_ro = TRUE; /* must use "w!" now */ return FAIL; } } #endif /* FEAT_AUTOCMD */ /* Autocommands may add lines to the file, need to check if it is empty */ wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY); if (!recoverymode && !filtering && !(flags & READ_DUMMY)) { /* * Show the user that we are busy reading the input. Sometimes this * may take a while. When reading from stdin another program may * still be running, don't move the cursor to the last line, unless * always using the GUI. */ if (read_stdin) { #ifndef ALWAYS_USE_GUI mch_msg(_("Vim: Reading from stdin...\n")); #endif #ifdef FEAT_GUI /* Also write a message in the GUI window, if there is one. */ if (gui.in_use && !gui.dying && !gui.starting) { p = (char_u *)_("Reading from stdin..."); gui_write(p, (int)STRLEN(p)); } #endif } else if (!read_buffer) filemess(curbuf, sfname, (char_u *)"", 0); } msg_scroll = FALSE; /* overwrite the file message */ /* * Set linecnt now, before the "retry" caused by a wrong guess for * fileformat, and after the autocommands, which may change them. */ linecnt = curbuf->b_ml.ml_line_count; #ifdef FEAT_MBYTE /* "++bad=" argument. */ if (eap != NULL && eap->bad_char != 0) { bad_char_behavior = eap->bad_char; if (set_options) curbuf->b_bad_char = eap->bad_char; } else curbuf->b_bad_char = 0; /* * Decide which 'encoding' to use or use first. */ if (eap != NULL && eap->force_enc != 0) { fenc = enc_canonize(eap->cmd + eap->force_enc); fenc_alloced = TRUE; keep_dest_enc = TRUE; } else if (curbuf->b_p_bin) { fenc = (char_u *)""; /* binary: don't convert */ fenc_alloced = FALSE; } else if (curbuf->b_help) { char_u firstline[80]; int fc; /* Help files are either utf-8 or latin1. Try utf-8 first, if this * fails it must be latin1. * Always do this when 'encoding' is "utf-8". Otherwise only do * this when needed to avoid [converted] remarks all the time. * It is needed when the first line contains non-ASCII characters. * That is only in *.??x files. */ fenc = (char_u *)"latin1"; c = enc_utf8; if (!c && !read_stdin) { fc = fname[STRLEN(fname) - 1]; if (TOLOWER_ASC(fc) == 'x') { /* Read the first line (and a bit more). Immediately rewind to * the start of the file. If the read() fails "len" is -1. */ len = read_eintr(fd, firstline, 80); lseek(fd, (off_t)0L, SEEK_SET); for (p = firstline; p < firstline + len; ++p) if (*p >= 0x80) { c = TRUE; break; } } } if (c) { fenc_next = fenc; fenc = (char_u *)"utf-8"; /* When the file is utf-8 but a character doesn't fit in * 'encoding' don't retry. In help text editing utf-8 bytes * doesn't make sense. */ if (!enc_utf8) keep_dest_enc = TRUE; } fenc_alloced = FALSE; } else if (*p_fencs == NUL) { fenc = curbuf->b_p_fenc; /* use format from buffer */ fenc_alloced = FALSE; } else { fenc_next = p_fencs; /* try items in 'fileencodings' */ fenc = next_fenc(&fenc_next); fenc_alloced = TRUE; } #endif /* * Jump back here to retry reading the file in different ways. * Reasons to retry: * - encoding conversion failed: try another one from "fenc_next" * - BOM detected and fenc was set, need to setup conversion * - "fileformat" check failed: try another * * Variables set for special retry actions: * "file_rewind" Rewind the file to start reading it again. * "advance_fenc" Advance "fenc" using "fenc_next". * "skip_read" Re-use already read bytes (BOM detected). * "did_iconv" iconv() conversion failed, try 'charconvert'. * "keep_fileformat" Don't reset "fileformat". * * Other status indicators: * "tmpname" When != NULL did conversion with 'charconvert'. * Output file has to be deleted afterwards. * "iconv_fd" When != -1 did conversion with iconv(). */ retry: if (file_rewind) { if (read_buffer) { read_buf_lnum = 1; read_buf_col = 0; } else if (read_stdin || lseek(fd, (off_t)0L, SEEK_SET) != 0) { /* Can't rewind the file, give up. */ error = TRUE; goto failed; } /* Delete the previously read lines. */ while (lnum > from) ml_delete(lnum--, FALSE); file_rewind = FALSE; #ifdef FEAT_MBYTE if (set_options) { curbuf->b_p_bomb = FALSE; curbuf->b_start_bomb = FALSE; } conv_error = 0; #endif } #ifdef FEAT_CRYPT if (cryptkey != NULL) /* Need to reset the state, but keep the key, don't want to ask for it * again. */ crypt_pop_state(); #endif /* * When retrying with another "fenc" and the first time "fileformat" * will be reset. */ if (keep_fileformat) keep_fileformat = FALSE; else { if (eap != NULL && eap->force_ff != 0) { fileformat = get_fileformat_force(curbuf, eap); try_unix = try_dos = try_mac = FALSE; } else if (curbuf->b_p_bin) fileformat = EOL_UNIX; /* binary: use Unix format */ else if (*p_ffs == NUL) fileformat = get_fileformat(curbuf);/* use format from buffer */ else fileformat = EOL_UNKNOWN; /* detect from file */ } #ifdef FEAT_MBYTE # ifdef USE_ICONV if (iconv_fd != (iconv_t)-1) { /* aborted conversion with iconv(), close the descriptor */ iconv_close(iconv_fd); iconv_fd = (iconv_t)-1; } # endif if (advance_fenc) { /* * Try the next entry in 'fileencodings'. */ advance_fenc = FALSE; if (eap != NULL && eap->force_enc != 0) { /* Conversion given with "++cc=" wasn't possible, read * without conversion. */ notconverted = TRUE; conv_error = 0; if (fenc_alloced) vim_free(fenc); fenc = (char_u *)""; fenc_alloced = FALSE; } else { if (fenc_alloced) vim_free(fenc); if (fenc_next != NULL) { fenc = next_fenc(&fenc_next); fenc_alloced = (fenc_next != NULL); } else { fenc = (char_u *)""; fenc_alloced = FALSE; } } if (tmpname != NULL) { mch_remove(tmpname); /* delete converted file */ vim_free(tmpname); tmpname = NULL; } } /* * Conversion may be required when the encoding of the file is different * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4. */ fio_flags = 0; converted = need_conversion(fenc); if (converted) { /* "ucs-bom" means we need to check the first bytes of the file * for a BOM. */ if (STRCMP(fenc, ENC_UCSBOM) == 0) fio_flags = FIO_UCSBOM; /* * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be * done. This is handled below after read(). Prepare the * fio_flags to avoid having to parse the string each time. * Also check for Unicode to Latin1 conversion, because iconv() * appears not to handle this correctly. This works just like * conversion to UTF-8 except how the resulting character is put in * the buffer. */ else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0) fio_flags = get_fio_flags(fenc); # ifdef WIN3264 /* * Conversion from an MS-Windows codepage to UTF-8 or another codepage * is handled with MultiByteToWideChar(). */ if (fio_flags == 0) fio_flags = get_win_fio_flags(fenc); # endif # ifdef MACOS_X /* Conversion from Apple MacRoman to latin1 or UTF-8 */ if (fio_flags == 0) fio_flags = get_mac_fio_flags(fenc); # endif # ifdef USE_ICONV /* * Try using iconv() if we can't convert internally. */ if (fio_flags == 0 # ifdef FEAT_EVAL && !did_iconv # endif ) iconv_fd = (iconv_t)my_iconv_open( enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc); # endif # ifdef FEAT_EVAL /* * Use the 'charconvert' expression when conversion is required * and we can't do it internally or with iconv(). */ if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL # ifdef USE_ICONV && iconv_fd == (iconv_t)-1 # endif ) { # ifdef USE_ICONV did_iconv = FALSE; # endif /* Skip conversion when it's already done (retry for wrong * "fileformat"). */ if (tmpname == NULL) { tmpname = readfile_charconvert(fname, fenc, &fd); if (tmpname == NULL) { /* Conversion failed. Try another one. */ advance_fenc = TRUE; if (fd < 0) { /* Re-opening the original file failed! */ EMSG(_("E202: Conversion made file unreadable!")); error = TRUE; goto failed; } goto retry; } } } else # endif { if (fio_flags == 0 # ifdef USE_ICONV && iconv_fd == (iconv_t)-1 # endif ) { /* Conversion wanted but we can't. * Try the next conversion in 'fileencodings' */ advance_fenc = TRUE; goto retry; } } } /* Set "can_retry" when it's possible to rewind the file and try with * another "fenc" value. It's FALSE when no other "fenc" to try, reading * stdin or fixed at a specific encoding. */ can_retry = (*fenc != NUL && !read_stdin && !keep_dest_enc); #endif if (!skip_read) { linerest = 0; filesize = 0; skip_count = lines_to_skip; read_count = lines_to_read; #ifdef FEAT_MBYTE conv_restlen = 0; #endif #ifdef FEAT_PERSISTENT_UNDO read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0 && curbuf->b_ffname != NULL && curbuf->b_p_udf && !filtering && !read_stdin && !read_buffer); if (read_undo_file) sha256_start(&sha_ctx); #endif } while (!error && !got_int) { /* * We allocate as much space for the file as we can get, plus * space for the old line plus room for one terminating NUL. * The amount is limited by the fact that read() only can read * upto max_unsigned characters (and other things). */ #if SIZEOF_INT <= 2 if (linerest >= 0x7ff0) { ++split; *ptr = NL; /* split line by inserting a NL */ size = 1; } else #endif { if (!skip_read) { #if SIZEOF_INT > 2 # if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L) size = SSIZE_MAX; /* use max I/O size, 52K */ # else size = 0x10000L; /* use buffer >= 64K */ # endif #else size = 0x7ff0L - linerest; /* limit buffer to 32K */ #endif for ( ; size >= 10; size = (long)((long_u)size >> 1)) { if ((new_buffer = lalloc((long_u)(size + linerest + 1), FALSE)) != NULL) break; } if (new_buffer == NULL) { do_outofmem_msg((long_u)(size * 2 + linerest + 1)); error = TRUE; break; } if (linerest) /* copy characters from the previous buffer */ mch_memmove(new_buffer, ptr - linerest, (size_t)linerest); vim_free(buffer); buffer = new_buffer; ptr = buffer + linerest; line_start = buffer; #ifdef FEAT_MBYTE /* May need room to translate into. * For iconv() we don't really know the required space, use a * factor ICONV_MULT. * latin1 to utf-8: 1 byte becomes up to 2 bytes * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes * become up to 4 bytes, size must be multiple of 2 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be * multiple of 2 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be * multiple of 4 */ real_size = (int)size; # ifdef USE_ICONV if (iconv_fd != (iconv_t)-1) size = size / ICONV_MULT; else # endif if (fio_flags & FIO_LATIN1) size = size / 2; else if (fio_flags & (FIO_UCS2 | FIO_UTF16)) size = (size * 2 / 3) & ~1; else if (fio_flags & FIO_UCS4) size = (size * 2 / 3) & ~3; else if (fio_flags == FIO_UCSBOM) size = size / ICONV_MULT; /* worst case */ # ifdef WIN3264 else if (fio_flags & FIO_CODEPAGE) size = size / ICONV_MULT; /* also worst case */ # endif # ifdef MACOS_X else if (fio_flags & FIO_MACROMAN) size = size / ICONV_MULT; /* also worst case */ # endif #endif #ifdef FEAT_MBYTE if (conv_restlen > 0) { /* Insert unconverted bytes from previous line. */ mch_memmove(ptr, conv_rest, conv_restlen); ptr += conv_restlen; size -= conv_restlen; } #endif if (read_buffer) { /* * Read bytes from curbuf. Used for converting text read * from stdin. */ if (read_buf_lnum > from) size = 0; else { int n, ni; long tlen; tlen = 0; for (;;) { p = ml_get(read_buf_lnum) + read_buf_col; n = (int)STRLEN(p); if ((int)tlen + n + 1 > size) { /* Filled up to "size", append partial line. * Change NL to NUL to reverse the effect done * below. */ n = (int)(size - tlen); for (ni = 0; ni < n; ++ni) { if (p[ni] == NL) ptr[tlen++] = NUL; else ptr[tlen++] = p[ni]; } read_buf_col += n; break; } else { /* Append whole line and new-line. Change NL * to NUL to reverse the effect done below. */ for (ni = 0; ni < n; ++ni) { if (p[ni] == NL) ptr[tlen++] = NUL; else ptr[tlen++] = p[ni]; } ptr[tlen++] = NL; read_buf_col = 0; if (++read_buf_lnum > from) { /* When the last line didn't have an * end-of-line don't add it now either. */ if (!curbuf->b_p_eol) --tlen; size = tlen; break; } } } } } else { /* * Read bytes from the file. */ size = read_eintr(fd, ptr, size); } if (size <= 0) { if (size < 0) /* read error */ error = TRUE; #ifdef FEAT_MBYTE else if (conv_restlen > 0) { /* * Reached end-of-file but some trailing bytes could * not be converted. Truncated file? */ /* When we did a conversion report an error. */ if (fio_flags != 0 # ifdef USE_ICONV || iconv_fd != (iconv_t)-1 # endif ) { if (conv_error == 0) conv_error = curbuf->b_ml.ml_line_count - linecnt + 1; } /* Remember the first linenr with an illegal byte */ else if (illegal_byte == 0) illegal_byte = curbuf->b_ml.ml_line_count - linecnt + 1; if (bad_char_behavior == BAD_DROP) { *(ptr - conv_restlen) = NUL; conv_restlen = 0; } else { /* Replace the trailing bytes with the replacement * character if we were converting; if we weren't, * leave the UTF8 checking code to do it, as it * works slightly differently. */ if (bad_char_behavior != BAD_KEEP && (fio_flags != 0 # ifdef USE_ICONV || iconv_fd != (iconv_t)-1 # endif )) { while (conv_restlen > 0) { *(--ptr) = bad_char_behavior; --conv_restlen; } } fio_flags = 0; /* don't convert this */ # ifdef USE_ICONV if (iconv_fd != (iconv_t)-1) { iconv_close(iconv_fd); iconv_fd = (iconv_t)-1; } # endif } } #endif } #ifdef FEAT_CRYPT /* * At start of file: Check for magic number of encryption. */ if (filesize == 0) cryptkey = check_for_cryptkey(cryptkey, ptr, &size, &filesize, newfile, sfname, &did_ask_for_key); /* * Decrypt the read bytes. */ if (cryptkey != NULL && size > 0) crypt_decode(ptr, size); #endif } skip_read = FALSE; #ifdef FEAT_MBYTE /* * At start of file (or after crypt magic number): Check for BOM. * Also check for a BOM for other Unicode encodings, but not after * converting with 'charconvert' or when a BOM has already been * found. */ if ((filesize == 0 # ifdef FEAT_CRYPT || (filesize == (CRYPT_MAGIC_LEN + crypt_salt_len[use_crypt_method] + crypt_seed_len[use_crypt_method]) && cryptkey != NULL) # endif ) && (fio_flags == FIO_UCSBOM || (!curbuf->b_p_bomb && tmpname == NULL && (*fenc == 'u' || (*fenc == NUL && enc_utf8))))) { char_u *ccname; int blen; /* no BOM detection in a short file or in binary mode */ if (size < 2 || curbuf->b_p_bin) ccname = NULL; else ccname = check_for_bom(ptr, size, &blen, fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc)); if (ccname != NULL) { /* Remove BOM from the text */ filesize += blen; size -= blen; mch_memmove(ptr, ptr + blen, (size_t)size); if (set_options) { curbuf->b_p_bomb = TRUE; curbuf->b_start_bomb = TRUE; } } if (fio_flags == FIO_UCSBOM) { if (ccname == NULL) { /* No BOM detected: retry with next encoding. */ advance_fenc = TRUE; } else { /* BOM detected: set "fenc" and jump back */ if (fenc_alloced) vim_free(fenc); fenc = ccname; fenc_alloced = FALSE; } /* retry reading without getting new bytes or rewinding */ skip_read = TRUE; goto retry; } } /* Include not converted bytes. */ ptr -= conv_restlen; size += conv_restlen; conv_restlen = 0; #endif /* * Break here for a read error or end-of-file. */ if (size <= 0) break; #ifdef FEAT_MBYTE # ifdef USE_ICONV if (iconv_fd != (iconv_t)-1) { /* * Attempt conversion of the read bytes to 'encoding' using * iconv(). */ const char *fromp; char *top; size_t from_size; size_t to_size; fromp = (char *)ptr; from_size = size; ptr += size; top = (char *)ptr; to_size = real_size - size; /* * If there is conversion error or not enough room try using * another conversion. Except for when there is no * alternative (help files). */ while ((iconv(iconv_fd, (void *)&fromp, &from_size, &top, &to_size) == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL) || from_size > CONV_RESTLEN) { if (can_retry) goto rewind_retry; if (conv_error == 0) conv_error = readfile_linenr(linecnt, ptr, (char_u *)top); /* Deal with a bad byte and continue with the next. */ ++fromp; --from_size; if (bad_char_behavior == BAD_KEEP) { *top++ = *(fromp - 1); --to_size; } else if (bad_char_behavior != BAD_DROP) { *top++ = bad_char_behavior; --to_size; } } if (from_size > 0) { /* Some remaining characters, keep them for the next * round. */ mch_memmove(conv_rest, (char_u *)fromp, from_size); conv_restlen = (int)from_size; } /* move the linerest to before the converted characters */ line_start = ptr - linerest; mch_memmove(line_start, buffer, (size_t)linerest); size = (long)((char_u *)top - ptr); } # endif # ifdef WIN3264 if (fio_flags & FIO_CODEPAGE) { char_u *src, *dst; WCHAR ucs2buf[3]; int ucs2len; int codepage = FIO_GET_CP(fio_flags); int bytelen; int found_bad; char replstr[2]; /* * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or * a codepage, using standard MS-Windows functions. This * requires two steps: * 1. convert from 'fileencoding' to ucs-2 * 2. convert from ucs-2 to 'encoding' * * Because there may be illegal bytes AND an incomplete byte * sequence at the end, we may have to do the conversion one * character at a time to get it right. */ /* Replacement string for WideCharToMultiByte(). */ if (bad_char_behavior > 0) replstr[0] = bad_char_behavior; else replstr[0] = '?'; replstr[1] = NUL; /* * Move the bytes to the end of the buffer, so that we have * room to put the result at the start. */ src = ptr + real_size - size; mch_memmove(src, ptr, size); /* * Do the conversion. */ dst = ptr; size = size; while (size > 0) { found_bad = FALSE; # ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */ if (codepage == CP_UTF8) { /* Handle CP_UTF8 input ourselves to be able to handle * trailing bytes properly. * Get one UTF-8 character from src. */ bytelen = (int)utf_ptr2len_len(src, size); if (bytelen > size) { /* Only got some bytes of a character. Normally * it's put in "conv_rest", but if it's too long * deal with it as if they were illegal bytes. */ if (bytelen <= CONV_RESTLEN) break; /* weird overlong byte sequence */ bytelen = size; found_bad = TRUE; } else { int u8c = utf_ptr2char(src); if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1)) found_bad = TRUE; ucs2buf[0] = u8c; ucs2len = 1; } } else # endif { /* We don't know how long the byte sequence is, try * from one to three bytes. */ for (bytelen = 1; bytelen <= size && bytelen <= 3; ++bytelen) { ucs2len = MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, (LPCSTR)src, bytelen, ucs2buf, 3); if (ucs2len > 0) break; } if (ucs2len == 0) { /* If we have only one byte then it's probably an * incomplete byte sequence. Otherwise discard * one byte as a bad character. */ if (size == 1) break; found_bad = TRUE; bytelen = 1; } } if (!found_bad) { int i; /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */ if (enc_utf8) { /* From UCS-2 to UTF-8. Cannot fail. */ for (i = 0; i < ucs2len; ++i) dst += utf_char2bytes(ucs2buf[i], dst); } else { BOOL bad = FALSE; int dstlen; /* From UCS-2 to "enc_codepage". If the * conversion uses the default character "?", * the data doesn't fit in this encoding. */ dstlen = WideCharToMultiByte(enc_codepage, 0, (LPCWSTR)ucs2buf, ucs2len, (LPSTR)dst, (int)(src - dst), replstr, &bad); if (bad) found_bad = TRUE; else dst += dstlen; } } if (found_bad) { /* Deal with bytes we can't convert. */ if (can_retry) goto rewind_retry; if (conv_error == 0) conv_error = readfile_linenr(linecnt, ptr, dst); if (bad_char_behavior != BAD_DROP) { if (bad_char_behavior == BAD_KEEP) { mch_memmove(dst, src, bytelen); dst += bytelen; } else *dst++ = bad_char_behavior; } } src += bytelen; size -= bytelen; } if (size > 0) { /* An incomplete byte sequence remaining. */ mch_memmove(conv_rest, src, size); conv_restlen = size; } /* The new size is equal to how much "dst" was advanced. */ size = (long)(dst - ptr); } else # endif # ifdef MACOS_CONVERT if (fio_flags & FIO_MACROMAN) { /* * Conversion from Apple MacRoman char encoding to UTF-8 or * latin1. This is in os_mac_conv.c. */ if (macroman2enc(ptr, &size, real_size) == FAIL) goto rewind_retry; } else # endif if (fio_flags != 0) { int u8c; char_u *dest; char_u *tail = NULL; /* * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8. * "enc_utf8" not set: Convert Unicode to Latin1. * Go from end to start through the buffer, because the number * of bytes may increase. * "dest" points to after where the UTF-8 bytes go, "p" points * to after the next character to convert. */ dest = ptr + real_size; if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8) { p = ptr + size; if (fio_flags == FIO_UTF8) { /* Check for a trailing incomplete UTF-8 sequence */ tail = ptr + size - 1; while (tail > ptr && (*tail & 0xc0) == 0x80) --tail; if (tail + utf_byte2len(*tail) <= ptr + size) tail = NULL; else p = tail; } } else if (fio_flags & (FIO_UCS2 | FIO_UTF16)) { /* Check for a trailing byte */ p = ptr + (size & ~1); if (size & 1) tail = p; if ((fio_flags & FIO_UTF16) && p > ptr) { /* Check for a trailing leading word */ if (fio_flags & FIO_ENDIAN_L) { u8c = (*--p << 8); u8c += *--p; } else { u8c = *--p; u8c += (*--p << 8); } if (u8c >= 0xd800 && u8c <= 0xdbff) tail = p; else p += 2; } } else /* FIO_UCS4 */ { /* Check for trailing 1, 2 or 3 bytes */ p = ptr + (size & ~3); if (size & 3) tail = p; } /* If there is a trailing incomplete sequence move it to * conv_rest[]. */ if (tail != NULL) { conv_restlen = (int)((ptr + size) - tail); mch_memmove(conv_rest, (char_u *)tail, conv_restlen); size -= conv_restlen; } while (p > ptr) { if (fio_flags & FIO_LATIN1) u8c = *--p; else if (fio_flags & (FIO_UCS2 | FIO_UTF16)) { if (fio_flags & FIO_ENDIAN_L) { u8c = (*--p << 8); u8c += *--p; } else { u8c = *--p; u8c += (*--p << 8); } if ((fio_flags & FIO_UTF16) && u8c >= 0xdc00 && u8c <= 0xdfff) { int u16c; if (p == ptr) { /* Missing leading word. */ if (can_retry) goto rewind_retry; if (conv_error == 0) conv_error = readfile_linenr(linecnt, ptr, p); if (bad_char_behavior == BAD_DROP) continue; if (bad_char_behavior != BAD_KEEP) u8c = bad_char_behavior; } /* found second word of double-word, get the first * word and compute the resulting character */ if (fio_flags & FIO_ENDIAN_L) { u16c = (*--p << 8); u16c += *--p; } else { u16c = *--p; u16c += (*--p << 8); } u8c = 0x10000 + ((u16c & 0x3ff) << 10) + (u8c & 0x3ff); /* Check if the word is indeed a leading word. */ if (u16c < 0xd800 || u16c > 0xdbff) { if (can_retry) goto rewind_retry; if (conv_error == 0) conv_error = readfile_linenr(linecnt, ptr, p); if (bad_char_behavior == BAD_DROP) continue; if (bad_char_behavior != BAD_KEEP) u8c = bad_char_behavior; } } } else if (fio_flags & FIO_UCS4) { if (fio_flags & FIO_ENDIAN_L) { u8c = (*--p << 24); u8c += (*--p << 16); u8c += (*--p << 8); u8c += *--p; } else /* big endian */ { u8c = *--p; u8c += (*--p << 8); u8c += (*--p << 16); u8c += (*--p << 24); } } else /* UTF-8 */ { if (*--p < 0x80) u8c = *p; else { len = utf_head_off(ptr, p); p -= len; u8c = utf_ptr2char(p); if (len == 0) { /* Not a valid UTF-8 character, retry with * another fenc when possible, otherwise just * report the error. */ if (can_retry) goto rewind_retry; if (conv_error == 0) conv_error = readfile_linenr(linecnt, ptr, p); if (bad_char_behavior == BAD_DROP) continue; if (bad_char_behavior != BAD_KEEP) u8c = bad_char_behavior; } } } if (enc_utf8) /* produce UTF-8 */ { dest -= utf_char2len(u8c); (void)utf_char2bytes(u8c, dest); } else /* produce Latin1 */ { --dest; if (u8c >= 0x100) { /* character doesn't fit in latin1, retry with * another fenc when possible, otherwise just * report the error. */ if (can_retry) goto rewind_retry; if (conv_error == 0) conv_error = readfile_linenr(linecnt, ptr, p); if (bad_char_behavior == BAD_DROP) ++dest; else if (bad_char_behavior == BAD_KEEP) *dest = u8c; else if (eap != NULL && eap->bad_char != 0) *dest = bad_char_behavior; else *dest = 0xBF; } else *dest = u8c; } } /* move the linerest to before the converted characters */ line_start = dest - linerest; mch_memmove(line_start, buffer, (size_t)linerest); size = (long)((ptr + real_size) - dest); ptr = dest; } else if (enc_utf8 && !curbuf->b_p_bin) { int incomplete_tail = FALSE; /* Reading UTF-8: Check if the bytes are valid UTF-8. */ for (p = ptr; ; ++p) { int todo = (int)((ptr + size) - p); int l; if (todo <= 0) break; if (*p >= 0x80) { /* A length of 1 means it's an illegal byte. Accept * an incomplete character at the end though, the next * read() will get the next bytes, we'll check it * then. */ l = utf_ptr2len_len(p, todo); if (l > todo && !incomplete_tail) { /* Avoid retrying with a different encoding when * a truncated file is more likely, or attempting * to read the rest of an incomplete sequence when * we have already done so. */ if (p > ptr || filesize > 0) incomplete_tail = TRUE; /* Incomplete byte sequence, move it to conv_rest[] * and try to read the rest of it, unless we've * already done so. */ if (p > ptr) { conv_restlen = todo; mch_memmove(conv_rest, p, conv_restlen); size -= conv_restlen; break; } } if (l == 1 || l > todo) { /* Illegal byte. If we can try another encoding * do that, unless at EOF where a truncated * file is more likely than a conversion error. */ if (can_retry && !incomplete_tail) break; # ifdef USE_ICONV /* When we did a conversion report an error. */ if (iconv_fd != (iconv_t)-1 && conv_error == 0) conv_error = readfile_linenr(linecnt, ptr, p); # endif /* Remember the first linenr with an illegal byte */ if (conv_error == 0 && illegal_byte == 0) illegal_byte = readfile_linenr(linecnt, ptr, p); /* Drop, keep or replace the bad byte. */ if (bad_char_behavior == BAD_DROP) { mch_memmove(p, p + 1, todo - 1); --p; --size; } else if (bad_char_behavior != BAD_KEEP) *p = bad_char_behavior; } else p += l - 1; } } if (p < ptr + size && !incomplete_tail) { /* Detected a UTF-8 error. */ rewind_retry: /* Retry reading with another conversion. */ # if defined(FEAT_EVAL) && defined(USE_ICONV) if (*p_ccv != NUL && iconv_fd != (iconv_t)-1) /* iconv() failed, try 'charconvert' */ did_iconv = TRUE; else # endif /* use next item from 'fileencodings' */ advance_fenc = TRUE; file_rewind = TRUE; goto retry; } } #endif /* count the number of characters (after conversion!) */ filesize += size; /* * when reading the first part of a file: guess EOL type */ if (fileformat == EOL_UNKNOWN) { /* First try finding a NL, for Dos and Unix */ if (try_dos || try_unix) { for (p = ptr; p < ptr + size; ++p) { if (*p == NL) { if (!try_unix || (try_dos && p > ptr && p[-1] == CAR)) fileformat = EOL_DOS; else fileformat = EOL_UNIX; break; } } /* Don't give in to EOL_UNIX if EOL_MAC is more likely */ if (fileformat == EOL_UNIX && try_mac) { /* Need to reset the counters when retrying fenc. */ try_mac = 1; try_unix = 1; for (; p >= ptr && *p != CAR; p--) ; if (p >= ptr) { for (p = ptr; p < ptr + size; ++p) { if (*p == NL) try_unix++; else if (*p == CAR) try_mac++; } if (try_mac > try_unix) fileformat = EOL_MAC; } } } /* No NL found: may use Mac format */ if (fileformat == EOL_UNKNOWN && try_mac) fileformat = EOL_MAC; /* Still nothing found? Use first format in 'ffs' */ if (fileformat == EOL_UNKNOWN) fileformat = default_fileformat(); /* if editing a new file: may set p_tx and p_ff */ if (set_options) set_fileformat(fileformat, OPT_LOCAL); } } /* * This loop is executed once for every character read. * Keep it fast! */ if (fileformat == EOL_MAC) { --ptr; while (++ptr, --size >= 0) { /* catch most common case first */ if ((c = *ptr) != NUL && c != CAR && c != NL) continue; if (c == NUL) *ptr = NL; /* NULs are replaced by newlines! */ else if (c == NL) *ptr = CAR; /* NLs are replaced by CRs! */ else { if (skip_count == 0) { *ptr = NUL; /* end of line */ len = (colnr_T) (ptr - line_start + 1); if (ml_append(lnum, line_start, len, newfile) == FAIL) { error = TRUE; break; } #ifdef FEAT_PERSISTENT_UNDO if (read_undo_file) sha256_update(&sha_ctx, line_start, len); #endif ++lnum; if (--read_count == 0) { error = TRUE; /* break loop */ line_start = ptr; /* nothing left to write */ break; } } else --skip_count; line_start = ptr + 1; } } } else { --ptr; while (++ptr, --size >= 0) { if ((c = *ptr) != NUL && c != NL) /* catch most common case */ continue; if (c == NUL) *ptr = NL; /* NULs are replaced by newlines! */ else { if (skip_count == 0) { *ptr = NUL; /* end of line */ len = (colnr_T)(ptr - line_start + 1); if (fileformat == EOL_DOS) { if (ptr[-1] == CAR) /* remove CR */ { ptr[-1] = NUL; --len; } /* * Reading in Dos format, but no CR-LF found! * When 'fileformats' includes "unix", delete all * the lines read so far and start all over again. * Otherwise give an error message later. */ else if (ff_error != EOL_DOS) { if ( try_unix && !read_stdin && (read_buffer || lseek(fd, (off_t)0L, SEEK_SET) == 0)) { fileformat = EOL_UNIX; if (set_options) set_fileformat(EOL_UNIX, OPT_LOCAL); file_rewind = TRUE; keep_fileformat = TRUE; goto retry; } ff_error = EOL_DOS; } } if (ml_append(lnum, line_start, len, newfile) == FAIL) { error = TRUE; break; } #ifdef FEAT_PERSISTENT_UNDO if (read_undo_file) sha256_update(&sha_ctx, line_start, len); #endif ++lnum; if (--read_count == 0) { error = TRUE; /* break loop */ line_start = ptr; /* nothing left to write */ break; } } else --skip_count; line_start = ptr + 1; } } } linerest = (long)(ptr - line_start); ui_breakcheck(); } failed: /* not an error, max. number of lines reached */ if (error && read_count == 0) error = FALSE; /* * If we get EOF in the middle of a line, note the fact and * complete the line ourselves. * In Dos format ignore a trailing CTRL-Z, unless 'binary' set. */ if (!error && !got_int && linerest != 0 && !(!curbuf->b_p_bin && fileformat == EOL_DOS && *line_start == Ctrl_Z && ptr == line_start + 1)) { /* remember for when writing */ if (set_options) curbuf->b_p_eol = FALSE; *ptr = NUL; len = (colnr_T)(ptr - line_start + 1); if (ml_append(lnum, line_start, len, newfile) == FAIL) error = TRUE; else { #ifdef FEAT_PERSISTENT_UNDO if (read_undo_file) sha256_update(&sha_ctx, line_start, len); #endif read_no_eol_lnum = ++lnum; } } if (set_options) save_file_ff(curbuf); /* remember the current file format */ #ifdef FEAT_CRYPT crypt_method_used = use_crypt_method; if (cryptkey != NULL) { crypt_pop_state(); if (cryptkey != curbuf->b_p_key) free_crypt_key(cryptkey); /* don't set cryptkey to NULL, it's used below as a flag that * encryption was used */ } #endif #ifdef FEAT_MBYTE /* If editing a new file: set 'fenc' for the current buffer. * Also for ":read ++edit file". */ if (set_options) set_string_option_direct((char_u *)"fenc", -1, fenc, OPT_FREE|OPT_LOCAL, 0); if (fenc_alloced) vim_free(fenc); # ifdef USE_ICONV if (iconv_fd != (iconv_t)-1) { iconv_close(iconv_fd); iconv_fd = (iconv_t)-1; } # endif #endif if (!read_buffer && !read_stdin) close(fd); /* errors are ignored */ #ifdef HAVE_FD_CLOEXEC else { int fdflags = fcntl(fd, F_GETFD); if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0) fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC); } #endif vim_free(buffer); #ifdef HAVE_DUP if (read_stdin) { /* Use stderr for stdin, makes shell commands work. */ close(0); ignored = dup(2); } #endif #ifdef FEAT_MBYTE if (tmpname != NULL) { mch_remove(tmpname); /* delete converted file */ vim_free(tmpname); } #endif --no_wait_return; /* may wait for return now */ /* * In recovery mode everything but autocommands is skipped. */ if (!recoverymode) { /* need to delete the last line, which comes from the empty buffer */ if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY)) { #ifdef FEAT_NETBEANS_INTG netbeansFireChanges = 0; #endif ml_delete(curbuf->b_ml.ml_line_count, FALSE); #ifdef FEAT_NETBEANS_INTG netbeansFireChanges = 1; #endif --linecnt; } linecnt = curbuf->b_ml.ml_line_count - linecnt; if (filesize == 0) linecnt = 0; if (newfile || read_buffer) { redraw_curbuf_later(NOT_VALID); #ifdef FEAT_DIFF /* After reading the text into the buffer the diff info needs to * be updated. */ diff_invalidate(curbuf); #endif #ifdef FEAT_FOLDING /* All folds in the window are invalid now. Mark them for update * before triggering autocommands. */ foldUpdateAll(curwin); #endif } else if (linecnt) /* appended at least one line */ appended_lines_mark(from, linecnt); #ifndef ALWAYS_USE_GUI /* * If we were reading from the same terminal as where messages go, * the screen will have been messed up. * Switch on raw mode now and clear the screen. */ if (read_stdin) { settmode(TMODE_RAW); /* set to raw mode */ starttermcap(); screenclear(); } #endif if (got_int) { if (!(flags & READ_DUMMY)) { filemess(curbuf, sfname, (char_u *)_(e_interr), 0); if (newfile) curbuf->b_p_ro = TRUE; /* must use "w!" now */ } msg_scroll = msg_save; #ifdef FEAT_VIMINFO check_marks_read(); #endif return OK; /* an interrupt isn't really an error */ } if (!filtering && !(flags & READ_DUMMY)) { msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */ c = FALSE; #ifdef UNIX # ifdef S_ISFIFO if (S_ISFIFO(perm)) /* fifo or socket */ { STRCAT(IObuff, _("[fifo/socket]")); c = TRUE; } # else # ifdef S_IFIFO if ((perm & S_IFMT) == S_IFIFO) /* fifo */ { STRCAT(IObuff, _("[fifo]")); c = TRUE; } # endif # ifdef S_IFSOCK if ((perm & S_IFMT) == S_IFSOCK) /* or socket */ { STRCAT(IObuff, _("[socket]")); c = TRUE; } # endif # endif # ifdef OPEN_CHR_FILES if (S_ISCHR(perm)) /* or character special */ { STRCAT(IObuff, _("[character special]")); c = TRUE; } # endif #endif if (curbuf->b_p_ro) { STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]")); c = TRUE; } if (read_no_eol_lnum) { msg_add_eol(); c = TRUE; } if (ff_error == EOL_DOS) { STRCAT(IObuff, _("[CR missing]")); c = TRUE; } if (split) { STRCAT(IObuff, _("[long lines split]")); c = TRUE; } #ifdef FEAT_MBYTE if (notconverted) { STRCAT(IObuff, _("[NOT converted]")); c = TRUE; } else if (converted) { STRCAT(IObuff, _("[converted]")); c = TRUE; } #endif #ifdef FEAT_CRYPT if (cryptkey != NULL) { if (crypt_method_used == 1) STRCAT(IObuff, _("[blowfish]")); else STRCAT(IObuff, _("[crypted]")); c = TRUE; } #endif #ifdef FEAT_MBYTE if (conv_error != 0) { sprintf((char *)IObuff + STRLEN(IObuff), _("[CONVERSION ERROR in line %ld]"), (long)conv_error); c = TRUE; } else if (illegal_byte > 0) { sprintf((char *)IObuff + STRLEN(IObuff), _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte); c = TRUE; } else #endif if (error) { STRCAT(IObuff, _("[READ ERRORS]")); c = TRUE; } if (msg_add_fileformat(fileformat)) c = TRUE; #ifdef FEAT_CRYPT if (cryptkey != NULL) msg_add_lines(c, (long)linecnt, filesize - CRYPT_MAGIC_LEN - crypt_salt_len[use_crypt_method] - crypt_seed_len[use_crypt_method]); else #endif msg_add_lines(c, (long)linecnt, filesize); vim_free(keep_msg); keep_msg = NULL; msg_scrolled_ign = TRUE; #ifdef ALWAYS_USE_GUI /* Don't show the message when reading stdin, it would end up in a * message box (which might be shown when exiting!) */ if (read_stdin || read_buffer) p = msg_may_trunc(FALSE, IObuff); else #endif p = msg_trunc_attr(IObuff, FALSE, 0); if (read_stdin || read_buffer || restart_edit != 0 || (msg_scrolled != 0 && !need_wait_return)) /* Need to repeat the message after redrawing when: * - When reading from stdin (the screen will be cleared next). * - When restart_edit is set (otherwise there will be a delay * before redrawing). * - When the screen was scrolled but there is no wait-return * prompt. */ set_keep_msg(p, 0); msg_scrolled_ign = FALSE; } /* with errors writing the file requires ":w!" */ if (newfile && (error #ifdef FEAT_MBYTE || conv_error != 0 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP) #endif )) curbuf->b_p_ro = TRUE; u_clearline(); /* cannot use "U" command after adding lines */ /* * In Ex mode: cursor at last new line. * Otherwise: cursor at first new line. */ if (exmode_active) curwin->w_cursor.lnum = from + linecnt; else curwin->w_cursor.lnum = from + 1; check_cursor_lnum(); beginline(BL_WHITE | BL_FIX); /* on first non-blank */ /* * Set '[ and '] marks to the newly read lines. */ curbuf->b_op_start.lnum = from + 1; curbuf->b_op_start.col = 0; curbuf->b_op_end.lnum = from + linecnt; curbuf->b_op_end.col = 0; #ifdef WIN32 /* * Work around a weird problem: When a file has two links (only * possible on NTFS) and we write through one link, then stat() it * through the other link, the timestamp information may be wrong. * It's correct again after reading the file, thus reset the timestamp * here. */ if (newfile && !read_stdin && !read_buffer && mch_stat((char *)fname, &st) >= 0) { buf_store_time(curbuf, &st, fname); curbuf->b_mtime_read = curbuf->b_mtime; } #endif } msg_scroll = msg_save; #ifdef FEAT_VIMINFO /* * Get the marks before executing autocommands, so they can be used there. */ check_marks_read(); #endif /* * Trick: We remember if the last line of the read didn't have * an eol even when 'binary' is off, for when writing it again with * 'binary' on. This is required for * ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work. */ curbuf->b_no_eol_lnum = read_no_eol_lnum; /* When reloading a buffer put the cursor at the first line that is * different. */ if (flags & READ_KEEP_UNDO) u_find_first_changed(); #ifdef FEAT_PERSISTENT_UNDO /* * When opening a new file locate undo info and read it. */ if (read_undo_file) { char_u hash[UNDO_HASH_SIZE]; sha256_finish(&sha_ctx, hash); u_read_undo(NULL, hash, fname); } #endif #ifdef FEAT_AUTOCMD if (!read_stdin && !read_buffer) { int m = msg_scroll; int n = msg_scrolled; /* Save the fileformat now, otherwise the buffer will be considered * modified if the format/encoding was automatically detected. */ if (set_options) save_file_ff(curbuf); /* * The output from the autocommands should not overwrite anything and * should not be overwritten: Set msg_scroll, restore its value if no * output was done. */ msg_scroll = TRUE; if (filtering) apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname, FALSE, curbuf, eap); else if (newfile) apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname, FALSE, curbuf, eap); else apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname, FALSE, NULL, eap); if (msg_scrolled == n) msg_scroll = m; # ifdef FEAT_EVAL if (aborting()) /* autocmds may abort script processing */ return FAIL; # endif } #endif if (recoverymode && error) return FAIL; return OK; } #ifdef OPEN_CHR_FILES /* * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+", * which is the name of files used for process substitution output by * some shells on some operating systems, e.g., bash on SunOS. * Do not accept "/dev/fd/[012]", opening these may hang Vim. */ static int is_dev_fd_file(fname) char_u *fname; { return (STRNCMP(fname, "/dev/fd/", 8) == 0 && VIM_ISDIGIT(fname[8]) && *skipdigits(fname + 9) == NUL && (fname[9] != NUL || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2'))); } #endif #ifdef FEAT_MBYTE /* * From the current line count and characters read after that, estimate the * line number where we are now. * Used for error messages that include a line number. */ static linenr_T readfile_linenr(linecnt, p, endp) linenr_T linecnt; /* line count before reading more bytes */ char_u *p; /* start of more bytes read */ char_u *endp; /* end of more bytes read */ { char_u *s; linenr_T lnum; lnum = curbuf->b_ml.ml_line_count - linecnt + 1; for (s = p; s < endp; ++s) if (*s == '\n') ++lnum; return lnum; } #endif /* * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be * equal to the buffer "buf". Used for calling readfile(). * Returns OK or FAIL. */ int prep_exarg(eap, buf) exarg_T *eap; buf_T *buf; { eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff) #ifdef FEAT_MBYTE + STRLEN(buf->b_p_fenc) #endif + 15)); if (eap->cmd == NULL) return FAIL; #ifdef FEAT_MBYTE sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc); eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff); eap->bad_char = buf->b_bad_char; #else sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff); #endif eap->force_ff = 7; eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN; eap->read_edit = FALSE; eap->forceit = FALSE; return OK; } #ifdef FEAT_MBYTE /* * Find next fileencoding to use from 'fileencodings'. * "pp" points to fenc_next. It's advanced to the next item. * When there are no more items, an empty string is returned and *pp is set to * NULL. * When *pp is not set to NULL, the result is in allocated memory. */ static char_u * next_fenc(pp) char_u **pp; { char_u *p; char_u *r; if (**pp == NUL) { *pp = NULL; return (char_u *)""; } p = vim_strchr(*pp, ','); if (p == NULL) { r = enc_canonize(*pp); *pp += STRLEN(*pp); } else { r = vim_strnsave(*pp, (int)(p - *pp)); *pp = p + 1; if (r != NULL) { p = enc_canonize(r); vim_free(r); r = p; } } if (r == NULL) /* out of memory */ { r = (char_u *)""; *pp = NULL; } return r; } # ifdef FEAT_EVAL /* * Convert a file with the 'charconvert' expression. * This closes the file which is to be read, converts it and opens the * resulting file for reading. * Returns name of the resulting converted file (the caller should delete it * after reading it). * Returns NULL if the conversion failed ("*fdp" is not set) . */ static char_u * readfile_charconvert(fname, fenc, fdp) char_u *fname; /* name of input file */ char_u *fenc; /* converted from */ int *fdp; /* in/out: file descriptor of file */ { char_u *tmpname; char_u *errmsg = NULL; tmpname = vim_tempname('r'); if (tmpname == NULL) errmsg = (char_u *)_("Can't find temp file for conversion"); else { close(*fdp); /* close the input file, ignore errors */ *fdp = -1; if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc, fname, tmpname) == FAIL) errmsg = (char_u *)_("Conversion with 'charconvert' failed"); if (errmsg == NULL && (*fdp = mch_open((char *)tmpname, O_RDONLY | O_EXTRA, 0)) < 0) errmsg = (char_u *)_("can't read output of 'charconvert'"); } if (errmsg != NULL) { /* Don't use emsg(), it breaks mappings, the retry with * another type of conversion might still work. */ MSG(errmsg); if (tmpname != NULL) { mch_remove(tmpname); /* delete converted file */ vim_free(tmpname); tmpname = NULL; } } /* If the input file is closed, open it (caller should check for error). */ if (*fdp < 0) *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0); return tmpname; } # endif #endif #ifdef FEAT_VIMINFO /* * Read marks for the current buffer from the viminfo file, when we support * buffer marks and the buffer has a name. */ static void check_marks_read() { if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0 && curbuf->b_ffname != NULL) read_viminfo(NULL, VIF_WANT_MARKS); /* Always set b_marks_read; needed when 'viminfo' is changed to include * the ' parameter after opening a buffer. */ curbuf->b_marks_read = TRUE; } #endif #if defined(FEAT_CRYPT) || defined(PROTO) /* * Get the crypt method used for a file from "ptr[len]", the magic text at the * start of the file. * Returns -1 when no encryption used. */ static int crypt_method_from_magic(ptr, len) char *ptr; int len; { int i; for (i = 0; i < (int)(sizeof(crypt_magic) / sizeof(crypt_magic[0])); i++) { if (len < (CRYPT_MAGIC_LEN + crypt_salt_len[i] + crypt_seed_len[i])) continue; if (memcmp(ptr, crypt_magic[i], CRYPT_MAGIC_LEN) == 0) return i; } i = (int)STRLEN(crypt_magic_head); if (len >= i && memcmp(ptr, crypt_magic_head, i) == 0) EMSG(_("E821: File is encrypted with unknown method")); return -1; } /* * Check for magic number used for encryption. Applies to the current buffer. * If found, the magic number is removed from ptr[*sizep] and *sizep and * *filesizep are updated. * Return the (new) encryption key, NULL for no encryption. */ static char_u * check_for_cryptkey(cryptkey, ptr, sizep, filesizep, newfile, fname, did_ask) char_u *cryptkey; /* previous encryption key or NULL */ char_u *ptr; /* pointer to read bytes */ long *sizep; /* length of read bytes */ off_t *filesizep; /* nr of bytes used from file */ int newfile; /* editing a new buffer */ char_u *fname; /* file name to display */ int *did_ask; /* flag: whether already asked for key */ { int method = crypt_method_from_magic((char *)ptr, *sizep); if (method >= 0) { set_crypt_method(curbuf, method); if (method > 0) (void)blowfish_self_test(); if (cryptkey == NULL && !*did_ask) { if (*curbuf->b_p_key) cryptkey = curbuf->b_p_key; else { /* When newfile is TRUE, store the typed key in the 'key' * option and don't free it. bf needs hash of the key saved. * Don't ask for the key again when first time Enter was hit. * Happens when retrying to detect encoding. */ smsg((char_u *)_(need_key_msg), fname); msg_scroll = TRUE; cryptkey = get_crypt_key(newfile, FALSE); *did_ask = TRUE; /* check if empty key entered */ if (cryptkey != NULL && *cryptkey == NUL) { if (cryptkey != curbuf->b_p_key) vim_free(cryptkey); cryptkey = NULL; } } } if (cryptkey != NULL) { int seed_len = crypt_seed_len[method]; int salt_len = crypt_salt_len[method]; crypt_push_state(); use_crypt_method = method; if (method == 0) crypt_init_keys(cryptkey); else { bf_key_init(cryptkey, ptr + CRYPT_MAGIC_LEN, salt_len); bf_ofb_init(ptr + CRYPT_MAGIC_LEN + salt_len, seed_len); } /* Remove magic number from the text */ *filesizep += CRYPT_MAGIC_LEN + salt_len + seed_len; *sizep -= CRYPT_MAGIC_LEN + salt_len + seed_len; mch_memmove(ptr, ptr + CRYPT_MAGIC_LEN + salt_len + seed_len, (size_t)*sizep); } } /* When starting to edit a new file which does not have encryption, clear * the 'key' option, except when starting up (called with -x argument) */ else if (newfile && *curbuf->b_p_key != NUL && !starting) set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL); return cryptkey; } /* * Check for magic number used for encryption. Applies to the current buffer. * If found and decryption is possible returns OK; */ int prepare_crypt_read(fp) FILE *fp; { int method; char_u buffer[CRYPT_MAGIC_LEN + CRYPT_SALT_LEN_MAX + CRYPT_SEED_LEN_MAX + 2]; if (fread(buffer, CRYPT_MAGIC_LEN, 1, fp) != 1) return FAIL; method = crypt_method_from_magic((char *)buffer, CRYPT_MAGIC_LEN + CRYPT_SEED_LEN_MAX + CRYPT_SALT_LEN_MAX); if (method < 0 || method != get_crypt_method(curbuf)) return FAIL; crypt_push_state(); if (method == 0) crypt_init_keys(curbuf->b_p_key); else { int salt_len = crypt_salt_len[method]; int seed_len = crypt_seed_len[method]; if (fread(buffer, salt_len + seed_len, 1, fp) != 1) return FAIL; bf_key_init(curbuf->b_p_key, buffer, salt_len); bf_ofb_init(buffer + salt_len, seed_len); } return OK; } /* * Prepare for writing encrypted bytes for buffer "buf". * Returns a pointer to an allocated header of length "*lenp". * When out of memory returns NULL. * Otherwise calls crypt_push_state(), call crypt_pop_state() later. */ char_u * prepare_crypt_write(buf, lenp) buf_T *buf; int *lenp; { char_u *header; int seed_len = crypt_seed_len[get_crypt_method(buf)]; int salt_len = crypt_salt_len[get_crypt_method(buf)]; char_u *salt; char_u *seed; header = alloc_clear(CRYPT_MAGIC_LEN + CRYPT_SALT_LEN_MAX + CRYPT_SEED_LEN_MAX + 2); if (header != NULL) { crypt_push_state(); use_crypt_method = get_crypt_method(buf); /* select zip or blowfish */ vim_strncpy(header, (char_u *)crypt_magic[use_crypt_method], CRYPT_MAGIC_LEN); if (use_crypt_method == 0) crypt_init_keys(buf->b_p_key); else { /* Using blowfish, add salt and seed. */ salt = header + CRYPT_MAGIC_LEN; seed = salt + salt_len; sha2_seed(salt, salt_len, seed, seed_len); bf_key_init(buf->b_p_key, salt, salt_len); bf_ofb_init(seed, seed_len); } } *lenp = CRYPT_MAGIC_LEN + salt_len + seed_len; return header; } #endif /* FEAT_CRYPT */ #ifdef UNIX static void set_file_time(fname, atime, mtime) char_u *fname; time_t atime; /* access time */ time_t mtime; /* modification time */ { # if defined(HAVE_UTIME) && defined(HAVE_UTIME_H) struct utimbuf buf; buf.actime = atime; buf.modtime = mtime; (void)utime((char *)fname, &buf); # else # if defined(HAVE_UTIMES) struct timeval tvp[2]; tvp[0].tv_sec = atime; tvp[0].tv_usec = 0; tvp[1].tv_sec = mtime; tvp[1].tv_usec = 0; # ifdef NeXT (void)utimes((char *)fname, tvp); # else (void)utimes((char *)fname, (const struct timeval *)&tvp); # endif # endif # endif } #endif /* UNIX */ #if defined(VMS) && !defined(MIN) /* Older DECC compiler for VAX doesn't define MIN() */ # define MIN(a, b) ((a) < (b) ? (a) : (b)) #endif /* * Return TRUE if a file appears to be read-only from the file permissions. */ int check_file_readonly(fname, perm) char_u *fname; /* full path to file */ int perm; /* known permissions on file */ { #ifndef USE_MCH_ACCESS int fd = 0; #endif return ( #ifdef USE_MCH_ACCESS # ifdef UNIX (perm & 0222) == 0 || # endif mch_access((char *)fname, W_OK) #else (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0 ? TRUE : (close(fd), FALSE) #endif ); } /* * buf_write() - write to file "fname" lines "start" through "end" * * We do our own buffering here because fwrite() is so slow. * * If "forceit" is true, we don't care for errors when attempting backups. * In case of an error everything possible is done to restore the original * file. But when "forceit" is TRUE, we risk losing it. * * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed. * * This function must NOT use NameBuff (because it's called by autowrite()). * * return FAIL for failure, OK otherwise */ int buf_write(buf, fname, sfname, start, end, eap, append, forceit, reset_changed, filtering) buf_T *buf; char_u *fname; char_u *sfname; linenr_T start, end; exarg_T *eap; /* for forced 'ff' and 'fenc', can be NULL! */ int append; /* append to the file */ int forceit; int reset_changed; int filtering; { int fd; char_u *backup = NULL; int backup_copy = FALSE; /* copy the original file? */ int dobackup; char_u *ffname; char_u *wfname = NULL; /* name of file to write to */ char_u *s; char_u *ptr; char_u c; int len; linenr_T lnum; long nchars; char_u *errmsg = NULL; int errmsg_allocated = FALSE; char_u *errnum = NULL; char_u *buffer; char_u smallbuf[SMBUFSIZE]; char_u *backup_ext; int bufsize; long perm; /* file permissions */ int retval = OK; int newfile = FALSE; /* TRUE if file doesn't exist yet */ int msg_save = msg_scroll; int overwriting; /* TRUE if writing over original */ int no_eol = FALSE; /* no end-of-line written */ int device = FALSE; /* writing to a device */ struct stat st_old; int prev_got_int = got_int; int file_readonly = FALSE; /* overwritten file is read-only */ static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')"; #if defined(UNIX) || defined(__EMX__XX) /*XXX fix me sometime? */ int made_writable = FALSE; /* 'w' bit has been set */ #endif /* writing everything */ int whole = (start == 1 && end == buf->b_ml.ml_line_count); #ifdef FEAT_AUTOCMD linenr_T old_line_count = buf->b_ml.ml_line_count; #endif int attr; int fileformat; int write_bin; struct bw_info write_info; /* info for buf_write_bytes() */ #ifdef FEAT_MBYTE int converted = FALSE; int notconverted = FALSE; char_u *fenc; /* effective 'fileencoding' */ char_u *fenc_tofree = NULL; /* allocated "fenc" */ #endif #ifdef HAS_BW_FLAGS int wb_flags = 0; #endif #ifdef HAVE_ACL vim_acl_T acl = NULL; /* ACL copied from original file to backup or new file */ #endif #ifdef FEAT_PERSISTENT_UNDO int write_undo_file = FALSE; context_sha256_T sha_ctx; #endif #ifdef FEAT_CRYPT int crypt_method_used; #endif if (fname == NULL || *fname == NUL) /* safety check */ return FAIL; if (buf->b_ml.ml_mfp == NULL) { /* This can happen during startup when there is a stray "w" in the * vimrc file. */ EMSG(_(e_emptybuf)); return FAIL; } /* * Disallow writing from .exrc and .vimrc in current directory for * security reasons. */ if (check_secure()) return FAIL; /* Avoid a crash for a long name. */ if (STRLEN(fname) >= MAXPATHL) { EMSG(_(e_longname)); return FAIL; } #ifdef FEAT_MBYTE /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */ write_info.bw_conv_buf = NULL; write_info.bw_conv_error = FALSE; write_info.bw_conv_error_lnum = 0; write_info.bw_restlen = 0; # ifdef USE_ICONV write_info.bw_iconv_fd = (iconv_t)-1; # endif #endif /* After writing a file changedtick changes but we don't want to display * the line. */ ex_no_reprint = TRUE; /* * If there is no file name yet, use the one for the written file. * BF_NOTEDITED is set to reflect this (in case the write fails). * Don't do this when the write is for a filter command. * Don't do this when appending. * Only do this when 'cpoptions' contains the 'F' flag. */ if (buf->b_ffname == NULL && reset_changed && whole && buf == curbuf #ifdef FEAT_QUICKFIX && !bt_nofile(buf) #endif && !filtering && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL) && vim_strchr(p_cpo, CPO_FNAMEW) != NULL) { if (set_rw_fname(fname, sfname) == FAIL) return FAIL; buf = curbuf; /* just in case autocmds made "buf" invalid */ } if (sfname == NULL) sfname = fname; /* * For Unix: Use the short file name whenever possible. * Avoids problems with networks and when directory names are changed. * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to * another directory, which we don't detect */ ffname = fname; /* remember full fname */ #ifdef UNIX fname = sfname; #endif if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0) overwriting = TRUE; else overwriting = FALSE; if (exiting) settmode(TMODE_COOK); /* when exiting allow typahead now */ ++no_wait_return; /* don't wait for return yet */ /* * Set '[ and '] marks to the lines to be written. */ buf->b_op_start.lnum = start; buf->b_op_start.col = 0; buf->b_op_end.lnum = end; buf->b_op_end.col = 0; #ifdef FEAT_AUTOCMD { aco_save_T aco; int buf_ffname = FALSE; int buf_sfname = FALSE; int buf_fname_f = FALSE; int buf_fname_s = FALSE; int did_cmd = FALSE; int nofile_err = FALSE; int empty_memline = (buf->b_ml.ml_mfp == NULL); /* * Apply PRE aucocommands. * Set curbuf to the buffer to be written. * Careful: The autocommands may call buf_write() recursively! */ if (ffname == buf->b_ffname) buf_ffname = TRUE; if (sfname == buf->b_sfname) buf_sfname = TRUE; if (fname == buf->b_ffname) buf_fname_f = TRUE; if (fname == buf->b_sfname) buf_fname_s = TRUE; /* set curwin/curbuf to buf and save a few things */ aucmd_prepbuf(&aco, buf); if (append) { if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD, sfname, sfname, FALSE, curbuf, eap))) { #ifdef FEAT_QUICKFIX if (overwriting && bt_nofile(curbuf)) nofile_err = TRUE; else #endif apply_autocmds_exarg(EVENT_FILEAPPENDPRE, sfname, sfname, FALSE, curbuf, eap); } } else if (filtering) { apply_autocmds_exarg(EVENT_FILTERWRITEPRE, NULL, sfname, FALSE, curbuf, eap); } else if (reset_changed && whole) { int was_changed = curbufIsChanged(); did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD, sfname, sfname, FALSE, curbuf, eap); if (did_cmd) { if (was_changed && !curbufIsChanged()) { /* Written everything correctly and BufWriteCmd has reset * 'modified': Correct the undo information so that an * undo now sets 'modified'. */ u_unchanged(curbuf); u_update_save_nr(curbuf); } } else { #ifdef FEAT_QUICKFIX if (overwriting && bt_nofile(curbuf)) nofile_err = TRUE; else #endif apply_autocmds_exarg(EVENT_BUFWRITEPRE, sfname, sfname, FALSE, curbuf, eap); } } else { if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD, sfname, sfname, FALSE, curbuf, eap))) { #ifdef FEAT_QUICKFIX if (overwriting && bt_nofile(curbuf)) nofile_err = TRUE; else #endif apply_autocmds_exarg(EVENT_FILEWRITEPRE, sfname, sfname, FALSE, curbuf, eap); } } /* restore curwin/curbuf and a few other things */ aucmd_restbuf(&aco); /* * In three situations we return here and don't write the file: * 1. the autocommands deleted or unloaded the buffer. * 2. The autocommands abort script processing. * 3. If one of the "Cmd" autocommands was executed. */ if (!buf_valid(buf)) buf = NULL; if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline) || did_cmd || nofile_err #ifdef FEAT_EVAL || aborting() #endif ) { --no_wait_return; msg_scroll = msg_save; if (nofile_err) EMSG(_("E676: No matching autocommands for acwrite buffer")); if (nofile_err #ifdef FEAT_EVAL || aborting() #endif ) /* An aborting error, interrupt or exception in the * autocommands. */ return FAIL; if (did_cmd) { if (buf == NULL) /* The buffer was deleted. We assume it was written * (can't retry anyway). */ return OK; if (overwriting) { /* Assume the buffer was written, update the timestamp. */ ml_timestamp(buf); if (append) buf->b_flags &= ~BF_NEW; else buf->b_flags &= ~BF_WRITE_MASK; } if (reset_changed && buf->b_changed && !append && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)) /* Buffer still changed, the autocommands didn't work * properly. */ return FAIL; return OK; } #ifdef FEAT_EVAL if (!aborting()) #endif EMSG(_("E203: Autocommands deleted or unloaded buffer to be written")); return FAIL; } /* * The autocommands may have changed the number of lines in the file. * When writing the whole file, adjust the end. * When writing part of the file, assume that the autocommands only * changed the number of lines that are to be written (tricky!). */ if (buf->b_ml.ml_line_count != old_line_count) { if (whole) /* write all */ end = buf->b_ml.ml_line_count; else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */ end += buf->b_ml.ml_line_count - old_line_count; else /* less lines */ { end -= old_line_count - buf->b_ml.ml_line_count; if (end < start) { --no_wait_return; msg_scroll = msg_save; EMSG(_("E204: Autocommand changed number of lines in unexpected way")); return FAIL; } } } /* * The autocommands may have changed the name of the buffer, which may * be kept in fname, ffname and sfname. */ if (buf_ffname) ffname = buf->b_ffname; if (buf_sfname) sfname = buf->b_sfname; if (buf_fname_f) fname = buf->b_ffname; if (buf_fname_s) fname = buf->b_sfname; } #endif #ifdef FEAT_NETBEANS_INTG if (netbeans_active() && isNetbeansBuffer(buf)) { if (whole) { /* * b_changed can be 0 after an undo, but we still need to write * the buffer to NetBeans. */ if (buf->b_changed || isNetbeansModified(buf)) { --no_wait_return; /* may wait for return now */ msg_scroll = msg_save; netbeans_save_buffer(buf); /* no error checking... */ return retval; } else { errnum = (char_u *)"E656: "; errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers"); buffer = NULL; goto fail; } } else { errnum = (char_u *)"E657: "; errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers"); buffer = NULL; goto fail; } } #endif if (shortmess(SHM_OVER) && !exiting) msg_scroll = FALSE; /* overwrite previous file message */ else msg_scroll = TRUE; /* don't overwrite previous file message */ if (!filtering) filemess(buf, #ifndef UNIX sfname, #else fname, #endif (char_u *)"", 0); /* show that we are busy */ msg_scroll = FALSE; /* always overwrite the file message now */ buffer = alloc(BUFSIZE); if (buffer == NULL) /* can't allocate big buffer, use small * one (to be able to write when out of * memory) */ { buffer = smallbuf; bufsize = SMBUFSIZE; } else bufsize = BUFSIZE; /* * Get information about original file (if there is one). */ #if defined(UNIX) && !defined(ARCHIE) st_old.st_dev = 0; st_old.st_ino = 0; perm = -1; if (mch_stat((char *)fname, &st_old) < 0) newfile = TRUE; else { perm = st_old.st_mode; if (!S_ISREG(st_old.st_mode)) /* not a file */ { if (S_ISDIR(st_old.st_mode)) { errnum = (char_u *)"E502: "; errmsg = (char_u *)_("is a directory"); goto fail; } if (mch_nodetype(fname) != NODE_WRITABLE) { errnum = (char_u *)"E503: "; errmsg = (char_u *)_("is not a file or writable device"); goto fail; } /* It's a device of some kind (or a fifo) which we can write to * but for which we can't make a backup. */ device = TRUE; newfile = TRUE; perm = -1; } } #else /* !UNIX */ /* * Check for a writable device name. */ c = mch_nodetype(fname); if (c == NODE_OTHER) { errnum = (char_u *)"E503: "; errmsg = (char_u *)_("is not a file or writable device"); goto fail; } if (c == NODE_WRITABLE) { # if defined(MSDOS) || defined(MSWIN) || defined(OS2) /* MS-Windows allows opening a device, but we will probably get stuck * trying to write to it. */ if (!p_odev) { errnum = (char_u *)"E796: "; errmsg = (char_u *)_("writing to device disabled with 'opendevice' option"); goto fail; } # endif device = TRUE; newfile = TRUE; perm = -1; } else { perm = mch_getperm(fname); if (perm < 0) newfile = TRUE; else if (mch_isdir(fname)) { errnum = (char_u *)"E502: "; errmsg = (char_u *)_("is a directory"); goto fail; } if (overwriting) (void)mch_stat((char *)fname, &st_old); } #endif /* !UNIX */ if (!device && !newfile) { /* * Check if the file is really writable (when renaming the file to * make a backup we won't discover it later). */ file_readonly = check_file_readonly(fname, (int)perm); if (!forceit && file_readonly) { if (vim_strchr(p_cpo, CPO_FWRITE) != NULL) { errnum = (char_u *)"E504: "; errmsg = (char_u *)_(err_readonly); } else { errnum = (char_u *)"E505: "; errmsg = (char_u *)_("is read-only (add ! to override)"); } goto fail; } /* * Check if the timestamp hasn't changed since reading the file. */ if (overwriting) { retval = check_mtime(buf, &st_old); if (retval == FAIL) goto fail; } } #ifdef HAVE_ACL /* * For systems that support ACL: get the ACL from the original file. */ if (!newfile) acl = mch_get_acl(fname); #endif /* * If 'backupskip' is not empty, don't make a backup for some files. */ dobackup = (p_wb || p_bk || *p_pm != NUL); #ifdef FEAT_WILDIGN if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname)) dobackup = FALSE; #endif /* * Save the value of got_int and reset it. We don't want a previous * interruption cancel writing, only hitting CTRL-C while writing should * abort it. */ prev_got_int = got_int; got_int = FALSE; /* Mark the buffer as 'being saved' to prevent changed buffer warnings */ buf->b_saving = TRUE; /* * If we are not appending or filtering, the file exists, and the * 'writebackup', 'backup' or 'patchmode' option is set, need a backup. * When 'patchmode' is set also make a backup when appending. * * Do not make any backup, if 'writebackup' and 'backup' are both switched * off. This helps when editing large files on almost-full disks. */ if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup) { #if defined(UNIX) || defined(WIN32) struct stat st; #endif if ((bkc_flags & BKC_YES) || append) /* "yes" */ backup_copy = TRUE; #if defined(UNIX) || defined(WIN32) else if ((bkc_flags & BKC_AUTO)) /* "auto" */ { int i; # ifdef UNIX /* * Don't rename the file when: * - it's a hard link * - it's a symbolic link * - we don't have write permission in the directory * - we can't set the owner/group of the new file */ if (st_old.st_nlink > 1 || mch_lstat((char *)fname, &st) < 0 || st.st_dev != st_old.st_dev || st.st_ino != st_old.st_ino # ifndef HAVE_FCHOWN || st.st_uid != st_old.st_uid || st.st_gid != st_old.st_gid # endif ) backup_copy = TRUE; else # else # ifdef WIN32 /* On NTFS file systems hard links are possible. */ if (mch_is_linked(fname)) backup_copy = TRUE; else # endif # endif { /* * Check if we can create a file and set the owner/group to * the ones from the original file. * First find a file name that doesn't exist yet (use some * arbitrary numbers). */ STRCPY(IObuff, fname); for (i = 4913; ; i += 123) { sprintf((char *)gettail(IObuff), "%d", i); if (mch_lstat((char *)IObuff, &st) < 0) break; } fd = mch_open((char *)IObuff, O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm); if (fd < 0) /* can't write in directory */ backup_copy = TRUE; else { # ifdef UNIX # ifdef HAVE_FCHOWN ignored = fchown(fd, st_old.st_uid, st_old.st_gid); # endif if (mch_stat((char *)IObuff, &st) < 0 || st.st_uid != st_old.st_uid || st.st_gid != st_old.st_gid || (long)st.st_mode != perm) backup_copy = TRUE; # endif /* Close the file before removing it, on MS-Windows we * can't delete an open file. */ close(fd); mch_remove(IObuff); # ifdef MSWIN /* MS-Windows may trigger a virus scanner to open the * file, we can't delete it then. Keep trying for half a * second. */ { int try; for (try = 0; try < 10; ++try) { if (mch_lstat((char *)IObuff, &st) < 0) break; ui_delay(50L, TRUE); /* wait 50 msec */ mch_remove(IObuff); } } # endif } } } # ifdef UNIX /* * Break symlinks and/or hardlinks if we've been asked to. */ if ((bkc_flags & BKC_BREAKSYMLINK) || (bkc_flags & BKC_BREAKHARDLINK)) { int lstat_res; lstat_res = mch_lstat((char *)fname, &st); /* Symlinks. */ if ((bkc_flags & BKC_BREAKSYMLINK) && lstat_res == 0 && st.st_ino != st_old.st_ino) backup_copy = FALSE; /* Hardlinks. */ if ((bkc_flags & BKC_BREAKHARDLINK) && st_old.st_nlink > 1 && (lstat_res != 0 || st.st_ino == st_old.st_ino)) backup_copy = FALSE; } #endif #endif /* make sure we have a valid backup extension to use */ if (*p_bex == NUL) backup_ext = (char_u *)".bak"; else backup_ext = p_bex; if (backup_copy && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0) { int bfd; char_u *copybuf, *wp; int some_error = FALSE; struct stat st_new; char_u *dirp; char_u *rootname; #if defined(UNIX) && !defined(SHORT_FNAME) int did_set_shortname; #endif copybuf = alloc(BUFSIZE + 1); if (copybuf == NULL) { some_error = TRUE; /* out of memory */ goto nobackup; } /* * Try to make the backup in each directory in the 'bdir' option. * * Unix semantics has it, that we may have a writable file, * that cannot be recreated with a simple open(..., O_CREAT, ) e.g: * - the directory is not writable, * - the file may be a symbolic link, * - the file may belong to another user/group, etc. * * For these reasons, the existing writable file must be truncated * and reused. Creation of a backup COPY will be attempted. */ dirp = p_bdir; while (*dirp) { #ifdef UNIX st_new.st_ino = 0; st_new.st_dev = 0; st_new.st_gid = 0; #endif /* * Isolate one directory name, using an entry in 'bdir'. */ (void)copy_option_part(&dirp, copybuf, BUFSIZE, ","); rootname = get_file_in_dir(fname, copybuf); if (rootname == NULL) { some_error = TRUE; /* out of memory */ goto nobackup; } #if defined(UNIX) && !defined(SHORT_FNAME) did_set_shortname = FALSE; #endif /* * May try twice if 'shortname' not set. */ for (;;) { /* * Make backup file name. */ backup = buf_modname( #ifdef SHORT_FNAME TRUE, #else (buf->b_p_sn || buf->b_shortname), #endif rootname, backup_ext, FALSE); if (backup == NULL) { vim_free(rootname); some_error = TRUE; /* out of memory */ goto nobackup; } /* * Check if backup file already exists. */ if (mch_stat((char *)backup, &st_new) >= 0) { #ifdef UNIX /* * Check if backup file is same as original file. * May happen when modname() gave the same file back. * E.g. silly link, or file name-length reached. * If we don't check here, we either ruin the file * when copying or erase it after writing. jw. */ if (st_new.st_dev == st_old.st_dev && st_new.st_ino == st_old.st_ino) { vim_free(backup); backup = NULL; /* no backup file to delete */ # ifndef SHORT_FNAME /* * may try again with 'shortname' set */ if (!(buf->b_shortname || buf->b_p_sn)) { buf->b_shortname = TRUE; did_set_shortname = TRUE; continue; } /* setting shortname didn't help */ if (did_set_shortname) buf->b_shortname = FALSE; # endif break; } #endif /* * If we are not going to keep the backup file, don't * delete an existing one, try to use another name. * Change one character, just before the extension. */ if (!p_bk) { wp = backup + STRLEN(backup) - 1 - STRLEN(backup_ext); if (wp < backup) /* empty file name ??? */ wp = backup; *wp = 'z'; while (*wp > 'a' && mch_stat((char *)backup, &st_new) >= 0) --*wp; /* They all exist??? Must be something wrong. */ if (*wp == 'a') { vim_free(backup); backup = NULL; } } } break; } vim_free(rootname); /* * Try to create the backup file */ if (backup != NULL) { /* remove old backup, if present */ mch_remove(backup); /* Open with O_EXCL to avoid the file being created while * we were sleeping (symlink hacker attack?) */ bfd = mch_open((char *)backup, O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW, perm & 0777); if (bfd < 0) { vim_free(backup); backup = NULL; } else { /* set file protection same as original file, but * strip s-bit */ (void)mch_setperm(backup, perm & 0777); #ifdef UNIX /* * Try to set the group of the backup same as the * original file. If this fails, set the protection * bits for the group same as the protection bits for * others. */ if (st_new.st_gid != st_old.st_gid # ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */ && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0 # endif ) mch_setperm(backup, (perm & 0707) | ((perm & 07) << 3)); # ifdef HAVE_SELINUX mch_copy_sec(fname, backup); # endif #endif /* * copy the file. */ write_info.bw_fd = bfd; write_info.bw_buf = copybuf; #ifdef HAS_BW_FLAGS write_info.bw_flags = FIO_NOCONVERT; #endif while ((write_info.bw_len = read_eintr(fd, copybuf, BUFSIZE)) > 0) { if (buf_write_bytes(&write_info) == FAIL) { errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)"); break; } ui_breakcheck(); if (got_int) { errmsg = (char_u *)_(e_interr); break; } } if (close(bfd) < 0 && errmsg == NULL) errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)"); if (write_info.bw_len < 0) errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)"); #ifdef UNIX set_file_time(backup, st_old.st_atime, st_old.st_mtime); #endif #ifdef HAVE_ACL mch_set_acl(backup, acl); #endif #ifdef HAVE_SELINUX mch_copy_sec(fname, backup); #endif break; } } } nobackup: close(fd); /* ignore errors for closing read file */ vim_free(copybuf); if (backup == NULL && errmsg == NULL) errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)"); /* ignore errors when forceit is TRUE */ if ((some_error || errmsg != NULL) && !forceit) { retval = FAIL; goto fail; } errmsg = NULL; } else { char_u *dirp; char_u *p; char_u *rootname; /* * Make a backup by renaming the original file. */ /* * If 'cpoptions' includes the "W" flag, we don't want to * overwrite a read-only file. But rename may be possible * anyway, thus we need an extra check here. */ if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL) { errnum = (char_u *)"E504: "; errmsg = (char_u *)_(err_readonly); goto fail; } /* * * Form the backup file name - change path/fo.o.h to * path/fo.o.h.bak Try all directories in 'backupdir', first one * that works is used. */ dirp = p_bdir; while (*dirp) { /* * Isolate one directory name and make the backup file name. */ (void)copy_option_part(&dirp, IObuff, IOSIZE, ","); rootname = get_file_in_dir(fname, IObuff); if (rootname == NULL) backup = NULL; else { backup = buf_modname( #ifdef SHORT_FNAME TRUE, #else (buf->b_p_sn || buf->b_shortname), #endif rootname, backup_ext, FALSE); vim_free(rootname); } if (backup != NULL) { /* * If we are not going to keep the backup file, don't * delete an existing one, try to use another name. * Change one character, just before the extension. */ if (!p_bk && mch_getperm(backup) >= 0) { p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext); if (p < backup) /* empty file name ??? */ p = backup; *p = 'z'; while (*p > 'a' && mch_getperm(backup) >= 0) --*p; /* They all exist??? Must be something wrong! */ if (*p == 'a') { vim_free(backup); backup = NULL; } } } if (backup != NULL) { /* * Delete any existing backup and move the current version * to the backup. For safety, we don't remove the backup * until the write has finished successfully. And if the * 'backup' option is set, leave it around. */ /* * If the renaming of the original file to the backup file * works, quit here. */ if (vim_rename(fname, backup) == 0) break; vim_free(backup); /* don't do the rename below */ backup = NULL; } } if (backup == NULL && !forceit) { errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)"); goto fail; } } } #if defined(UNIX) && !defined(ARCHIE) /* When using ":w!" and the file was read-only: make it writable */ if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid() && vim_strchr(p_cpo, CPO_FWRITE) == NULL) { perm |= 0200; (void)mch_setperm(fname, perm); made_writable = TRUE; } #endif /* When using ":w!" and writing to the current file, 'readonly' makes no * sense, reset it, unless 'Z' appears in 'cpoptions'. */ if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL) { buf->b_p_ro = FALSE; #ifdef FEAT_TITLE need_maketitle = TRUE; /* set window title later */ #endif #ifdef FEAT_WINDOWS status_redraw_all(); /* redraw status lines later */ #endif } if (end > buf->b_ml.ml_line_count) end = buf->b_ml.ml_line_count; if (buf->b_ml.ml_flags & ML_EMPTY) start = end + 1; /* * If the original file is being overwritten, there is a small chance that * we crash in the middle of writing. Therefore the file is preserved now. * This makes all block numbers positive so that recovery does not need * the original file. * Don't do this if there is a backup file and we are exiting. */ if (reset_changed && !newfile && overwriting && !(exiting && backup != NULL)) { ml_preserve(buf, FALSE); if (got_int) { errmsg = (char_u *)_(e_interr); goto restore_backup; } } #ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */ /* * Before risking to lose the original file verify if there's * a resource fork to preserve, and if cannot be done warn * the users. This happens when overwriting without backups. */ if (backup == NULL && overwriting && !append) if (mch_has_resource_fork(fname)) { errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)"); goto restore_backup; } #endif #ifdef VMS vms_remove_version(fname); /* remove version */ #endif /* Default: write the file directly. May write to a temp file for * multi-byte conversion. */ wfname = fname; #ifdef FEAT_MBYTE /* Check for forced 'fileencoding' from "++opt=val" argument. */ if (eap != NULL && eap->force_enc != 0) { fenc = eap->cmd + eap->force_enc; fenc = enc_canonize(fenc); fenc_tofree = fenc; } else fenc = buf->b_p_fenc; /* * Check if the file needs to be converted. */ converted = need_conversion(fenc); /* * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or * Latin1 to Unicode conversion. This is handled in buf_write_bytes(). * Prepare the flags for it and allocate bw_conv_buf when needed. */ if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0)) { wb_flags = get_fio_flags(fenc); if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8)) { /* Need to allocate a buffer to translate into. */ if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8)) write_info.bw_conv_buflen = bufsize * 2; else /* FIO_UCS4 */ write_info.bw_conv_buflen = bufsize * 4; write_info.bw_conv_buf = lalloc((long_u)write_info.bw_conv_buflen, TRUE); if (write_info.bw_conv_buf == NULL) end = 0; } } # ifdef WIN3264 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0) { /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */ write_info.bw_conv_buflen = bufsize * 4; write_info.bw_conv_buf = lalloc((long_u)write_info.bw_conv_buflen, TRUE); if (write_info.bw_conv_buf == NULL) end = 0; } # endif # ifdef MACOS_X if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0) { write_info.bw_conv_buflen = bufsize * 3; write_info.bw_conv_buf = lalloc((long_u)write_info.bw_conv_buflen, TRUE); if (write_info.bw_conv_buf == NULL) end = 0; } # endif # if defined(FEAT_EVAL) || defined(USE_ICONV) if (converted && wb_flags == 0) { # ifdef USE_ICONV /* * Use iconv() conversion when conversion is needed and it's not done * internally. */ write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc); if (write_info.bw_iconv_fd != (iconv_t)-1) { /* We're going to use iconv(), allocate a buffer to convert in. */ write_info.bw_conv_buflen = bufsize * ICONV_MULT; write_info.bw_conv_buf = lalloc((long_u)write_info.bw_conv_buflen, TRUE); if (write_info.bw_conv_buf == NULL) end = 0; write_info.bw_first = TRUE; } # ifdef FEAT_EVAL else # endif # endif # ifdef FEAT_EVAL /* * When the file needs to be converted with 'charconvert' after * writing, write to a temp file instead and let the conversion * overwrite the original file. */ if (*p_ccv != NUL) { wfname = vim_tempname('w'); if (wfname == NULL) /* Can't write without a tempfile! */ { errmsg = (char_u *)_("E214: Can't find temp file for writing"); goto restore_backup; } } # endif } # endif if (converted && wb_flags == 0 # ifdef USE_ICONV && write_info.bw_iconv_fd == (iconv_t)-1 # endif # ifdef FEAT_EVAL && wfname == fname # endif ) { if (!forceit) { errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)"); goto restore_backup; } notconverted = TRUE; } #endif /* * Open the file "wfname" for writing. * We may try to open the file twice: If we can't write to the * file and forceit is TRUE we delete the existing file and try to create * a new one. If this still fails we may have lost the original file! * (this may happen when the user reached his quotum for number of files). * Appending will fail if the file does not exist and forceit is FALSE. */ while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND) : (O_CREAT | O_TRUNC)) , perm < 0 ? 0666 : (perm & 0777))) < 0) { /* * A forced write will try to create a new file if the old one is * still readonly. This may also happen when the directory is * read-only. In that case the mch_remove() will fail. */ if (errmsg == NULL) { #ifdef UNIX struct stat st; /* Don't delete the file when it's a hard or symbolic link. */ if ((!newfile && st_old.st_nlink > 1) || (mch_lstat((char *)fname, &st) == 0 && (st.st_dev != st_old.st_dev || st.st_ino != st_old.st_ino))) errmsg = (char_u *)_("E166: Can't open linked file for writing"); else #endif { errmsg = (char_u *)_("E212: Can't open file for writing"); if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL && perm >= 0) { #ifdef UNIX /* we write to the file, thus it should be marked writable after all */ if (!(perm & 0200)) made_writable = TRUE; perm |= 0200; if (st_old.st_uid != getuid() || st_old.st_gid != getgid()) perm &= 0777; #endif if (!append) /* don't remove when appending */ mch_remove(wfname); continue; } } } restore_backup: { struct stat st; /* * If we failed to open the file, we don't need a backup. Throw it * away. If we moved or removed the original file try to put the * backup in its place. */ if (backup != NULL && wfname == fname) { if (backup_copy) { /* * There is a small chance that we removed the original, * try to move the copy in its place. * This may not work if the vim_rename() fails. * In that case we leave the copy around. */ /* If file does not exist, put the copy in its place */ if (mch_stat((char *)fname, &st) < 0) vim_rename(backup, fname); /* if original file does exist throw away the copy */ if (mch_stat((char *)fname, &st) >= 0) mch_remove(backup); } else { /* try to put the original file back */ vim_rename(backup, fname); } } /* if original file no longer exists give an extra warning */ if (!newfile && mch_stat((char *)fname, &st) < 0) end = 0; } #ifdef FEAT_MBYTE if (wfname != fname) vim_free(wfname); #endif goto fail; } errmsg = NULL; #if defined(MACOS_CLASSIC) || defined(WIN3264) /* TODO: Is it need for MACOS_X? (Dany) */ /* * On macintosh copy the original files attributes (i.e. the backup) * This is done in order to preserve the resource fork and the * Finder attribute (label, comments, custom icons, file creator) */ if (backup != NULL && overwriting && !append) { if (backup_copy) (void)mch_copy_file_attribute(wfname, backup); else (void)mch_copy_file_attribute(backup, wfname); } if (!overwriting && !append) { if (buf->b_ffname != NULL) (void)mch_copy_file_attribute(buf->b_ffname, wfname); /* Should copy resource fork */ } #endif write_info.bw_fd = fd; #ifdef FEAT_CRYPT if (*buf->b_p_key != NUL && !filtering) { char_u *header; int header_len; header = prepare_crypt_write(buf, &header_len); if (header == NULL) end = 0; else { /* Write magic number, so that Vim knows that this file is * encrypted when reading it again. This also undergoes utf-8 to * ucs-2/4 conversion when needed. */ write_info.bw_buf = header; write_info.bw_len = header_len; write_info.bw_flags = FIO_NOCONVERT; if (buf_write_bytes(&write_info) == FAIL) end = 0; wb_flags |= FIO_ENCRYPTED; vim_free(header); } } #endif write_info.bw_buf = buffer; nchars = 0; /* use "++bin", "++nobin" or 'binary' */ if (eap != NULL && eap->force_bin != 0) write_bin = (eap->force_bin == FORCE_BIN); else write_bin = buf->b_p_bin; #ifdef FEAT_MBYTE /* * The BOM is written just after the encryption magic number. * Skip it when appending and the file already existed, the BOM only makes * sense at the start of the file. */ if (buf->b_p_bomb && !write_bin && (!append || perm < 0)) { write_info.bw_len = make_bom(buffer, fenc); if (write_info.bw_len > 0) { /* don't convert, do encryption */ write_info.bw_flags = FIO_NOCONVERT | wb_flags; if (buf_write_bytes(&write_info) == FAIL) end = 0; else nchars += write_info.bw_len; } } write_info.bw_start_lnum = start; #endif #ifdef FEAT_PERSISTENT_UNDO write_undo_file = (buf->b_p_udf && overwriting && !append && !filtering && reset_changed); if (write_undo_file) /* Prepare for computing the hash value of the text. */ sha256_start(&sha_ctx); #endif write_info.bw_len = bufsize; #ifdef HAS_BW_FLAGS write_info.bw_flags = wb_flags; #endif fileformat = get_fileformat_force(buf, eap); s = buffer; len = 0; for (lnum = start; lnum <= end; ++lnum) { /* * The next while loop is done once for each character written. * Keep it fast! */ ptr = ml_get_buf(buf, lnum, FALSE) - 1; #ifdef FEAT_PERSISTENT_UNDO if (write_undo_file) sha256_update(&sha_ctx, ptr + 1, (UINT32_T)(STRLEN(ptr + 1) + 1)); #endif while ((c = *++ptr) != NUL) { if (c == NL) *s = NUL; /* replace newlines with NULs */ else if (c == CAR && fileformat == EOL_MAC) *s = NL; /* Mac: replace CRs with NLs */ else *s = c; ++s; if (++len != bufsize) continue; if (buf_write_bytes(&write_info) == FAIL) { end = 0; /* write error: break loop */ break; } nchars += bufsize; s = buffer; len = 0; #ifdef FEAT_MBYTE write_info.bw_start_lnum = lnum; #endif } /* write failed or last line has no EOL: stop here */ if (end == 0 || (lnum == end && write_bin && (lnum == buf->b_no_eol_lnum || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol)))) { ++lnum; /* written the line, count it */ no_eol = TRUE; break; } if (fileformat == EOL_UNIX) *s++ = NL; else { *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */ if (fileformat == EOL_DOS) /* write CR-NL */ { if (++len == bufsize) { if (buf_write_bytes(&write_info) == FAIL) { end = 0; /* write error: break loop */ break; } nchars += bufsize; s = buffer; len = 0; } *s++ = NL; } } if (++len == bufsize && end) { if (buf_write_bytes(&write_info) == FAIL) { end = 0; /* write error: break loop */ break; } nchars += bufsize; s = buffer; len = 0; ui_breakcheck(); if (got_int) { end = 0; /* Interrupted, break loop */ break; } } #ifdef VMS /* * On VMS there is a problem: newlines get added when writing blocks * at a time. Fix it by writing a line at a time. * This is much slower! * Explanation: VAX/DECC RTL insists that records in some RMS * structures end with a newline (carriage return) character, and if * they don't it adds one. * With other RMS structures it works perfect without this fix. */ if (buf->b_fab_rfm == FAB$C_VFC || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0)) { int b2write; buf->b_fab_mrs = (buf->b_fab_mrs == 0 ? MIN(4096, bufsize) : MIN(buf->b_fab_mrs, bufsize)); b2write = len; while (b2write > 0) { write_info.bw_len = MIN(b2write, buf->b_fab_mrs); if (buf_write_bytes(&write_info) == FAIL) { end = 0; break; } b2write -= MIN(b2write, buf->b_fab_mrs); } write_info.bw_len = bufsize; nchars += len; s = buffer; len = 0; } #endif } if (len > 0 && end > 0) { write_info.bw_len = len; if (buf_write_bytes(&write_info) == FAIL) end = 0; /* write error */ nchars += len; } #if defined(UNIX) && defined(HAVE_FSYNC) /* On many journalling file systems there is a bug that causes both the * original and the backup file to be lost when halting the system right * after writing the file. That's because only the meta-data is * journalled. Syncing the file slows down the system, but assures it has * been written to disk and we don't lose it. * For a device do try the fsync() but don't complain if it does not work * (could be a pipe). * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */ if (p_fs && fsync(fd) != 0 && !device) { errmsg = (char_u *)_("E667: Fsync failed"); end = 0; } #endif #ifdef HAVE_SELINUX /* Probably need to set the security context. */ if (!backup_copy) mch_copy_sec(backup, wfname); #endif #ifdef UNIX /* When creating a new file, set its owner/group to that of the original * file. Get the new device and inode number. */ if (backup != NULL && !backup_copy) { # ifdef HAVE_FCHOWN struct stat st; /* don't change the owner when it's already OK, some systems remove * permission or ACL stuff */ if (mch_stat((char *)wfname, &st) < 0 || st.st_uid != st_old.st_uid || st.st_gid != st_old.st_gid) { ignored = fchown(fd, st_old.st_uid, st_old.st_gid); if (perm >= 0) /* set permission again, may have changed */ (void)mch_setperm(wfname, perm); } # endif buf_setino(buf); } else if (!buf->b_dev_valid) /* Set the inode when creating a new file. */ buf_setino(buf); #endif if (close(fd) != 0) { errmsg = (char_u *)_("E512: Close failed"); end = 0; } #ifdef UNIX if (made_writable) perm &= ~0200; /* reset 'w' bit for security reasons */ #endif if (perm >= 0) /* set perm. of new file same as old file */ (void)mch_setperm(wfname, perm); #ifdef HAVE_ACL /* Probably need to set the ACL before changing the user (can't set the * ACL on a file the user doesn't own). */ if (!backup_copy) mch_set_acl(wfname, acl); #endif #ifdef FEAT_CRYPT crypt_method_used = use_crypt_method; if (wb_flags & FIO_ENCRYPTED) crypt_pop_state(); #endif #if defined(FEAT_MBYTE) && defined(FEAT_EVAL) if (wfname != fname) { /* * The file was written to a temp file, now it needs to be converted * with 'charconvert' to (overwrite) the output file. */ if (end != 0) { if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc, wfname, fname) == FAIL) { write_info.bw_conv_error = TRUE; end = 0; } } mch_remove(wfname); vim_free(wfname); } #endif if (end == 0) { if (errmsg == NULL) { #ifdef FEAT_MBYTE if (write_info.bw_conv_error) { if (write_info.bw_conv_error_lnum == 0) errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)"); else { errmsg_allocated = TRUE; errmsg = alloc(300); vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"), (long)write_info.bw_conv_error_lnum); } } else #endif if (got_int) errmsg = (char_u *)_(e_interr); else errmsg = (char_u *)_("E514: write error (file system full?)"); } /* * If we have a backup file, try to put it in place of the new file, * because the new file is probably corrupt. This avoids losing the * original file when trying to make a backup when writing the file a * second time. * When "backup_copy" is set we need to copy the backup over the new * file. Otherwise rename the backup file. * If this is OK, don't give the extra warning message. */ if (backup != NULL) { if (backup_copy) { /* This may take a while, if we were interrupted let the user * know we got the message. */ if (got_int) { MSG(_(e_interr)); out_flush(); } if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0) { if ((write_info.bw_fd = mch_open((char *)fname, O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA, perm & 0777)) >= 0) { /* copy the file. */ write_info.bw_buf = smallbuf; #ifdef HAS_BW_FLAGS write_info.bw_flags = FIO_NOCONVERT; #endif while ((write_info.bw_len = read_eintr(fd, smallbuf, SMBUFSIZE)) > 0) if (buf_write_bytes(&write_info) == FAIL) break; if (close(write_info.bw_fd) >= 0 && write_info.bw_len == 0) end = 1; /* success */ } close(fd); /* ignore errors for closing read file */ } } else { if (vim_rename(backup, fname) == 0) end = 1; } } goto fail; } lnum -= start; /* compute number of written lines */ --no_wait_return; /* may wait for return now */ #if !(defined(UNIX) || defined(VMS)) fname = sfname; /* use shortname now, for the messages */ #endif if (!filtering) { msg_add_fname(buf, fname); /* put fname in IObuff with quotes */ c = FALSE; #ifdef FEAT_MBYTE if (write_info.bw_conv_error) { STRCAT(IObuff, _(" CONVERSION ERROR")); c = TRUE; if (write_info.bw_conv_error_lnum != 0) vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"), (long)write_info.bw_conv_error_lnum); } else if (notconverted) { STRCAT(IObuff, _("[NOT converted]")); c = TRUE; } else if (converted) { STRCAT(IObuff, _("[converted]")); c = TRUE; } #endif if (device) { STRCAT(IObuff, _("[Device]")); c = TRUE; } else if (newfile) { STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]")); c = TRUE; } if (no_eol) { msg_add_eol(); c = TRUE; } /* may add [unix/dos/mac] */ if (msg_add_fileformat(fileformat)) c = TRUE; #ifdef FEAT_CRYPT if (wb_flags & FIO_ENCRYPTED) { if (crypt_method_used == 1) STRCAT(IObuff, _("[blowfish]")); else STRCAT(IObuff, _("[crypted]")); c = TRUE; } #endif msg_add_lines(c, (long)lnum, nchars); /* add line/char count */ if (!shortmess(SHM_WRITE)) { if (append) STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended")); else STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written")); } set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0); } /* When written everything correctly: reset 'modified'. Unless not * writing to the original file and '+' is not in 'cpoptions'. */ if (reset_changed && whole && !append #ifdef FEAT_MBYTE && !write_info.bw_conv_error #endif && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL) ) { unchanged(buf, TRUE); u_unchanged(buf); u_update_save_nr(buf); } /* * If written to the current file, update the timestamp of the swap file * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime. */ if (overwriting) { ml_timestamp(buf); if (append) buf->b_flags &= ~BF_NEW; else buf->b_flags &= ~BF_WRITE_MASK; } /* * If we kept a backup until now, and we are in patch mode, then we make * the backup file our 'original' file. */ if (*p_pm && dobackup) { char *org = (char *)buf_modname( #ifdef SHORT_FNAME TRUE, #else (buf->b_p_sn || buf->b_shortname), #endif fname, p_pm, FALSE); if (backup != NULL) { struct stat st; /* * If the original file does not exist yet * the current backup file becomes the original file */ if (org == NULL) EMSG(_("E205: Patchmode: can't save original file")); else if (mch_stat(org, &st) < 0) { vim_rename(backup, (char_u *)org); vim_free(backup); /* don't delete the file */ backup = NULL; #ifdef UNIX set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime); #endif } } /* * If there is no backup file, remember that a (new) file was * created. */ else { int empty_fd; if (org == NULL || (empty_fd = mch_open(org, O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW, perm < 0 ? 0666 : (perm & 0777))) < 0) EMSG(_("E206: patchmode: can't touch empty original file")); else close(empty_fd); } if (org != NULL) { mch_setperm((char_u *)org, mch_getperm(fname) & 0777); vim_free(org); } } /* * Remove the backup unless 'backup' option is set */ if (!p_bk && backup != NULL && mch_remove(backup) != 0) EMSG(_("E207: Can't delete backup file")); #ifdef FEAT_SUN_WORKSHOP if (usingSunWorkShop) workshop_file_saved((char *) ffname); #endif goto nofail; /* * Finish up. We get here either after failure or success. */ fail: --no_wait_return; /* may wait for return now */ nofail: /* Done saving, we accept changed buffer warnings again */ buf->b_saving = FALSE; vim_free(backup); if (buffer != smallbuf) vim_free(buffer); #ifdef FEAT_MBYTE vim_free(fenc_tofree); vim_free(write_info.bw_conv_buf); # ifdef USE_ICONV if (write_info.bw_iconv_fd != (iconv_t)-1) { iconv_close(write_info.bw_iconv_fd); write_info.bw_iconv_fd = (iconv_t)-1; } # endif #endif #ifdef HAVE_ACL mch_free_acl(acl); #endif if (errmsg != NULL) { int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0; attr = hl_attr(HLF_E); /* set highlight for error messages */ msg_add_fname(buf, #ifndef UNIX sfname #else fname #endif ); /* put file name in IObuff with quotes */ if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE) IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL; /* If the error message has the form "is ...", put the error number in * front of the file name. */ if (errnum != NULL) { STRMOVE(IObuff + numlen, IObuff); mch_memmove(IObuff, errnum, (size_t)numlen); } STRCAT(IObuff, errmsg); emsg(IObuff); if (errmsg_allocated) vim_free(errmsg); retval = FAIL; if (end == 0) { MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"), attr | MSG_HIST); MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"), attr | MSG_HIST); /* Update the timestamp to avoid an "overwrite changed file" * prompt when writing again. */ if (mch_stat((char *)fname, &st_old) >= 0) { buf_store_time(buf, &st_old, fname); buf->b_mtime_read = buf->b_mtime; } } } msg_scroll = msg_save; #ifdef FEAT_PERSISTENT_UNDO /* * When writing the whole file and 'undofile' is set, also write the undo * file. */ if (retval == OK && write_undo_file) { char_u hash[UNDO_HASH_SIZE]; sha256_finish(&sha_ctx, hash); u_write_undo(NULL, FALSE, buf, hash); } #endif #ifdef FEAT_AUTOCMD #ifdef FEAT_EVAL if (!should_abort(retval)) #else if (!got_int) #endif { aco_save_T aco; curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */ /* * Apply POST autocommands. * Careful: The autocommands may call buf_write() recursively! */ aucmd_prepbuf(&aco, buf); if (append) apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname, FALSE, curbuf, eap); else if (filtering) apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname, FALSE, curbuf, eap); else if (reset_changed && whole) apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname, FALSE, curbuf, eap); else apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname, FALSE, curbuf, eap); /* restore curwin/curbuf and a few other things */ aucmd_restbuf(&aco); #ifdef FEAT_EVAL if (aborting()) /* autocmds may abort script processing */ retval = FALSE; #endif } #endif got_int |= prev_got_int; #ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */ /* Update machine specific information. */ mch_post_buffer_write(buf); #endif return retval; } /* * Set the name of the current buffer. Use when the buffer doesn't have a * name and a ":r" or ":w" command with a file name is used. */ static int set_rw_fname(fname, sfname) char_u *fname; char_u *sfname; { #ifdef FEAT_AUTOCMD buf_T *buf = curbuf; /* It's like the unnamed buffer is deleted.... */ if (curbuf->b_p_bl) apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf); apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf); # ifdef FEAT_EVAL if (aborting()) /* autocmds may abort script processing */ return FAIL; # endif if (curbuf != buf) { /* We are in another buffer now, don't do the renaming. */ EMSG(_(e_auchangedbuf)); return FAIL; } #endif if (setfname(curbuf, fname, sfname, FALSE) == OK) curbuf->b_flags |= BF_NOTEDITED; #ifdef FEAT_AUTOCMD /* ....and a new named one is created */ apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf); if (curbuf->b_p_bl) apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf); # ifdef FEAT_EVAL if (aborting()) /* autocmds may abort script processing */ return FAIL; # endif /* Do filetype detection now if 'filetype' is empty. */ if (*curbuf->b_p_ft == NUL) { if (au_has_group((char_u *)"filetypedetect")) (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE); do_modelines(0); } #endif return OK; } /* * Put file name into IObuff with quotes. */ void msg_add_fname(buf, fname) buf_T *buf; char_u *fname; { if (fname == NULL) fname = (char_u *)"-stdin-"; home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE); IObuff[0] = '"'; STRCAT(IObuff, "\" "); } /* * Append message for text mode to IObuff. * Return TRUE if something appended. */ static int msg_add_fileformat(eol_type) int eol_type; { #ifndef USE_CRNL if (eol_type == EOL_DOS) { STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]")); return TRUE; } #endif #ifndef USE_CR if (eol_type == EOL_MAC) { STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]")); return TRUE; } #endif #if defined(USE_CRNL) || defined(USE_CR) if (eol_type == EOL_UNIX) { STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]")); return TRUE; } #endif return FALSE; } /* * Append line and character count to IObuff. */ void msg_add_lines(insert_space, lnum, nchars) int insert_space; long lnum; off_t nchars; { char_u *p; p = IObuff + STRLEN(IObuff); if (insert_space) *p++ = ' '; if (shortmess(SHM_LINES)) sprintf((char *)p, #ifdef LONG_LONG_OFF_T "%ldL, %lldC", lnum, nchars #else /* Explicit typecast avoids warning on Mac OS X 10.6 */ "%ldL, %ldC", lnum, (long)nchars #endif ); else { if (lnum == 1) STRCPY(p, _("1 line, ")); else sprintf((char *)p, _("%ld lines, "), lnum); p += STRLEN(p); if (nchars == 1) STRCPY(p, _("1 character")); else sprintf((char *)p, #ifdef LONG_LONG_OFF_T _("%lld characters"), nchars #else /* Explicit typecast avoids warning on Mac OS X 10.6 */ _("%ld characters"), (long)nchars #endif ); } } /* * Append message for missing line separator to IObuff. */ static void msg_add_eol() { STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]")); } /* * Check modification time of file, before writing to it. * The size isn't checked, because using a tool like "gzip" takes care of * using the same timestamp but can't set the size. */ static int check_mtime(buf, st) buf_T *buf; struct stat *st; { if (buf->b_mtime_read != 0 && time_differs((long)st->st_mtime, buf->b_mtime_read)) { msg_scroll = TRUE; /* don't overwrite messages here */ msg_silent = 0; /* must give this prompt */ /* don't use emsg() here, don't want to flush the buffers */ MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"), hl_attr(HLF_E)); if (ask_yesno((char_u *)_("Do you really want to write to it"), TRUE) == 'n') return FAIL; msg_scroll = FALSE; /* always overwrite the file message now */ } return OK; } static int time_differs(t1, t2) long t1, t2; { #if defined(__linux__) || defined(MSDOS) || defined(MSWIN) /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store * the seconds. Since the roundoff is done when flushing the inode, the * time may change unexpectedly by one second!!! */ return (t1 - t2 > 1 || t2 - t1 > 1); #else return (t1 != t2); #endif } /* * Call write() to write a number of bytes to the file. * Handles encryption and 'encoding' conversion. * * Return FAIL for failure, OK otherwise. */ static int buf_write_bytes(ip) struct bw_info *ip; { int wlen; char_u *buf = ip->bw_buf; /* data to write */ int len = ip->bw_len; /* length of data */ #ifdef HAS_BW_FLAGS int flags = ip->bw_flags; /* extra flags */ #endif #ifdef FEAT_MBYTE /* * Skip conversion when writing the crypt magic number or the BOM. */ if (!(flags & FIO_NOCONVERT)) { char_u *p; unsigned c; int n; if (flags & FIO_UTF8) { /* * Convert latin1 in the buffer to UTF-8 in the file. */ p = ip->bw_conv_buf; /* translate to buffer */ for (wlen = 0; wlen < len; ++wlen) p += utf_char2bytes(buf[wlen], p); buf = ip->bw_conv_buf; len = (int)(p - ip->bw_conv_buf); } else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1)) { /* * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or * Latin1 chars in the file. */ if (flags & FIO_LATIN1) p = buf; /* translate in-place (can only get shorter) */ else p = ip->bw_conv_buf; /* translate to buffer */ for (wlen = 0; wlen < len; wlen += n) { if (wlen == 0 && ip->bw_restlen != 0) { int l; /* Use remainder of previous call. Append the start of * buf[] to get a full sequence. Might still be too * short! */ l = CONV_RESTLEN - ip->bw_restlen; if (l > len) l = len; mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l); n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l); if (n > ip->bw_restlen + len) { /* We have an incomplete byte sequence at the end to * be written. We can't convert it without the * remaining bytes. Keep them for the next call. */ if (ip->bw_restlen + len > CONV_RESTLEN) return FAIL; ip->bw_restlen += len; break; } if (n > 1) c = utf_ptr2char(ip->bw_rest); else c = ip->bw_rest[0]; if (n >= ip->bw_restlen) { n -= ip->bw_restlen; ip->bw_restlen = 0; } else { ip->bw_restlen -= n; mch_memmove(ip->bw_rest, ip->bw_rest + n, (size_t)ip->bw_restlen); n = 0; } } else { n = utf_ptr2len_len(buf + wlen, len - wlen); if (n > len - wlen) { /* We have an incomplete byte sequence at the end to * be written. We can't convert it without the * remaining bytes. Keep them for the next call. */ if (len - wlen > CONV_RESTLEN) return FAIL; ip->bw_restlen = len - wlen; mch_memmove(ip->bw_rest, buf + wlen, (size_t)ip->bw_restlen); break; } if (n > 1) c = utf_ptr2char(buf + wlen); else c = buf[wlen]; } if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error) { ip->bw_conv_error = TRUE; ip->bw_conv_error_lnum = ip->bw_start_lnum; } if (c == NL) ++ip->bw_start_lnum; } if (flags & FIO_LATIN1) len = (int)(p - buf); else { buf = ip->bw_conv_buf; len = (int)(p - ip->bw_conv_buf); } } # ifdef WIN3264 else if (flags & FIO_CODEPAGE) { /* * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows * codepage. */ char_u *from; size_t fromlen; char_u *to; int u8c; BOOL bad = FALSE; int needed; if (ip->bw_restlen > 0) { /* Need to concatenate the remainder of the previous call and * the bytes of the current call. Use the end of the * conversion buffer for this. */ fromlen = len + ip->bw_restlen; from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen; mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen); mch_memmove(from + ip->bw_restlen, buf, (size_t)len); } else { from = buf; fromlen = len; } to = ip->bw_conv_buf; if (enc_utf8) { /* Convert from UTF-8 to UCS-2, to the start of the buffer. * The buffer has been allocated to be big enough. */ while (fromlen > 0) { n = (int)utf_ptr2len_len(from, (int)fromlen); if (n > (int)fromlen) /* incomplete byte sequence */ break; u8c = utf_ptr2char(from); *to++ = (u8c & 0xff); *to++ = (u8c >> 8); fromlen -= n; from += n; } /* Copy remainder to ip->bw_rest[] to be used for the next * call. */ if (fromlen > CONV_RESTLEN) { /* weird overlong sequence */ ip->bw_conv_error = TRUE; return FAIL; } mch_memmove(ip->bw_rest, from, fromlen); ip->bw_restlen = (int)fromlen; } else { /* Convert from enc_codepage to UCS-2, to the start of the * buffer. The buffer has been allocated to be big enough. */ ip->bw_restlen = 0; needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen, NULL, 0); if (needed == 0) { /* When conversion fails there may be a trailing byte. */ needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1, NULL, 0); if (needed == 0) { /* Conversion doesn't work. */ ip->bw_conv_error = TRUE; return FAIL; } /* Save the trailing byte for the next call. */ ip->bw_rest[0] = from[fromlen - 1]; ip->bw_restlen = 1; } needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)(fromlen - ip->bw_restlen), (LPWSTR)to, needed); if (needed == 0) { /* Safety check: Conversion doesn't work. */ ip->bw_conv_error = TRUE; return FAIL; } to += needed * 2; } fromlen = to - ip->bw_conv_buf; buf = to; # ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */ if (FIO_GET_CP(flags) == CP_UTF8) { /* Convert from UCS-2 to UTF-8, using the remainder of the * conversion buffer. Fails when out of space. */ for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2) { u8c = *from++; u8c += (*from++ << 8); to += utf_char2bytes(u8c, to); if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen) { ip->bw_conv_error = TRUE; return FAIL; } } len = (int)(to - buf); } else #endif { /* Convert from UCS-2 to the codepage, using the remainder of * the conversion buffer. If the conversion uses the default * character "0", the data doesn't fit in this encoding, so * fail. */ len = WideCharToMultiByte(FIO_GET_CP(flags), 0, (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR), (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0, &bad); if (bad) { ip->bw_conv_error = TRUE; return FAIL; } } } # endif # ifdef MACOS_CONVERT else if (flags & FIO_MACROMAN) { /* * Convert UTF-8 or latin1 to Apple MacRoman. */ char_u *from; size_t fromlen; if (ip->bw_restlen > 0) { /* Need to concatenate the remainder of the previous call and * the bytes of the current call. Use the end of the * conversion buffer for this. */ fromlen = len + ip->bw_restlen; from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen; mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen); mch_memmove(from + ip->bw_restlen, buf, (size_t)len); } else { from = buf; fromlen = len; } if (enc2macroman(from, fromlen, ip->bw_conv_buf, &len, ip->bw_conv_buflen, ip->bw_rest, &ip->bw_restlen) == FAIL) { ip->bw_conv_error = TRUE; return FAIL; } buf = ip->bw_conv_buf; } # endif # ifdef USE_ICONV if (ip->bw_iconv_fd != (iconv_t)-1) { const char *from; size_t fromlen; char *to; size_t tolen; /* Convert with iconv(). */ if (ip->bw_restlen > 0) { char *fp; /* Need to concatenate the remainder of the previous call and * the bytes of the current call. Use the end of the * conversion buffer for this. */ fromlen = len + ip->bw_restlen; fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen; mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen); mch_memmove(fp + ip->bw_restlen, buf, (size_t)len); from = fp; tolen = ip->bw_conv_buflen - fromlen; } else { from = (const char *)buf; fromlen = len; tolen = ip->bw_conv_buflen; } to = (char *)ip->bw_conv_buf; if (ip->bw_first) { size_t save_len = tolen; /* output the initial shift state sequence */ (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen); /* There is a bug in iconv() on Linux (which appears to be * wide-spread) which sets "to" to NULL and messes up "tolen". */ if (to == NULL) { to = (char *)ip->bw_conv_buf; tolen = save_len; } ip->bw_first = FALSE; } /* * If iconv() has an error or there is not enough room, fail. */ if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen) == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL) || fromlen > CONV_RESTLEN) { ip->bw_conv_error = TRUE; return FAIL; } /* copy remainder to ip->bw_rest[] to be used for the next call. */ if (fromlen > 0) mch_memmove(ip->bw_rest, (void *)from, fromlen); ip->bw_restlen = (int)fromlen; buf = ip->bw_conv_buf; len = (int)((char_u *)to - ip->bw_conv_buf); } # endif } #endif /* FEAT_MBYTE */ #ifdef FEAT_CRYPT if (flags & FIO_ENCRYPTED) /* encrypt the data */ crypt_encode(buf, len, buf); #endif wlen = write_eintr(ip->bw_fd, buf, len); return (wlen < len) ? FAIL : OK; } #ifdef FEAT_MBYTE /* * Convert a Unicode character to bytes. * Return TRUE for an error, FALSE when it's OK. */ static int ucs2bytes(c, pp, flags) unsigned c; /* in: character */ char_u **pp; /* in/out: pointer to result */ int flags; /* FIO_ flags */ { char_u *p = *pp; int error = FALSE; int cc; if (flags & FIO_UCS4) { if (flags & FIO_ENDIAN_L) { *p++ = c; *p++ = (c >> 8); *p++ = (c >> 16); *p++ = (c >> 24); } else { *p++ = (c >> 24); *p++ = (c >> 16); *p++ = (c >> 8); *p++ = c; } } else if (flags & (FIO_UCS2 | FIO_UTF16)) { if (c >= 0x10000) { if (flags & FIO_UTF16) { /* Make two words, ten bits of the character in each. First * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */ c -= 0x10000; if (c >= 0x100000) error = TRUE; cc = ((c >> 10) & 0x3ff) + 0xd800; if (flags & FIO_ENDIAN_L) { *p++ = cc; *p++ = ((unsigned)cc >> 8); } else { *p++ = ((unsigned)cc >> 8); *p++ = cc; } c = (c & 0x3ff) + 0xdc00; } else error = TRUE; } if (flags & FIO_ENDIAN_L) { *p++ = c; *p++ = (c >> 8); } else { *p++ = (c >> 8); *p++ = c; } } else /* Latin1 */ { if (c >= 0x100) { error = TRUE; *p++ = 0xBF; } else *p++ = c; } *pp = p; return error; } /* * Return TRUE if file encoding "fenc" requires conversion from or to * 'encoding'. */ static int need_conversion(fenc) char_u *fenc; { int same_encoding; int enc_flags; int fenc_flags; if (*fenc == NUL || STRCMP(p_enc, fenc) == 0) { same_encoding = TRUE; fenc_flags = 0; } else { /* Ignore difference between "ansi" and "latin1", "ucs-4" and * "ucs-4be", etc. */ enc_flags = get_fio_flags(p_enc); fenc_flags = get_fio_flags(fenc); same_encoding = (enc_flags != 0 && fenc_flags == enc_flags); } if (same_encoding) { /* Specified encoding matches with 'encoding'. This requires * conversion when 'encoding' is Unicode but not UTF-8. */ return enc_unicode != 0; } /* Encodings differ. However, conversion is not needed when 'enc' is any * Unicode encoding and the file is UTF-8. */ return !(enc_utf8 && fenc_flags == FIO_UTF8); } /* * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the * internal conversion. * if "ptr" is an empty string, use 'encoding'. */ static int get_fio_flags(ptr) char_u *ptr; { int prop; if (*ptr == NUL) ptr = p_enc; prop = enc_canon_props(ptr); if (prop & ENC_UNICODE) { if (prop & ENC_2BYTE) { if (prop & ENC_ENDIAN_L) return FIO_UCS2 | FIO_ENDIAN_L; return FIO_UCS2; } if (prop & ENC_4BYTE) { if (prop & ENC_ENDIAN_L) return FIO_UCS4 | FIO_ENDIAN_L; return FIO_UCS4; } if (prop & ENC_2WORD) { if (prop & ENC_ENDIAN_L) return FIO_UTF16 | FIO_ENDIAN_L; return FIO_UTF16; } return FIO_UTF8; } if (prop & ENC_LATIN1) return FIO_LATIN1; /* must be ENC_DBCS, requires iconv() */ return 0; } #ifdef WIN3264 /* * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed * for the conversion MS-Windows can do for us. Also accept "utf-8". * Used for conversion between 'encoding' and 'fileencoding'. */ static int get_win_fio_flags(ptr) char_u *ptr; { int cp; /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */ if (!enc_utf8 && enc_codepage <= 0) return 0; cp = encname2codepage(ptr); if (cp == 0) { # ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */ if (STRCMP(ptr, "utf-8") == 0) cp = CP_UTF8; else # endif return 0; } return FIO_PUT_CP(cp) | FIO_CODEPAGE; } #endif #ifdef MACOS_X /* * Check "ptr" for a Carbon supported encoding and return the FIO_ flags * needed for the internal conversion to/from utf-8 or latin1. */ static int get_mac_fio_flags(ptr) char_u *ptr; { if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0) && (enc_canon_props(ptr) & ENC_MACROMAN)) return FIO_MACROMAN; return 0; } #endif /* * Check for a Unicode BOM (Byte Order Mark) at the start of p[size]. * "size" must be at least 2. * Return the name of the encoding and set "*lenp" to the length. * Returns NULL when no BOM found. */ static char_u * check_for_bom(p, size, lenp, flags) char_u *p; long size; int *lenp; int flags; { char *name = NULL; int len = 2; if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0)) { name = "utf-8"; /* EF BB BF */ len = 3; } else if (p[0] == 0xff && p[1] == 0xfe) { if (size >= 4 && p[2] == 0 && p[3] == 0 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L))) { name = "ucs-4le"; /* FF FE 00 00 */ len = 4; } else if (flags == (FIO_UCS2 | FIO_ENDIAN_L)) name = "ucs-2le"; /* FF FE */ else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L)) /* utf-16le is preferred, it also works for ucs-2le text */ name = "utf-16le"; /* FF FE */ } else if (p[0] == 0xfe && p[1] == 0xff && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16)) { /* Default to utf-16, it works also for ucs-2 text. */ if (flags == FIO_UCS2) name = "ucs-2"; /* FE FF */ else name = "utf-16"; /* FE FF */ } else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4)) { name = "ucs-4"; /* 00 00 FE FF */ len = 4; } *lenp = len; return (char_u *)name; } /* * Generate a BOM in "buf[4]" for encoding "name". * Return the length of the BOM (zero when no BOM). */ static int make_bom(buf, name) char_u *buf; char_u *name; { int flags; char_u *p; flags = get_fio_flags(name); /* Can't put a BOM in a non-Unicode file. */ if (flags == FIO_LATIN1 || flags == 0) return 0; if (flags == FIO_UTF8) /* UTF-8 */ { buf[0] = 0xef; buf[1] = 0xbb; buf[2] = 0xbf; return 3; } p = buf; (void)ucs2bytes(0xfeff, &p, flags); return (int)(p - buf); } #endif #if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \ defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO) /* * Try to find a shortname by comparing the fullname with the current * directory. * Returns "full_path" or pointer into "full_path" if shortened. */ char_u * shorten_fname1(full_path) char_u *full_path; { char_u *dirname; char_u *p = full_path; dirname = alloc(MAXPATHL); if (dirname == NULL) return full_path; if (mch_dirname(dirname, MAXPATHL) == OK) { p = shorten_fname(full_path, dirname); if (p == NULL || *p == NUL) p = full_path; } vim_free(dirname); return p; } #endif /* * Try to find a shortname by comparing the fullname with the current * directory. * Returns NULL if not shorter name possible, pointer into "full_path" * otherwise. */ char_u * shorten_fname(full_path, dir_name) char_u *full_path; char_u *dir_name; { int len; char_u *p; if (full_path == NULL) return NULL; len = (int)STRLEN(dir_name); if (fnamencmp(dir_name, full_path, len) == 0) { p = full_path + len; #if defined(MSDOS) || defined(MSWIN) || defined(OS2) /* * MSDOS: when a file is in the root directory, dir_name will end in a * slash, since C: by itself does not define a specific dir. In this * case p may already be correct. <negri> */ if (!((len > 2) && (*(p - 2) == ':'))) #endif { if (vim_ispathsep(*p)) ++p; #ifndef VMS /* the path separator is always part of the path */ else p = NULL; #endif } } #if defined(MSDOS) || defined(MSWIN) || defined(OS2) /* * When using a file in the current drive, remove the drive name: * "A:\dir\file" -> "\dir\file". This helps when moving a session file on * a floppy from "A:\dir" to "B:\dir". */ else if (len > 3 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0]) && full_path[1] == ':' && vim_ispathsep(full_path[2])) p = full_path + 2; #endif else p = NULL; return p; } /* * Shorten filenames for all buffers. * When "force" is TRUE: Use full path from now on for files currently being * edited, both for file name and swap file name. Try to shorten the file * names a bit, if safe to do so. * When "force" is FALSE: Only try to shorten absolute file names. * For buffers that have buftype "nofile" or "scratch": never change the file * name. */ void shorten_fnames(force) int force; { char_u dirname[MAXPATHL]; buf_T *buf; char_u *p; mch_dirname(dirname, MAXPATHL); for (buf = firstbuf; buf != NULL; buf = buf->b_next) { if (buf->b_fname != NULL #ifdef FEAT_QUICKFIX && !bt_nofile(buf) #endif && !path_with_url(buf->b_fname) && (force || buf->b_sfname == NULL || mch_isFullName(buf->b_sfname))) { vim_free(buf->b_sfname); buf->b_sfname = NULL; p = shorten_fname(buf->b_ffname, dirname); if (p != NULL) { buf->b_sfname = vim_strsave(p); buf->b_fname = buf->b_sfname; } if (p == NULL || buf->b_fname == NULL) buf->b_fname = buf->b_ffname; } /* Always make the swap file name a full path, a "nofile" buffer may * also have a swap file. */ mf_fullname(buf->b_ml.ml_mfp); } #ifdef FEAT_WINDOWS status_redraw_all(); redraw_tabline = TRUE; #endif } #if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \ || defined(FEAT_GUI_MSWIN) \ || defined(FEAT_GUI_MAC) \ || defined(PROTO) /* * Shorten all filenames in "fnames[count]" by current directory. */ void shorten_filenames(fnames, count) char_u **fnames; int count; { int i; char_u dirname[MAXPATHL]; char_u *p; if (fnames == NULL || count < 1) return; mch_dirname(dirname, sizeof(dirname)); for (i = 0; i < count; ++i) { if ((p = shorten_fname(fnames[i], dirname)) != NULL) { /* shorten_fname() returns pointer in given "fnames[i]". If free * "fnames[i]" first, "p" becomes invalid. So we need to copy * "p" first then free fnames[i]. */ p = vim_strsave(p); vim_free(fnames[i]); fnames[i] = p; } } } #endif /* * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or * fo_o_h.ext for MSDOS or when shortname option set. * * Assumed that fname is a valid name found in the filesystem we assure that * the return value is a different name and ends in 'ext'. * "ext" MUST be at most 4 characters long if it starts with a dot, 3 * characters otherwise. * Space for the returned name is allocated, must be freed later. * Returns NULL when out of memory. */ char_u * modname(fname, ext, prepend_dot) char_u *fname, *ext; int prepend_dot; /* may prepend a '.' to file name */ { return buf_modname( #ifdef SHORT_FNAME TRUE, #else (curbuf->b_p_sn || curbuf->b_shortname), #endif fname, ext, prepend_dot); } char_u * buf_modname(shortname, fname, ext, prepend_dot) int shortname; /* use 8.3 file name */ char_u *fname, *ext; int prepend_dot; /* may prepend a '.' to file name */ { char_u *retval; char_u *s; char_u *e; char_u *ptr; int fnamelen, extlen; extlen = (int)STRLEN(ext); /* * If there is no file name we must get the name of the current directory * (we need the full path in case :cd is used). */ if (fname == NULL || *fname == NUL) { retval = alloc((unsigned)(MAXPATHL + extlen + 3)); if (retval == NULL) return NULL; if (mch_dirname(retval, MAXPATHL) == FAIL || (fnamelen = (int)STRLEN(retval)) == 0) { vim_free(retval); return NULL; } if (!after_pathsep(retval, retval + fnamelen)) { retval[fnamelen++] = PATHSEP; retval[fnamelen] = NUL; } #ifndef SHORT_FNAME prepend_dot = FALSE; /* nothing to prepend a dot to */ #endif } else { fnamelen = (int)STRLEN(fname); retval = alloc((unsigned)(fnamelen + extlen + 3)); if (retval == NULL) return NULL; STRCPY(retval, fname); #ifdef VMS vms_remove_version(retval); /* we do not need versions here */ #endif } /* * search backwards until we hit a '/', '\' or ':' replacing all '.' * by '_' for MSDOS or when shortname option set and ext starts with a dot. * Then truncate what is after the '/', '\' or ':' to 8 characters for * MSDOS and 26 characters for AMIGA, a lot more for UNIX. */ for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr)) { if (*ext == '.' #ifdef USE_LONG_FNAME && (!USE_LONG_FNAME || shortname) #else # ifndef SHORT_FNAME && shortname # endif #endif ) if (*ptr == '.') /* replace '.' by '_' */ *ptr = '_'; if (vim_ispathsep(*ptr)) { ++ptr; break; } } /* the file name has at most BASENAMELEN characters. */ #ifndef SHORT_FNAME if (STRLEN(ptr) > (unsigned)BASENAMELEN) ptr[BASENAMELEN] = '\0'; #endif s = ptr + STRLEN(ptr); /* * For 8.3 file names we may have to reduce the length. */ #ifdef USE_LONG_FNAME if (!USE_LONG_FNAME || shortname) #else # ifndef SHORT_FNAME if (shortname) # endif #endif { /* * If there is no file name, or the file name ends in '/', and the * extension starts with '.', put a '_' before the dot, because just * ".ext" is invalid. */ if (fname == NULL || *fname == NUL || vim_ispathsep(fname[STRLEN(fname) - 1])) { if (*ext == '.') *s++ = '_'; } /* * If the extension starts with '.', truncate the base name at 8 * characters */ else if (*ext == '.') { if ((size_t)(s - ptr) > (size_t)8) { s = ptr + 8; *s = '\0'; } } /* * If the extension doesn't start with '.', and the file name * doesn't have an extension yet, append a '.' */ else if ((e = vim_strchr(ptr, '.')) == NULL) *s++ = '.'; /* * If the extension doesn't start with '.', and there already is an * extension, it may need to be truncated */ else if ((int)STRLEN(e) + extlen > 4) s = e + 4 - extlen; } #if defined(OS2) || defined(USE_LONG_FNAME) || defined(WIN3264) /* * If there is no file name, and the extension starts with '.', put a * '_' before the dot, because just ".ext" may be invalid if it's on a * FAT partition, and on HPFS it doesn't matter. */ else if ((fname == NULL || *fname == NUL) && *ext == '.') *s++ = '_'; #endif /* * Append the extension. * ext can start with '.' and cannot exceed 3 more characters. */ STRCPY(s, ext); #ifndef SHORT_FNAME /* * Prepend the dot. */ if (prepend_dot && !shortname && *(e = gettail(retval)) != '.' #ifdef USE_LONG_FNAME && USE_LONG_FNAME #endif ) { STRMOVE(e + 1, e); *e = '.'; } #endif /* * Check that, after appending the extension, the file name is really * different. */ if (fname != NULL && STRCMP(fname, retval) == 0) { /* we search for a character that can be replaced by '_' */ while (--s >= ptr) { if (*s != '_') { *s = '_'; break; } } if (s < ptr) /* fname was "________.<ext>", how tricky! */ *ptr = 'v'; } return retval; } /* * Like fgets(), but if the file line is too long, it is truncated and the * rest of the line is thrown away. Returns TRUE for end-of-file. */ int vim_fgets(buf, size, fp) char_u *buf; int size; FILE *fp; { char *eof; #define FGETS_SIZE 200 char tbuf[FGETS_SIZE]; buf[size - 2] = NUL; #ifdef USE_CR eof = fgets_cr((char *)buf, size, fp); #else eof = fgets((char *)buf, size, fp); #endif if (buf[size - 2] != NUL && buf[size - 2] != '\n') { buf[size - 1] = NUL; /* Truncate the line */ /* Now throw away the rest of the line: */ do { tbuf[FGETS_SIZE - 2] = NUL; #ifdef USE_CR ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp); #else ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp); #endif } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n'); } return (eof == NULL); } #if defined(USE_CR) || defined(PROTO) /* * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF. * Returns TRUE for end-of-file. * Only used for the Mac, because it's much slower than vim_fgets(). */ int tag_fgets(buf, size, fp) char_u *buf; int size; FILE *fp; { int i = 0; int c; int eof = FALSE; for (;;) { c = fgetc(fp); if (c == EOF) { eof = TRUE; break; } if (c == '\r') { /* Always store a NL for end-of-line. */ if (i < size - 1) buf[i++] = '\n'; c = fgetc(fp); if (c != '\n') /* Macintosh format: single CR. */ ungetc(c, fp); break; } if (i < size - 1) buf[i++] = c; if (c == '\n') break; } buf[i] = NUL; return eof; } #endif /* * rename() only works if both files are on the same file system, this * function will (attempts to?) copy the file across if rename fails -- webb * Return -1 for failure, 0 for success. */ int vim_rename(from, to) char_u *from; char_u *to; { int fd_in; int fd_out; int n; char *errmsg = NULL; char *buffer; #ifdef AMIGA BPTR flock; #endif struct stat st; long perm; #ifdef HAVE_ACL vim_acl_T acl; /* ACL from original file */ #endif #if defined(UNIX) || defined(CASE_INSENSITIVE_FILENAME) int use_tmp_file = FALSE; #endif /* * When the names are identical, there is nothing to do. When they refer * to the same file (ignoring case and slash/backslash differences) but * the file name differs we need to go through a temp file. */ if (fnamecmp(from, to) == 0) { #ifdef CASE_INSENSITIVE_FILENAME if (STRCMP(gettail(from), gettail(to)) != 0) use_tmp_file = TRUE; else #endif return 0; } /* * Fail if the "from" file doesn't exist. Avoids that "to" is deleted. */ if (mch_stat((char *)from, &st) < 0) return -1; #ifdef UNIX { struct stat st_to; /* It's possible for the source and destination to be the same file. * This happens when "from" and "to" differ in case and are on a FAT32 * filesystem. In that case go through a temp file name. */ if (mch_stat((char *)to, &st_to) >= 0 && st.st_dev == st_to.st_dev && st.st_ino == st_to.st_ino) use_tmp_file = TRUE; } #endif #ifdef WIN3264 { BY_HANDLE_FILE_INFORMATION info1, info2; /* It's possible for the source and destination to be the same file. * In that case go through a temp file name. This makes rename("foo", * "./foo") a no-op (in a complicated way). */ if (win32_fileinfo(from, &info1) == FILEINFO_OK && win32_fileinfo(to, &info2) == FILEINFO_OK && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber && info1.nFileIndexHigh == info2.nFileIndexHigh && info1.nFileIndexLow == info2.nFileIndexLow) use_tmp_file = TRUE; } #endif #if defined(UNIX) || defined(CASE_INSENSITIVE_FILENAME) if (use_tmp_file) { char tempname[MAXPATHL + 1]; /* * Find a name that doesn't exist and is in the same directory. * Rename "from" to "tempname" and then rename "tempname" to "to". */ if (STRLEN(from) >= MAXPATHL - 5) return -1; STRCPY(tempname, from); for (n = 123; n < 99999; ++n) { sprintf((char *)gettail((char_u *)tempname), "%d", n); if (mch_stat(tempname, &st) < 0) { if (mch_rename((char *)from, tempname) == 0) { if (mch_rename(tempname, (char *)to) == 0) return 0; /* Strange, the second step failed. Try moving the * file back and return failure. */ mch_rename(tempname, (char *)from); return -1; } /* If it fails for one temp name it will most likely fail * for any temp name, give up. */ return -1; } } return -1; } #endif /* * Delete the "to" file, this is required on some systems to make the * mch_rename() work, on other systems it makes sure that we don't have * two files when the mch_rename() fails. */ #ifdef AMIGA /* * With MSDOS-compatible filesystems (crossdos, messydos) it is possible * that the name of the "to" file is the same as the "from" file, even * though the names are different. To avoid the chance of accidentally * deleting the "from" file (horror!) we lock it during the remove. * * When used for making a backup before writing the file: This should not * happen with ":w", because startscript() should detect this problem and * set buf->b_shortname, causing modname() to return a correct ".bak" file * name. This problem does exist with ":w filename", but then the * original file will be somewhere else so the backup isn't really * important. If autoscripting is off the rename may fail. */ flock = Lock((UBYTE *)from, (long)ACCESS_READ); #endif mch_remove(to); #ifdef AMIGA if (flock) UnLock(flock); #endif /* * First try a normal rename, return if it works. */ if (mch_rename((char *)from, (char *)to) == 0) return 0; /* * Rename() failed, try copying the file. */ perm = mch_getperm(from); #ifdef HAVE_ACL /* For systems that support ACL: get the ACL from the original file. */ acl = mch_get_acl(from); #endif fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0); if (fd_in == -1) { #ifdef HAVE_ACL mch_free_acl(acl); #endif return -1; } /* Create the new file with same permissions as the original. */ fd_out = mch_open((char *)to, O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm); if (fd_out == -1) { close(fd_in); #ifdef HAVE_ACL mch_free_acl(acl); #endif return -1; } buffer = (char *)alloc(BUFSIZE); if (buffer == NULL) { close(fd_out); close(fd_in); #ifdef HAVE_ACL mch_free_acl(acl); #endif return -1; } while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0) if (write_eintr(fd_out, buffer, n) != n) { errmsg = _("E208: Error writing to \"%s\""); break; } vim_free(buffer); close(fd_in); if (close(fd_out) < 0) errmsg = _("E209: Error closing \"%s\""); if (n < 0) { errmsg = _("E210: Error reading \"%s\""); to = from; } #ifndef UNIX /* for Unix mch_open() already set the permission */ mch_setperm(to, perm); #endif #ifdef HAVE_ACL mch_set_acl(to, acl); mch_free_acl(acl); #endif if (errmsg != NULL) { EMSG2(errmsg, to); return -1; } mch_remove(from); return 0; } static int already_warned = FALSE; /* * Check if any not hidden buffer has been changed. * Postpone the check if there are characters in the stuff buffer, a global * command is being executed, a mapping is being executed or an autocommand is * busy. * Returns TRUE if some message was written (screen should be redrawn and * cursor positioned). */ int check_timestamps(focus) int focus; /* called for GUI focus event */ { buf_T *buf; int didit = 0; int n; /* Don't check timestamps while system() or another low-level function may * cause us to lose and gain focus. */ if (no_check_timestamps > 0) return FALSE; /* Avoid doing a check twice. The OK/Reload dialog can cause a focus * event and we would keep on checking if the file is steadily growing. * Do check again after typing something. */ if (focus && did_check_timestamps) { need_check_timestamps = TRUE; return FALSE; } if (!stuff_empty() || global_busy || !typebuf_typed() #ifdef FEAT_AUTOCMD || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0 #endif ) need_check_timestamps = TRUE; /* check later */ else { ++no_wait_return; did_check_timestamps = TRUE; already_warned = FALSE; for (buf = firstbuf; buf != NULL; ) { /* Only check buffers in a window. */ if (buf->b_nwindows > 0) { n = buf_check_timestamp(buf, focus); if (didit < n) didit = n; if (n > 0 && !buf_valid(buf)) { /* Autocommands have removed the buffer, start at the * first one again. */ buf = firstbuf; continue; } } buf = buf->b_next; } --no_wait_return; need_check_timestamps = FALSE; if (need_wait_return && didit == 2) { /* make sure msg isn't overwritten */ msg_puts((char_u *)"\n"); out_flush(); } } return didit; } /* * Move all the lines from buffer "frombuf" to buffer "tobuf". * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not * empty. */ static int move_lines(frombuf, tobuf) buf_T *frombuf; buf_T *tobuf; { buf_T *tbuf = curbuf; int retval = OK; linenr_T lnum; char_u *p; /* Copy the lines in "frombuf" to "tobuf". */ curbuf = tobuf; for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum) { p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE)); if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL) { vim_free(p); retval = FAIL; break; } vim_free(p); } /* Delete all the lines in "frombuf". */ if (retval != FAIL) { curbuf = frombuf; for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum) if (ml_delete(lnum, FALSE) == FAIL) { /* Oops! We could try putting back the saved lines, but that * might fail again... */ retval = FAIL; break; } } curbuf = tbuf; return retval; } /* * Check if buffer "buf" has been changed. * Also check if the file for a new buffer unexpectedly appeared. * return 1 if a changed buffer was found. * return 2 if a message has been displayed. * return 0 otherwise. */ int buf_check_timestamp(buf, focus) buf_T *buf; int focus UNUSED; /* called for GUI focus event */ { struct stat st; int stat_res; int retval = 0; char_u *path; char_u *tbuf; char *mesg = NULL; char *mesg2 = ""; int helpmesg = FALSE; int reload = FALSE; #if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG) int can_reload = FALSE; #endif off_t orig_size = buf->b_orig_size; int orig_mode = buf->b_orig_mode; #ifdef FEAT_GUI int save_mouse_correct = need_mouse_correct; #endif #ifdef FEAT_AUTOCMD static int busy = FALSE; int n; char_u *s; #endif char *reason; /* If there is no file name, the buffer is not loaded, 'buftype' is * set, we are in the middle of a save or being called recursively: ignore * this buffer. */ if (buf->b_ffname == NULL || buf->b_ml.ml_mfp == NULL #if defined(FEAT_QUICKFIX) || *buf->b_p_bt != NUL #endif || buf->b_saving #ifdef FEAT_AUTOCMD || busy #endif #ifdef FEAT_NETBEANS_INTG || isNetbeansBuffer(buf) #endif ) return 0; if ( !(buf->b_flags & BF_NOTEDITED) && buf->b_mtime != 0 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0 || time_differs((long)st.st_mtime, buf->b_mtime) #ifdef HAVE_ST_MODE || (int)st.st_mode != buf->b_orig_mode #else || mch_getperm(buf->b_ffname) != buf->b_orig_mode #endif )) { retval = 1; /* set b_mtime to stop further warnings (e.g., when executing * FileChangedShell autocmd) */ if (stat_res < 0) { buf->b_mtime = 0; buf->b_orig_size = 0; buf->b_orig_mode = 0; } else buf_store_time(buf, &st, buf->b_ffname); /* Don't do anything for a directory. Might contain the file * explorer. */ if (mch_isdir(buf->b_fname)) ; /* * If 'autoread' is set, the buffer has no changes and the file still * exists, reload the buffer. Use the buffer-local option value if it * was set, the global option value otherwise. */ else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar) && !bufIsChanged(buf) && stat_res >= 0) reload = TRUE; else { if (stat_res < 0) reason = "deleted"; else if (bufIsChanged(buf)) reason = "conflict"; else if (orig_size != buf->b_orig_size || buf_contents_changed(buf)) reason = "changed"; else if (orig_mode != buf->b_orig_mode) reason = "mode"; else reason = "time"; #ifdef FEAT_AUTOCMD /* * Only give the warning if there are no FileChangedShell * autocommands. * Avoid being called recursively by setting "busy". */ busy = TRUE; # ifdef FEAT_EVAL set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1); set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1); # endif ++allbuf_lock; n = apply_autocmds(EVENT_FILECHANGEDSHELL, buf->b_fname, buf->b_fname, FALSE, buf); --allbuf_lock; busy = FALSE; if (n) { if (!buf_valid(buf)) EMSG(_("E246: FileChangedShell autocommand deleted buffer")); # ifdef FEAT_EVAL s = get_vim_var_str(VV_FCS_CHOICE); if (STRCMP(s, "reload") == 0 && *reason != 'd') reload = TRUE; else if (STRCMP(s, "ask") == 0) n = FALSE; else # endif return 2; } if (!n) #endif { if (*reason == 'd') mesg = _("E211: File \"%s\" no longer available"); else { helpmesg = TRUE; #if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG) can_reload = TRUE; #endif /* * Check if the file contents really changed to avoid * giving a warning when only the timestamp was set (e.g., * checked out of CVS). Always warn when the buffer was * changed. */ if (reason[2] == 'n') { mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well"); mesg2 = _("See \":help W12\" for more info."); } else if (reason[1] == 'h') { mesg = _("W11: Warning: File \"%s\" has changed since editing started"); mesg2 = _("See \":help W11\" for more info."); } else if (*reason == 'm') { mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started"); mesg2 = _("See \":help W16\" for more info."); } else /* Only timestamp changed, store it to avoid a warning * in check_mtime() later. */ buf->b_mtime_read = buf->b_mtime; } } } } else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W) && vim_fexists(buf->b_ffname)) { retval = 1; mesg = _("W13: Warning: File \"%s\" has been created after editing started"); buf->b_flags |= BF_NEW_W; #if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG) can_reload = TRUE; #endif } if (mesg != NULL) { path = home_replace_save(buf, buf->b_fname); if (path != NULL) { if (!helpmesg) mesg2 = ""; tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg) + STRLEN(mesg2) + 2)); sprintf((char *)tbuf, mesg, path); #ifdef FEAT_EVAL /* Set warningmsg here, before the unimportant and output-specific * mesg2 has been appended. */ set_vim_var_string(VV_WARNINGMSG, tbuf, -1); #endif #if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG) if (can_reload) { if (*mesg2 != NUL) { STRCAT(tbuf, "\n"); STRCAT(tbuf, mesg2); } if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf, (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2) reload = TRUE; } else #endif if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned) { if (*mesg2 != NUL) { STRCAT(tbuf, "; "); STRCAT(tbuf, mesg2); } EMSG(tbuf); retval = 2; } else { # ifdef FEAT_AUTOCMD if (!autocmd_busy) # endif { msg_start(); msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST); if (*mesg2 != NUL) msg_puts_attr((char_u *)mesg2, hl_attr(HLF_W) + MSG_HIST); msg_clr_eos(); (void)msg_end(); if (emsg_silent == 0) { out_flush(); # ifdef FEAT_GUI if (!focus) # endif /* give the user some time to think about it */ ui_delay(1000L, TRUE); /* don't redraw and erase the message */ redraw_cmdline = FALSE; } } already_warned = TRUE; } vim_free(path); vim_free(tbuf); } } if (reload) /* Reload the buffer. */ buf_reload(buf, orig_mode); #ifdef FEAT_AUTOCMD /* Trigger FileChangedShell when the file was changed in any way. */ if (buf_valid(buf) && retval != 0) (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST, buf->b_fname, buf->b_fname, FALSE, buf); #endif #ifdef FEAT_GUI /* restore this in case an autocommand has set it; it would break * 'mousefocus' */ need_mouse_correct = save_mouse_correct; #endif return retval; } /* * Reload a buffer that is already loaded. * Used when the file was changed outside of Vim. * "orig_mode" is buf->b_orig_mode before the need for reloading was detected. * buf->b_orig_mode may have been reset already. */ void buf_reload(buf, orig_mode) buf_T *buf; int orig_mode; { exarg_T ea; pos_T old_cursor; linenr_T old_topline; int old_ro = buf->b_p_ro; buf_T *savebuf; int saved = OK; aco_save_T aco; int flags = READ_NEW; /* set curwin/curbuf for "buf" and save some things */ aucmd_prepbuf(&aco, buf); /* We only want to read the text from the file, not reset the syntax * highlighting, clear marks, diff status, etc. Force the fileformat * and encoding to be the same. */ if (prep_exarg(&ea, buf) == OK) { old_cursor = curwin->w_cursor; old_topline = curwin->w_topline; if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur) { /* Save all the text, so that the reload can be undone. * Sync first so that this is a separate undo-able action. */ u_sync(FALSE); saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE); flags |= READ_KEEP_UNDO; } /* * To behave like when a new file is edited (matters for * BufReadPost autocommands) we first need to delete the current * buffer contents. But if reading the file fails we should keep * the old contents. Can't use memory only, the file might be * too big. Use a hidden buffer to move the buffer contents to. */ if (bufempty() || saved == FAIL) savebuf = NULL; else { /* Allocate a buffer without putting it in the buffer list. */ savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY); if (savebuf != NULL && buf == curbuf) { /* Open the memline. */ curbuf = savebuf; curwin->w_buffer = savebuf; saved = ml_open(curbuf); curbuf = buf; curwin->w_buffer = buf; } if (savebuf == NULL || saved == FAIL || buf != curbuf || move_lines(buf, savebuf) == FAIL) { EMSG2(_("E462: Could not prepare for reloading \"%s\""), buf->b_fname); saved = FAIL; } } if (saved == OK) { curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */ #ifdef FEAT_AUTOCMD keep_filetype = TRUE; /* don't detect 'filetype' */ #endif if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0, (linenr_T)0, (linenr_T)MAXLNUM, &ea, flags) == FAIL) { #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL) if (!aborting()) #endif EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname); if (savebuf != NULL && buf_valid(savebuf) && buf == curbuf) { /* Put the text back from the save buffer. First * delete any lines that readfile() added. */ while (!bufempty()) if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL) break; (void)move_lines(savebuf, buf); } } else if (buf == curbuf) /* "buf" still valid */ { /* Mark the buffer as unmodified and free undo info. */ unchanged(buf, TRUE); if ((flags & READ_KEEP_UNDO) == 0) { u_blockfree(buf); u_clearall(buf); } else { /* Mark all undo states as changed. */ u_unchanged(curbuf); } } } vim_free(ea.cmd); if (savebuf != NULL && buf_valid(savebuf)) wipe_buffer(savebuf, FALSE); #ifdef FEAT_DIFF /* Invalidate diff info if necessary. */ diff_invalidate(curbuf); #endif /* Restore the topline and cursor position and check it (lines may * have been removed). */ if (old_topline > curbuf->b_ml.ml_line_count) curwin->w_topline = curbuf->b_ml.ml_line_count; else curwin->w_topline = old_topline; curwin->w_cursor = old_cursor; check_cursor(); update_topline(); #ifdef FEAT_AUTOCMD keep_filetype = FALSE; #endif #ifdef FEAT_FOLDING { win_T *wp; tabpage_T *tp; /* Update folds unless they are defined manually. */ FOR_ALL_TAB_WINDOWS(tp, wp) if (wp->w_buffer == curwin->w_buffer && !foldmethodIsManual(wp)) foldUpdateAll(wp); } #endif /* If the mode didn't change and 'readonly' was set, keep the old * value; the user probably used the ":view" command. But don't * reset it, might have had a read error. */ if (orig_mode == curbuf->b_orig_mode) curbuf->b_p_ro |= old_ro; } /* restore curwin/curbuf and a few other things */ aucmd_restbuf(&aco); /* Careful: autocommands may have made "buf" invalid! */ } void buf_store_time(buf, st, fname) buf_T *buf; struct stat *st; char_u *fname UNUSED; { buf->b_mtime = (long)st->st_mtime; buf->b_orig_size = st->st_size; #ifdef HAVE_ST_MODE buf->b_orig_mode = (int)st->st_mode; #else buf->b_orig_mode = mch_getperm(fname); #endif } /* * Adjust the line with missing eol, used for the next write. * Used for do_filter(), when the input lines for the filter are deleted. */ void write_lnum_adjust(offset) linenr_T offset; { if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */ curbuf->b_no_eol_lnum += offset; } #if defined(TEMPDIRNAMES) || defined(PROTO) static long temp_count = 0; /* Temp filename counter. */ /* * Delete the temp directory and all files it contains. */ void vim_deltempdir() { char_u **files; int file_count; int i; if (vim_tempdir != NULL) { sprintf((char *)NameBuff, "%s*", vim_tempdir); if (gen_expand_wildcards(1, &NameBuff, &file_count, &files, EW_DIR|EW_FILE|EW_SILENT) == OK) { for (i = 0; i < file_count; ++i) mch_remove(files[i]); FreeWild(file_count, files); } gettail(NameBuff)[-1] = NUL; (void)mch_rmdir(NameBuff); vim_free(vim_tempdir); vim_tempdir = NULL; } } #endif #ifdef TEMPDIRNAMES /* * Directory "tempdir" was created. Expand this name to a full path and put * it in "vim_tempdir". This avoids that using ":cd" would confuse us. * "tempdir" must be no longer than MAXPATHL. */ static void vim_settempdir(tempdir) char_u *tempdir; { char_u *buf; buf = alloc((unsigned)MAXPATHL + 2); if (buf != NULL) { if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL) STRCPY(buf, tempdir); # ifdef __EMX__ if (vim_strchr(buf, '/') != NULL) STRCAT(buf, "/"); else # endif add_pathsep(buf); vim_tempdir = vim_strsave(buf); vim_free(buf); } } #endif /* * vim_tempname(): Return a unique name that can be used for a temp file. * * The temp file is NOT created. * * The returned pointer is to allocated memory. * The returned pointer is NULL if no valid name was found. */ char_u * vim_tempname(extra_char) int extra_char UNUSED; /* char to use in the name instead of '?' */ { #ifdef USE_TMPNAM char_u itmp[L_tmpnam]; /* use tmpnam() */ #else char_u itmp[TEMPNAMELEN]; #endif #ifdef TEMPDIRNAMES static char *(tempdirs[]) = {TEMPDIRNAMES}; int i; # ifndef EEXIST struct stat st; # endif /* * This will create a directory for private use by this instance of Vim. * This is done once, and the same directory is used for all temp files. * This method avoids security problems because of symlink attacks et al. * It's also a bit faster, because we only need to check for an existing * file when creating the directory and not for each temp file. */ if (vim_tempdir == NULL) { /* * Try the entries in TEMPDIRNAMES to create the temp directory. */ for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i) { # ifndef HAVE_MKDTEMP size_t itmplen; long nr; long off; # endif /* expand $TMP, leave room for "/v1100000/999999999" */ expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20); if (mch_isdir(itmp)) /* directory exists */ { # ifdef __EMX__ /* If $TMP contains a forward slash (perhaps using bash or * tcsh), don't add a backslash, use a forward slash! * Adding 2 backslashes didn't work. */ if (vim_strchr(itmp, '/') != NULL) STRCAT(itmp, "/"); else # endif add_pathsep(itmp); # ifdef HAVE_MKDTEMP /* Leave room for filename */ STRCAT(itmp, "vXXXXXX"); if (mkdtemp((char *)itmp) != NULL) vim_settempdir(itmp); # else /* Get an arbitrary number of up to 6 digits. When it's * unlikely that it already exists it will be faster, * otherwise it doesn't matter. The use of mkdir() avoids any * security problems because of the predictable number. */ nr = (mch_get_pid() + (long)time(NULL)) % 1000000L; itmplen = STRLEN(itmp); /* Try up to 10000 different values until we find a name that * doesn't exist. */ for (off = 0; off < 10000L; ++off) { int r; # if defined(UNIX) || defined(VMS) mode_t umask_save; # endif sprintf((char *)itmp + itmplen, "v%ld", nr + off); # ifndef EEXIST /* If mkdir() does not set errno to EEXIST, check for * existing file here. There is a race condition then, * although it's fail-safe. */ if (mch_stat((char *)itmp, &st) >= 0) continue; # endif # if defined(UNIX) || defined(VMS) /* Make sure the umask doesn't remove the executable bit. * "repl" has been reported to use "177". */ umask_save = umask(077); # endif r = vim_mkdir(itmp, 0700); # if defined(UNIX) || defined(VMS) (void)umask(umask_save); # endif if (r == 0) { vim_settempdir(itmp); break; } # ifdef EEXIST /* If the mkdir() didn't fail because the file/dir exists, * we probably can't create any dir here, try another * place. */ if (errno != EEXIST) # endif break; } # endif /* HAVE_MKDTEMP */ if (vim_tempdir != NULL) break; } } } if (vim_tempdir != NULL) { /* There is no need to check if the file exists, because we own the * directory and nobody else creates a file in it. */ sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++); return vim_strsave(itmp); } return NULL; #else /* TEMPDIRNAMES */ # ifdef WIN3264 char szTempFile[_MAX_PATH + 1]; char buf4[4]; char_u *retval; char_u *p; STRCPY(itmp, ""); if (GetTempPath(_MAX_PATH, szTempFile) == 0) { szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */ szTempFile[1] = NUL; } strcpy(buf4, "VIM"); buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */ if (GetTempFileName(szTempFile, buf4, 0, itmp) == 0) return NULL; /* GetTempFileName() will create the file, we don't want that */ (void)DeleteFile(itmp); /* Backslashes in a temp file name cause problems when filtering with * "sh". NOTE: This also checks 'shellcmdflag' to help those people who * didn't set 'shellslash'. */ retval = vim_strsave(itmp); if (*p_shcf == '-' || p_ssl) for (p = retval; *p; ++p) if (*p == '\\') *p = '/'; return retval; # else /* WIN3264 */ # ifdef USE_TMPNAM char_u *p; /* tmpnam() will make its own name */ p = tmpnam((char *)itmp); if (p == NULL || *p == NUL) return NULL; # else char_u *p; # ifdef VMS_TEMPNAM /* mktemp() is not working on VMS. It seems to be * a do-nothing function. Therefore we use tempnam(). */ sprintf((char *)itmp, "VIM%c", extra_char); p = (char_u *)tempnam("tmp:", (char *)itmp); if (p != NULL) { /* VMS will use '.LOG' if we don't explicitly specify an extension, * and VIM will then be unable to find the file later */ STRCPY(itmp, p); STRCAT(itmp, ".txt"); free(p); } else return NULL; # else STRCPY(itmp, TEMPNAME); if ((p = vim_strchr(itmp, '?')) != NULL) *p = extra_char; if (mktemp((char *)itmp) == NULL) return NULL; # endif # endif return vim_strsave(itmp); # endif /* WIN3264 */ #endif /* TEMPDIRNAMES */ } #if defined(BACKSLASH_IN_FILENAME) || defined(PROTO) /* * Convert all backslashes in fname to forward slashes in-place. */ void forward_slash(fname) char_u *fname; { char_u *p; for (p = fname; *p != NUL; ++p) # ifdef FEAT_MBYTE /* The Big5 encoding can have '\' in the trail byte. */ if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1) ++p; else # endif if (*p == '\\') *p = '/'; } #endif /* * Code for automatic commands. * * Only included when "FEAT_AUTOCMD" has been defined. */ #if defined(FEAT_AUTOCMD) || defined(PROTO) /* * The autocommands are stored in a list for each event. * Autocommands for the same pattern, that are consecutive, are joined * together, to avoid having to match the pattern too often. * The result is an array of Autopat lists, which point to AutoCmd lists: * * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL * Autopat.cmds Autopat.cmds * | | * V V * AutoCmd.next AutoCmd.next * | | * V V * AutoCmd.next NULL * | * V * NULL * * first_autopat[1] --> Autopat.next --> NULL * Autopat.cmds * | * V * AutoCmd.next * | * V * NULL * etc. * * The order of AutoCmds is important, this is the order in which they were * defined and will have to be executed. */ typedef struct AutoCmd { char_u *cmd; /* The command to be executed (NULL when command has been removed) */ char nested; /* If autocommands nest here */ char last; /* last command in list */ #ifdef FEAT_EVAL scid_T scriptID; /* script ID where defined */ #endif struct AutoCmd *next; /* Next AutoCmd in list */ } AutoCmd; typedef struct AutoPat { int group; /* group ID */ char_u *pat; /* pattern as typed (NULL when pattern has been removed) */ int patlen; /* strlen() of pat */ regprog_T *reg_prog; /* compiled regprog for pattern */ char allow_dirs; /* Pattern may match whole path */ char last; /* last pattern for apply_autocmds() */ AutoCmd *cmds; /* list of commands to do */ struct AutoPat *next; /* next AutoPat in AutoPat list */ int buflocal_nr; /* !=0 for buffer-local AutoPat */ } AutoPat; static struct event_name { char *name; /* event name */ event_T event; /* event number */ } event_names[] = { {"BufAdd", EVENT_BUFADD}, {"BufCreate", EVENT_BUFADD}, {"BufDelete", EVENT_BUFDELETE}, {"BufEnter", EVENT_BUFENTER}, {"BufFilePost", EVENT_BUFFILEPOST}, {"BufFilePre", EVENT_BUFFILEPRE}, {"BufHidden", EVENT_BUFHIDDEN}, {"BufLeave", EVENT_BUFLEAVE}, {"BufNew", EVENT_BUFNEW}, {"BufNewFile", EVENT_BUFNEWFILE}, {"BufRead", EVENT_BUFREADPOST}, {"BufReadCmd", EVENT_BUFREADCMD}, {"BufReadPost", EVENT_BUFREADPOST}, {"BufReadPre", EVENT_BUFREADPRE}, {"BufUnload", EVENT_BUFUNLOAD}, {"BufWinEnter", EVENT_BUFWINENTER}, {"BufWinLeave", EVENT_BUFWINLEAVE}, {"BufWipeout", EVENT_BUFWIPEOUT}, {"BufWrite", EVENT_BUFWRITEPRE}, {"BufWritePost", EVENT_BUFWRITEPOST}, {"BufWritePre", EVENT_BUFWRITEPRE}, {"BufWriteCmd", EVENT_BUFWRITECMD}, {"CmdwinEnter", EVENT_CMDWINENTER}, {"CmdwinLeave", EVENT_CMDWINLEAVE}, {"ColorScheme", EVENT_COLORSCHEME}, {"CursorHold", EVENT_CURSORHOLD}, {"CursorHoldI", EVENT_CURSORHOLDI}, {"CursorMoved", EVENT_CURSORMOVED}, {"CursorMovedI", EVENT_CURSORMOVEDI}, {"EncodingChanged", EVENT_ENCODINGCHANGED}, {"FileEncoding", EVENT_ENCODINGCHANGED}, {"FileAppendPost", EVENT_FILEAPPENDPOST}, {"FileAppendPre", EVENT_FILEAPPENDPRE}, {"FileAppendCmd", EVENT_FILEAPPENDCMD}, {"FileChangedShell",EVENT_FILECHANGEDSHELL}, {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST}, {"FileChangedRO", EVENT_FILECHANGEDRO}, {"FileReadPost", EVENT_FILEREADPOST}, {"FileReadPre", EVENT_FILEREADPRE}, {"FileReadCmd", EVENT_FILEREADCMD}, {"FileType", EVENT_FILETYPE}, {"FileWritePost", EVENT_FILEWRITEPOST}, {"FileWritePre", EVENT_FILEWRITEPRE}, {"FileWriteCmd", EVENT_FILEWRITECMD}, {"FilterReadPost", EVENT_FILTERREADPOST}, {"FilterReadPre", EVENT_FILTERREADPRE}, {"FilterWritePost", EVENT_FILTERWRITEPOST}, {"FilterWritePre", EVENT_FILTERWRITEPRE}, {"FocusGained", EVENT_FOCUSGAINED}, {"FocusLost", EVENT_FOCUSLOST}, {"FuncUndefined", EVENT_FUNCUNDEFINED}, {"GUIEnter", EVENT_GUIENTER}, {"GUIFailed", EVENT_GUIFAILED}, {"InsertChange", EVENT_INSERTCHANGE}, {"InsertEnter", EVENT_INSERTENTER}, {"InsertLeave", EVENT_INSERTLEAVE}, {"InsertCharPre", EVENT_INSERTCHARPRE}, {"MenuPopup", EVENT_MENUPOPUP}, {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST}, {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE}, {"QuitPre", EVENT_QUITPRE}, {"RemoteReply", EVENT_REMOTEREPLY}, {"SessionLoadPost", EVENT_SESSIONLOADPOST}, {"ShellCmdPost", EVENT_SHELLCMDPOST}, {"ShellFilterPost", EVENT_SHELLFILTERPOST}, {"SourcePre", EVENT_SOURCEPRE}, {"SourceCmd", EVENT_SOURCECMD}, {"SpellFileMissing",EVENT_SPELLFILEMISSING}, {"StdinReadPost", EVENT_STDINREADPOST}, {"StdinReadPre", EVENT_STDINREADPRE}, {"SwapExists", EVENT_SWAPEXISTS}, {"Syntax", EVENT_SYNTAX}, {"TabEnter", EVENT_TABENTER}, {"TabLeave", EVENT_TABLEAVE}, {"TermChanged", EVENT_TERMCHANGED}, {"TermResponse", EVENT_TERMRESPONSE}, {"User", EVENT_USER}, {"VimEnter", EVENT_VIMENTER}, {"VimLeave", EVENT_VIMLEAVE}, {"VimLeavePre", EVENT_VIMLEAVEPRE}, {"WinEnter", EVENT_WINENTER}, {"WinLeave", EVENT_WINLEAVE}, {"VimResized", EVENT_VIMRESIZED}, {NULL, (event_T)0} }; static AutoPat *first_autopat[NUM_EVENTS] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; /* * struct used to keep status while executing autocommands for an event. */ typedef struct AutoPatCmd { AutoPat *curpat; /* next AutoPat to examine */ AutoCmd *nextcmd; /* next AutoCmd to execute */ int group; /* group being used */ char_u *fname; /* fname to match with */ char_u *sfname; /* sfname to match with */ char_u *tail; /* tail of fname */ event_T event; /* current event */ int arg_bufnr; /* initially equal to <abuf>, set to zero when buf is deleted */ struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/ } AutoPatCmd; static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */ /* * augroups stores a list of autocmd group names. */ static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL}; #define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i]) /* * The ID of the current group. Group 0 is the default one. */ static int current_augroup = AUGROUP_DEFAULT; static int au_need_clean = FALSE; /* need to delete marked patterns */ static void show_autocmd __ARGS((AutoPat *ap, event_T event)); static void au_remove_pat __ARGS((AutoPat *ap)); static void au_remove_cmds __ARGS((AutoPat *ap)); static void au_cleanup __ARGS((void)); static int au_new_group __ARGS((char_u *name)); static void au_del_group __ARGS((char_u *name)); static event_T event_name2nr __ARGS((char_u *start, char_u **end)); static char_u *event_nr2name __ARGS((event_T event)); static char_u *find_end_event __ARGS((char_u *arg, int have_group)); static int event_ignored __ARGS((event_T event)); static int au_get_grouparg __ARGS((char_u **argp)); static int do_autocmd_event __ARGS((event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group)); static char_u *getnextac __ARGS((int c, void *cookie, int indent)); static int apply_autocmds_group __ARGS((event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap)); static void auto_next_pat __ARGS((AutoPatCmd *apc, int stop_at_last)); static event_T last_event; static int last_group; static int autocmd_blocked = 0; /* block all autocmds */ /* * Show the autocommands for one AutoPat. */ static void show_autocmd(ap, event) AutoPat *ap; event_T event; { AutoCmd *ac; /* Check for "got_int" (here and at various places below), which is set * when "q" has been hit for the "--more--" prompt */ if (got_int) return; if (ap->pat == NULL) /* pattern has been removed */ return; msg_putchar('\n'); if (got_int) return; if (event != last_event || ap->group != last_group) { if (ap->group != AUGROUP_DEFAULT) { if (AUGROUP_NAME(ap->group) == NULL) msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E)); else msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T)); msg_puts((char_u *)" "); } msg_puts_attr(event_nr2name(event), hl_attr(HLF_T)); last_event = event; last_group = ap->group; msg_putchar('\n'); if (got_int) return; } msg_col = 4; msg_outtrans(ap->pat); for (ac = ap->cmds; ac != NULL; ac = ac->next) { if (ac->cmd != NULL) /* skip removed commands */ { if (msg_col >= 14) msg_putchar('\n'); msg_col = 14; if (got_int) return; msg_outtrans(ac->cmd); #ifdef FEAT_EVAL if (p_verbose > 0) last_set_msg(ac->scriptID); #endif if (got_int) return; if (ac->next != NULL) { msg_putchar('\n'); if (got_int) return; } } } } /* * Mark an autocommand pattern for deletion. */ static void au_remove_pat(ap) AutoPat *ap; { vim_free(ap->pat); ap->pat = NULL; ap->buflocal_nr = -1; au_need_clean = TRUE; } /* * Mark all commands for a pattern for deletion. */ static void au_remove_cmds(ap) AutoPat *ap; { AutoCmd *ac; for (ac = ap->cmds; ac != NULL; ac = ac->next) { vim_free(ac->cmd); ac->cmd = NULL; } au_need_clean = TRUE; } /* * Cleanup autocommands and patterns that have been deleted. * This is only done when not executing autocommands. */ static void au_cleanup() { AutoPat *ap, **prev_ap; AutoCmd *ac, **prev_ac; event_T event; if (autocmd_busy || !au_need_clean) return; /* loop over all events */ for (event = (event_T)0; (int)event < (int)NUM_EVENTS; event = (event_T)((int)event + 1)) { /* loop over all autocommand patterns */ prev_ap = &(first_autopat[(int)event]); for (ap = *prev_ap; ap != NULL; ap = *prev_ap) { /* loop over all commands for this pattern */ prev_ac = &(ap->cmds); for (ac = *prev_ac; ac != NULL; ac = *prev_ac) { /* remove the command if the pattern is to be deleted or when * the command has been marked for deletion */ if (ap->pat == NULL || ac->cmd == NULL) { *prev_ac = ac->next; vim_free(ac->cmd); vim_free(ac); } else prev_ac = &(ac->next); } /* remove the pattern if it has been marked for deletion */ if (ap->pat == NULL) { *prev_ap = ap->next; vim_free(ap->reg_prog); vim_free(ap); } else prev_ap = &(ap->next); } } au_need_clean = FALSE; } /* * Called when buffer is freed, to remove/invalidate related buffer-local * autocmds. */ void aubuflocal_remove(buf) buf_T *buf; { AutoPat *ap; event_T event; AutoPatCmd *apc; /* invalidate currently executing autocommands */ for (apc = active_apc_list; apc; apc = apc->next) if (buf->b_fnum == apc->arg_bufnr) apc->arg_bufnr = 0; /* invalidate buflocals looping through events */ for (event = (event_T)0; (int)event < (int)NUM_EVENTS; event = (event_T)((int)event + 1)) /* loop over all autocommand patterns */ for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next) if (ap->buflocal_nr == buf->b_fnum) { au_remove_pat(ap); if (p_verbose >= 6) { verbose_enter(); smsg((char_u *) _("auto-removing autocommand: %s <buffer=%d>"), event_nr2name(event), buf->b_fnum); verbose_leave(); } } au_cleanup(); } /* * Add an autocmd group name. * Return it's ID. Returns AUGROUP_ERROR (< 0) for error. */ static int au_new_group(name) char_u *name; { int i; i = au_find_group(name); if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */ { /* First try using a free entry. */ for (i = 0; i < augroups.ga_len; ++i) if (AUGROUP_NAME(i) == NULL) break; if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL) return AUGROUP_ERROR; AUGROUP_NAME(i) = vim_strsave(name); if (AUGROUP_NAME(i) == NULL) return AUGROUP_ERROR; if (i == augroups.ga_len) ++augroups.ga_len; } return i; } static void au_del_group(name) char_u *name; { int i; i = au_find_group(name); if (i == AUGROUP_ERROR) /* the group doesn't exist */ EMSG2(_("E367: No such group: \"%s\""), name); else { vim_free(AUGROUP_NAME(i)); AUGROUP_NAME(i) = NULL; } } /* * Find the ID of an autocmd group name. * Return it's ID. Returns AUGROUP_ERROR (< 0) for error. */ static int au_find_group(name) char_u *name; { int i; for (i = 0; i < augroups.ga_len; ++i) if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0) return i; return AUGROUP_ERROR; } /* * Return TRUE if augroup "name" exists. */ int au_has_group(name) char_u *name; { return au_find_group(name) != AUGROUP_ERROR; } /* * ":augroup {name}". */ void do_augroup(arg, del_group) char_u *arg; int del_group; { int i; if (del_group) { if (*arg == NUL) EMSG(_(e_argreq)); else au_del_group(arg); } else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */ current_augroup = AUGROUP_DEFAULT; else if (*arg) /* ":aug xxx": switch to group xxx */ { i = au_new_group(arg); if (i != AUGROUP_ERROR) current_augroup = i; } else /* ":aug": list the group names */ { msg_start(); for (i = 0; i < augroups.ga_len; ++i) { if (AUGROUP_NAME(i) != NULL) { msg_puts(AUGROUP_NAME(i)); msg_puts((char_u *)" "); } } msg_clr_eos(); msg_end(); } } #if defined(EXITFREE) || defined(PROTO) void free_all_autocmds() { for (current_augroup = -1; current_augroup < augroups.ga_len; ++current_augroup) do_autocmd((char_u *)"", TRUE); ga_clear_strings(&augroups); } #endif /* * Return the event number for event name "start". * Return NUM_EVENTS if the event name was not found. * Return a pointer to the next event name in "end". */ static event_T event_name2nr(start, end) char_u *start; char_u **end; { char_u *p; int i; int len; /* the event name ends with end of line, a blank or a comma */ for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p) ; for (i = 0; event_names[i].name != NULL; ++i) { len = (int)STRLEN(event_names[i].name); if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0) break; } if (*p == ',') ++p; *end = p; if (event_names[i].name == NULL) return NUM_EVENTS; return event_names[i].event; } /* * Return the name for event "event". */ static char_u * event_nr2name(event) event_T event; { int i; for (i = 0; event_names[i].name != NULL; ++i) if (event_names[i].event == event) return (char_u *)event_names[i].name; return (char_u *)"Unknown"; } /* * Scan over the events. "*" stands for all events. */ static char_u * find_end_event(arg, have_group) char_u *arg; int have_group; /* TRUE when group name was found */ { char_u *pat; char_u *p; if (*arg == '*') { if (arg[1] && !vim_iswhite(arg[1])) { EMSG2(_("E215: Illegal character after *: %s"), arg); return NULL; } pat = arg + 1; } else { for (pat = arg; *pat && !vim_iswhite(*pat); pat = p) { if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS) { if (have_group) EMSG2(_("E216: No such event: %s"), pat); else EMSG2(_("E216: No such group or event: %s"), pat); return NULL; } } } return pat; } /* * Return TRUE if "event" is included in 'eventignore'. */ static int event_ignored(event) event_T event; { char_u *p = p_ei; while (*p != NUL) { if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ',')) return TRUE; if (event_name2nr(p, &p) == event) return TRUE; } return FALSE; } /* * Return OK when the contents of p_ei is valid, FAIL otherwise. */ int check_ei() { char_u *p = p_ei; while (*p) { if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ',')) { p += 3; if (*p == ',') ++p; } else if (event_name2nr(p, &p) == NUM_EVENTS) return FAIL; } return OK; } # if defined(FEAT_SYN_HL) || defined(PROTO) /* * Add "what" to 'eventignore' to skip loading syntax highlighting for every * buffer loaded into the window. "what" must start with a comma. * Returns the old value of 'eventignore' in allocated memory. */ char_u * au_event_disable(what) char *what; { char_u *new_ei; char_u *save_ei; save_ei = vim_strsave(p_ei); if (save_ei != NULL) { new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what))); if (new_ei != NULL) { if (*what == ',' && *p_ei == NUL) STRCPY(new_ei, what + 1); else STRCAT(new_ei, what); set_string_option_direct((char_u *)"ei", -1, new_ei, OPT_FREE, SID_NONE); vim_free(new_ei); } } return save_ei; } void au_event_restore(old_ei) char_u *old_ei; { if (old_ei != NULL) { set_string_option_direct((char_u *)"ei", -1, old_ei, OPT_FREE, SID_NONE); vim_free(old_ei); } } # endif /* FEAT_SYN_HL */ /* * do_autocmd() -- implements the :autocmd command. Can be used in the * following ways: * * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that * will be automatically executed for <event> * when editing a file matching <pat>, in * the current group. * :autocmd <event> <pat> Show the auto-commands associated with * <event> and <pat>. * :autocmd <event> Show the auto-commands associated with * <event>. * :autocmd Show all auto-commands. * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with * <event> and <pat>, and add the command * <cmd>, for the current group. * :autocmd! <event> <pat> Remove all auto-commands associated with * <event> and <pat> for the current group. * :autocmd! <event> Remove all auto-commands associated with * <event> for the current group. * :autocmd! Remove ALL auto-commands for the current * group. * * Multiple events and patterns may be given separated by commas. Here are * some examples: * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic * :autocmd bufleave * set tw=79 nosmartindent ic infercase * * :autocmd * *.c show all autocommands for *.c files. * * Mostly a {group} argument can optionally appear before <event>. */ void do_autocmd(arg, forceit) char_u *arg; int forceit; { char_u *pat; char_u *envpat = NULL; char_u *cmd; event_T event; int need_free = FALSE; int nested = FALSE; int group; /* * Check for a legal group name. If not, use AUGROUP_ALL. */ group = au_get_grouparg(&arg); if (arg == NULL) /* out of memory */ return; /* * Scan over the events. * If we find an illegal name, return here, don't do anything. */ pat = find_end_event(arg, group != AUGROUP_ALL); if (pat == NULL) return; /* * Scan over the pattern. Put a NUL at the end. */ pat = skipwhite(pat); cmd = pat; while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\')) cmd++; if (*cmd) *cmd++ = NUL; /* Expand environment variables in the pattern. Set 'shellslash', we want * forward slashes here. */ if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL) { #ifdef BACKSLASH_IN_FILENAME int p_ssl_save = p_ssl; p_ssl = TRUE; #endif envpat = expand_env_save(pat); #ifdef BACKSLASH_IN_FILENAME p_ssl = p_ssl_save; #endif if (envpat != NULL) pat = envpat; } /* * Check for "nested" flag. */ cmd = skipwhite(cmd); if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6])) { nested = TRUE; cmd = skipwhite(cmd + 6); } /* * Find the start of the commands. * Expand <sfile> in it. */ if (*cmd != NUL) { cmd = expand_sfile(cmd); if (cmd == NULL) /* some error */ return; need_free = TRUE; } /* * Print header when showing autocommands. */ if (!forceit && *cmd == NUL) { /* Highlight title */ MSG_PUTS_TITLE(_("\n--- Auto-Commands ---")); } /* * Loop over the events. */ last_event = (event_T)-1; /* for listing the event name */ last_group = AUGROUP_ERROR; /* for listing the group name */ if (*arg == '*' || *arg == NUL) { for (event = (event_T)0; (int)event < (int)NUM_EVENTS; event = (event_T)((int)event + 1)) if (do_autocmd_event(event, pat, nested, cmd, forceit, group) == FAIL) break; } else { while (*arg && !vim_iswhite(*arg)) if (do_autocmd_event(event_name2nr(arg, &arg), pat, nested, cmd, forceit, group) == FAIL) break; } if (need_free) vim_free(cmd); vim_free(envpat); } /* * Find the group ID in a ":autocmd" or ":doautocmd" argument. * The "argp" argument is advanced to the following argument. * * Returns the group ID, AUGROUP_ERROR for error (out of memory). */ static int au_get_grouparg(argp) char_u **argp; { char_u *group_name; char_u *p; char_u *arg = *argp; int group = AUGROUP_ALL; p = skiptowhite(arg); if (p > arg) { group_name = vim_strnsave(arg, (int)(p - arg)); if (group_name == NULL) /* out of memory */ return AUGROUP_ERROR; group = au_find_group(group_name); if (group == AUGROUP_ERROR) group = AUGROUP_ALL; /* no match, use all groups */ else *argp = skipwhite(p); /* match, skip over group name */ vim_free(group_name); } return group; } /* * do_autocmd() for one event. * If *pat == NUL do for all patterns. * If *cmd == NUL show entries. * If forceit == TRUE delete entries. * If group is not AUGROUP_ALL, only use this group. */ static int do_autocmd_event(event, pat, nested, cmd, forceit, group) event_T event; char_u *pat; int nested; char_u *cmd; int forceit; int group; { AutoPat *ap; AutoPat **prev_ap; AutoCmd *ac; AutoCmd **prev_ac; int brace_level; char_u *endpat; int findgroup; int allgroups; int patlen; int is_buflocal; int buflocal_nr; char_u buflocal_pat[25]; /* for "<buffer=X>" */ if (group == AUGROUP_ALL) findgroup = current_augroup; else findgroup = group; allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL); /* * Show or delete all patterns for an event. */ if (*pat == NUL) { for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next) { if (forceit) /* delete the AutoPat, if it's in the current group */ { if (ap->group == findgroup) au_remove_pat(ap); } else if (group == AUGROUP_ALL || ap->group == group) show_autocmd(ap, event); } } /* * Loop through all the specified patterns. */ for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat)) { /* * Find end of the pattern. * Watch out for a comma in braces, like "*.\{obj,o\}". */ brace_level = 0; for (endpat = pat; *endpat && (*endpat != ',' || brace_level || endpat[-1] == '\\'); ++endpat) { if (*endpat == '{') brace_level++; else if (*endpat == '}') brace_level--; } if (pat == endpat) /* ignore single comma */ continue; patlen = (int)(endpat - pat); /* * detect special <buflocal[=X]> buffer-local patterns */ is_buflocal = FALSE; buflocal_nr = 0; if (patlen >= 7 && STRNCMP(pat, "<buffer", 7) == 0 && pat[patlen - 1] == '>') { /* Error will be printed only for addition. printing and removing * will proceed silently. */ is_buflocal = TRUE; if (patlen == 8) buflocal_nr = curbuf->b_fnum; else if (patlen > 9 && pat[7] == '=') { /* <buffer=abuf> */ if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13)) buflocal_nr = autocmd_bufnr; /* <buffer=123> */ else if (skipdigits(pat + 8) == pat + patlen - 1) buflocal_nr = atoi((char *)pat + 8); } } if (is_buflocal) { /* normalize pat into standard "<buffer>#N" form */ sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr); pat = buflocal_pat; /* can modify pat and patlen */ patlen = (int)STRLEN(buflocal_pat); /* but not endpat */ } /* * Find AutoPat entries with this pattern. */ prev_ap = &first_autopat[(int)event]; while ((ap = *prev_ap) != NULL) { if (ap->pat != NULL) { /* Accept a pattern when: * - a group was specified and it's that group, or a group was * not specified and it's the current group, or a group was * not specified and we are listing * - the length of the pattern matches * - the pattern matches. * For <buffer[=X]>, this condition works because we normalize * all buffer-local patterns. */ if ((allgroups || ap->group == findgroup) && ap->patlen == patlen && STRNCMP(pat, ap->pat, patlen) == 0) { /* * Remove existing autocommands. * If adding any new autocmd's for this AutoPat, don't * delete the pattern from the autopat list, append to * this list. */ if (forceit) { if (*cmd != NUL && ap->next == NULL) { au_remove_cmds(ap); break; } au_remove_pat(ap); } /* * Show autocmd's for this autopat, or buflocals <buffer=X> */ else if (*cmd == NUL) show_autocmd(ap, event); /* * Add autocmd to this autopat, if it's the last one. */ else if (ap->next == NULL) break; } } prev_ap = &ap->next; } /* * Add a new command. */ if (*cmd != NUL) { /* * If the pattern we want to add a command to does appear at the * end of the list (or not is not in the list at all), add the * pattern at the end of the list. */ if (ap == NULL) { /* refuse to add buffer-local ap if buffer number is invalid */ if (is_buflocal && (buflocal_nr == 0 || buflist_findnr(buflocal_nr) == NULL)) { EMSGN(_("E680: <buffer=%d>: invalid buffer number "), buflocal_nr); return FAIL; } ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat)); if (ap == NULL) return FAIL; ap->pat = vim_strnsave(pat, patlen); ap->patlen = patlen; if (ap->pat == NULL) { vim_free(ap); return FAIL; } if (is_buflocal) { ap->buflocal_nr = buflocal_nr; ap->reg_prog = NULL; } else { char_u *reg_pat; ap->buflocal_nr = 0; reg_pat = file_pat_to_reg_pat(pat, endpat, &ap->allow_dirs, TRUE); if (reg_pat != NULL) ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC); vim_free(reg_pat); if (reg_pat == NULL || ap->reg_prog == NULL) { vim_free(ap->pat); vim_free(ap); return FAIL; } } ap->cmds = NULL; *prev_ap = ap; ap->next = NULL; if (group == AUGROUP_ALL) ap->group = current_augroup; else ap->group = group; } /* * Add the autocmd at the end of the AutoCmd list. */ prev_ac = &(ap->cmds); while ((ac = *prev_ac) != NULL) prev_ac = &ac->next; ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd)); if (ac == NULL) return FAIL; ac->cmd = vim_strsave(cmd); #ifdef FEAT_EVAL ac->scriptID = current_SID; #endif if (ac->cmd == NULL) { vim_free(ac); return FAIL; } ac->next = NULL; *prev_ac = ac; ac->nested = nested; } } au_cleanup(); /* may really delete removed patterns/commands now */ return OK; } /* * Implementation of ":doautocmd [group] event [fname]". * Return OK for success, FAIL for failure; */ int do_doautocmd(arg, do_msg) char_u *arg; int do_msg; /* give message for no matching autocmds? */ { char_u *fname; int nothing_done = TRUE; int group; /* * Check for a legal group name. If not, use AUGROUP_ALL. */ group = au_get_grouparg(&arg); if (arg == NULL) /* out of memory */ return FAIL; if (*arg == '*') { EMSG(_("E217: Can't execute autocommands for ALL events")); return FAIL; } /* * Scan over the events. * If we find an illegal name, return here, don't do anything. */ fname = find_end_event(arg, group != AUGROUP_ALL); if (fname == NULL) return FAIL; fname = skipwhite(fname); /* * Loop over the events. */ while (*arg && !vim_iswhite(*arg)) if (apply_autocmds_group(event_name2nr(arg, &arg), fname, NULL, TRUE, group, curbuf, NULL)) nothing_done = FALSE; if (nothing_done && do_msg) MSG(_("No matching autocommands")); #ifdef FEAT_EVAL return aborting() ? FAIL : OK; #else return OK; #endif } /* * ":doautoall": execute autocommands for each loaded buffer. */ void ex_doautoall(eap) exarg_T *eap; { int retval; aco_save_T aco; buf_T *buf; char_u *arg = eap->arg; int call_do_modelines = check_nomodeline(&arg); /* * This is a bit tricky: For some commands curwin->w_buffer needs to be * equal to curbuf, but for some buffers there may not be a window. * So we change the buffer for the current window for a moment. This * gives problems when the autocommands make changes to the list of * buffers or windows... */ for (buf = firstbuf; buf != NULL; buf = buf->b_next) { if (buf->b_ml.ml_mfp != NULL) { /* find a window for this buffer and save some values */ aucmd_prepbuf(&aco, buf); /* execute the autocommands for this buffer */ retval = do_doautocmd(arg, FALSE); if (call_do_modelines) { /* Execute the modeline settings, but don't set window-local * options if we are using the current window for another * buffer. */ do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0); } /* restore the current window */ aucmd_restbuf(&aco); /* stop if there is some error or buffer was deleted */ if (retval == FAIL || !buf_valid(buf)) break; } } check_cursor(); /* just in case lines got deleted */ } /* * Check *argp for <nomodeline>. When it is present return FALSE, otherwise * return TRUE and advance *argp to after it. * Thus return TRUE when do_modelines() should be called. */ int check_nomodeline(argp) char_u **argp; { if (STRNCMP(*argp, "<nomodeline>", 12) == 0) { *argp = skipwhite(*argp + 12); return FALSE; } return TRUE; } /* * Prepare for executing autocommands for (hidden) buffer "buf". * Search for a visible window containing the current buffer. If there isn't * one then use "aucmd_win". * Set "curbuf" and "curwin" to match "buf". * When FEAT_AUTOCMD is not defined another version is used, see below. */ void aucmd_prepbuf(aco, buf) aco_save_T *aco; /* structure to save values in */ buf_T *buf; /* new curbuf */ { win_T *win; #ifdef FEAT_WINDOWS int save_ea; #endif /* Find a window that is for the new buffer */ if (buf == curbuf) /* be quick when buf is curbuf */ win = curwin; else #ifdef FEAT_WINDOWS for (win = firstwin; win != NULL; win = win->w_next) if (win->w_buffer == buf) break; #else win = NULL; #endif /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall * back to using the current window. */ if (win == NULL && aucmd_win == NULL) { win_alloc_aucmd_win(); if (aucmd_win == NULL) win = curwin; } if (win == NULL && aucmd_win_used) /* Strange recursive autocommand, fall back to using the current * window. Expect a few side effects... */ win = curwin; aco->save_curwin = curwin; aco->save_curbuf = curbuf; if (win != NULL) { /* There is a window for "buf" in the current tab page, make it the * curwin. This is preferred, it has the least side effects (esp. if * "buf" is curbuf). */ aco->use_aucmd_win = FALSE; curwin = win; } else { /* There is no window for "buf", use "aucmd_win". To minimize the side * effects, insert it in a the current tab page. * Anything related to a window (e.g., setting folds) may have * unexpected results. */ aco->use_aucmd_win = TRUE; aucmd_win_used = TRUE; aucmd_win->w_buffer = buf; aucmd_win->w_s = &buf->b_s; ++buf->b_nwindows; win_init_empty(aucmd_win); /* set cursor and topline to safe values */ vim_free(aucmd_win->w_localdir); aucmd_win->w_localdir = NULL; /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in * win_enter_ext(). */ aucmd_win->w_localdir = NULL; aco->globaldir = globaldir; globaldir = NULL; #ifdef FEAT_WINDOWS /* Split the current window, put the aucmd_win in the upper half. * We don't want the BufEnter or WinEnter autocommands. */ block_autocmds(); make_snapshot(SNAP_AUCMD_IDX); save_ea = p_ea; p_ea = FALSE; (void)win_split_ins(0, WSP_TOP, aucmd_win, 0); (void)win_comp_pos(); /* recompute window positions */ p_ea = save_ea; unblock_autocmds(); #endif curwin = aucmd_win; } curbuf = buf; aco->new_curwin = curwin; aco->new_curbuf = curbuf; } /* * Cleanup after executing autocommands for a (hidden) buffer. * Restore the window as it was (if possible). * When FEAT_AUTOCMD is not defined another version is used, see below. */ void aucmd_restbuf(aco) aco_save_T *aco; /* structure holding saved values */ { #ifdef FEAT_WINDOWS int dummy; #endif if (aco->use_aucmd_win) { --curbuf->b_nwindows; #ifdef FEAT_WINDOWS /* Find "aucmd_win", it can't be closed, but it may be in another tab * page. Do not trigger autocommands here. */ block_autocmds(); if (curwin != aucmd_win) { tabpage_T *tp; win_T *wp; FOR_ALL_TAB_WINDOWS(tp, wp) { if (wp == aucmd_win) { if (tp != curtab) goto_tabpage_tp(tp, TRUE); win_goto(aucmd_win); goto win_found; } } } win_found: /* Remove the window and frame from the tree of frames. */ (void)winframe_remove(curwin, &dummy, NULL); win_remove(curwin, NULL); aucmd_win_used = FALSE; last_status(FALSE); /* may need to remove last status line */ restore_snapshot(SNAP_AUCMD_IDX, FALSE); (void)win_comp_pos(); /* recompute window positions */ unblock_autocmds(); if (win_valid(aco->save_curwin)) curwin = aco->save_curwin; else /* Hmm, original window disappeared. Just use the first one. */ curwin = firstwin; # ifdef FEAT_EVAL vars_clear(&aucmd_win->w_vars.dv_hashtab); /* free all w: variables */ hash_init(&aucmd_win->w_vars.dv_hashtab); /* re-use the hashtab */ # endif #else curwin = aco->save_curwin; #endif curbuf = curwin->w_buffer; vim_free(globaldir); globaldir = aco->globaldir; /* the buffer contents may have changed */ check_cursor(); if (curwin->w_topline > curbuf->b_ml.ml_line_count) { curwin->w_topline = curbuf->b_ml.ml_line_count; #ifdef FEAT_DIFF curwin->w_topfill = 0; #endif } #if defined(FEAT_GUI) /* Hide the scrollbars from the aucmd_win and update. */ gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE); gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE); gui_may_update_scrollbars(); #endif } else { /* restore curwin */ #ifdef FEAT_WINDOWS if (win_valid(aco->save_curwin)) #endif { /* Restore the buffer which was previously edited by curwin, if * it was changed, we are still the same window and the buffer is * valid. */ if (curwin == aco->new_curwin && curbuf != aco->new_curbuf && buf_valid(aco->new_curbuf) && aco->new_curbuf->b_ml.ml_mfp != NULL) { # if defined(FEAT_SYN_HL) || defined(FEAT_SPELL) if (curwin->w_s == &curbuf->b_s) curwin->w_s = &aco->new_curbuf->b_s; # endif --curbuf->b_nwindows; curbuf = aco->new_curbuf; curwin->w_buffer = curbuf; ++curbuf->b_nwindows; } curwin = aco->save_curwin; curbuf = curwin->w_buffer; } } } static int autocmd_nested = FALSE; /* * Execute autocommands for "event" and file name "fname". * Return TRUE if some commands were executed. */ int apply_autocmds(event, fname, fname_io, force, buf) event_T event; char_u *fname; /* NULL or empty means use actual file name */ char_u *fname_io; /* fname to use for <afile> on cmdline */ int force; /* when TRUE, ignore autocmd_busy */ buf_T *buf; /* buffer for <abuf> */ { return apply_autocmds_group(event, fname, fname_io, force, AUGROUP_ALL, buf, NULL); } /* * Like apply_autocmds(), but with extra "eap" argument. This takes care of * setting v:filearg. */ static int apply_autocmds_exarg(event, fname, fname_io, force, buf, eap) event_T event; char_u *fname; char_u *fname_io; int force; buf_T *buf; exarg_T *eap; { return apply_autocmds_group(event, fname, fname_io, force, AUGROUP_ALL, buf, eap); } /* * Like apply_autocmds(), but handles the caller's retval. If the script * processing is being aborted or if retval is FAIL when inside a try * conditional, no autocommands are executed. If otherwise the autocommands * cause the script to be aborted, retval is set to FAIL. */ int apply_autocmds_retval(event, fname, fname_io, force, buf, retval) event_T event; char_u *fname; /* NULL or empty means use actual file name */ char_u *fname_io; /* fname to use for <afile> on cmdline */ int force; /* when TRUE, ignore autocmd_busy */ buf_T *buf; /* buffer for <abuf> */ int *retval; /* pointer to caller's retval */ { int did_cmd; #ifdef FEAT_EVAL if (should_abort(*retval)) return FALSE; #endif did_cmd = apply_autocmds_group(event, fname, fname_io, force, AUGROUP_ALL, buf, NULL); if (did_cmd #ifdef FEAT_EVAL && aborting() #endif ) *retval = FAIL; return did_cmd; } /* * Return TRUE when there is a CursorHold autocommand defined. */ int has_cursorhold() { return (first_autopat[(int)(get_real_state() == NORMAL_BUSY ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL); } /* * Return TRUE if the CursorHold event can be triggered. */ int trigger_cursorhold() { int state; if (!did_cursorhold && has_cursorhold() && !Recording && typebuf.tb_len == 0 #ifdef FEAT_INS_EXPAND && !ins_compl_active() #endif ) { state = get_real_state(); if (state == NORMAL_BUSY || (state & INSERT) != 0) return TRUE; } return FALSE; } /* * Return TRUE when there is a CursorMoved autocommand defined. */ int has_cursormoved() { return (first_autopat[(int)EVENT_CURSORMOVED] != NULL); } /* * Return TRUE when there is a CursorMovedI autocommand defined. */ int has_cursormovedI() { return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL); } /* * Return TRUE when there is an InsertCharPre autocommand defined. */ int has_insertcharpre() { return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL); } static int apply_autocmds_group(event, fname, fname_io, force, group, buf, eap) event_T event; char_u *fname; /* NULL or empty means use actual file name */ char_u *fname_io; /* fname to use for <afile> on cmdline, NULL means use fname */ int force; /* when TRUE, ignore autocmd_busy */ int group; /* group ID, or AUGROUP_ALL */ buf_T *buf; /* buffer for <abuf> */ exarg_T *eap; /* command arguments */ { char_u *sfname = NULL; /* short file name */ char_u *tail; int save_changed; buf_T *old_curbuf; int retval = FALSE; char_u *save_sourcing_name; linenr_T save_sourcing_lnum; char_u *save_autocmd_fname; int save_autocmd_fname_full; int save_autocmd_bufnr; char_u *save_autocmd_match; int save_autocmd_busy; int save_autocmd_nested; static int nesting = 0; AutoPatCmd patcmd; AutoPat *ap; #ifdef FEAT_EVAL scid_T save_current_SID; void *save_funccalp; char_u *save_cmdarg; long save_cmdbang; #endif static int filechangeshell_busy = FALSE; #ifdef FEAT_PROFILE proftime_T wait_time; #endif /* * Quickly return if there are no autocommands for this event or * autocommands are blocked. */ if (first_autopat[(int)event] == NULL || autocmd_blocked > 0) goto BYPASS_AU; /* * When autocommands are busy, new autocommands are only executed when * explicitly enabled with the "nested" flag. */ if (autocmd_busy && !(force || autocmd_nested)) goto BYPASS_AU; #ifdef FEAT_EVAL /* * Quickly return when immediately aborting on error, or when an interrupt * occurred or an exception was thrown but not caught. */ if (aborting()) goto BYPASS_AU; #endif /* * FileChangedShell never nests, because it can create an endless loop. */ if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL || event == EVENT_FILECHANGEDSHELLPOST)) goto BYPASS_AU; /* * Ignore events in 'eventignore'. */ if (event_ignored(event)) goto BYPASS_AU; /* * Allow nesting of autocommands, but restrict the depth, because it's * possible to create an endless loop. */ if (nesting == 10) { EMSG(_("E218: autocommand nesting too deep")); goto BYPASS_AU; } /* * Check if these autocommands are disabled. Used when doing ":all" or * ":ball". */ if ( (autocmd_no_enter && (event == EVENT_WINENTER || event == EVENT_BUFENTER)) || (autocmd_no_leave && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE))) goto BYPASS_AU; /* * Save the autocmd_* variables and info about the current buffer. */ save_autocmd_fname = autocmd_fname; save_autocmd_fname_full = autocmd_fname_full; save_autocmd_bufnr = autocmd_bufnr; save_autocmd_match = autocmd_match; save_autocmd_busy = autocmd_busy; save_autocmd_nested = autocmd_nested; save_changed = curbuf->b_changed; old_curbuf = curbuf; /* * Set the file name to be used for <afile>. * Make a copy to avoid that changing a buffer name or directory makes it * invalid. */ if (fname_io == NULL) { if (fname != NULL && *fname != NUL) autocmd_fname = fname; else if (buf != NULL) autocmd_fname = buf->b_ffname; else autocmd_fname = NULL; } else autocmd_fname = fname_io; if (autocmd_fname != NULL) autocmd_fname = vim_strsave(autocmd_fname); autocmd_fname_full = FALSE; /* call FullName_save() later */ /* * Set the buffer number to be used for <abuf>. */ if (buf == NULL) autocmd_bufnr = 0; else autocmd_bufnr = buf->b_fnum; /* * When the file name is NULL or empty, use the file name of buffer "buf". * Always use the full path of the file name to match with, in case * "allow_dirs" is set. */ if (fname == NULL || *fname == NUL) { if (buf == NULL) fname = NULL; else { #ifdef FEAT_SYN_HL if (event == EVENT_SYNTAX) fname = buf->b_p_syn; else #endif if (event == EVENT_FILETYPE) fname = buf->b_p_ft; else { if (buf->b_sfname != NULL) sfname = vim_strsave(buf->b_sfname); fname = buf->b_ffname; } } if (fname == NULL) fname = (char_u *)""; fname = vim_strsave(fname); /* make a copy, so we can change it */ } else { sfname = vim_strsave(fname); /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID or * QuickFixCmd* */ if (event == EVENT_FILETYPE || event == EVENT_SYNTAX || event == EVENT_FUNCUNDEFINED || event == EVENT_REMOTEREPLY || event == EVENT_SPELLFILEMISSING || event == EVENT_QUICKFIXCMDPRE || event == EVENT_QUICKFIXCMDPOST) fname = vim_strsave(fname); else fname = FullName_save(fname, FALSE); } if (fname == NULL) /* out of memory */ { vim_free(sfname); retval = FALSE; goto BYPASS_AU; } #ifdef BACKSLASH_IN_FILENAME /* * Replace all backslashes with forward slashes. This makes the * autocommand patterns portable between Unix and MS-DOS. */ if (sfname != NULL) forward_slash(sfname); forward_slash(fname); #endif #ifdef VMS /* remove version for correct match */ if (sfname != NULL) vms_remove_version(sfname); vms_remove_version(fname); #endif /* * Set the name to be used for <amatch>. */ autocmd_match = fname; /* Don't redraw while doing auto commands. */ ++RedrawingDisabled; save_sourcing_name = sourcing_name; sourcing_name = NULL; /* don't free this one */ save_sourcing_lnum = sourcing_lnum; sourcing_lnum = 0; /* no line number here */ #ifdef FEAT_EVAL save_current_SID = current_SID; # ifdef FEAT_PROFILE if (do_profiling == PROF_YES) prof_child_enter(&wait_time); /* doesn't count for the caller itself */ # endif /* Don't use local function variables, if called from a function */ save_funccalp = save_funccal(); #endif /* * When starting to execute autocommands, save the search patterns. */ if (!autocmd_busy) { save_search_patterns(); saveRedobuff(); did_filetype = keep_filetype; } /* * Note that we are applying autocmds. Some commands need to know. */ autocmd_busy = TRUE; filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL); ++nesting; /* see matching decrement below */ /* Remember that FileType was triggered. Used for did_filetype(). */ if (event == EVENT_FILETYPE) did_filetype = TRUE; tail = gettail(fname); /* Find first autocommand that matches */ patcmd.curpat = first_autopat[(int)event]; patcmd.nextcmd = NULL; patcmd.group = group; patcmd.fname = fname; patcmd.sfname = sfname; patcmd.tail = tail; patcmd.event = event; patcmd.arg_bufnr = autocmd_bufnr; patcmd.next = NULL; auto_next_pat(&patcmd, FALSE); /* found one, start executing the autocommands */ if (patcmd.curpat != NULL) { /* add to active_apc_list */ patcmd.next = active_apc_list; active_apc_list = &patcmd; #ifdef FEAT_EVAL /* set v:cmdarg (only when there is a matching pattern) */ save_cmdbang = get_vim_var_nr(VV_CMDBANG); if (eap != NULL) { save_cmdarg = set_cmdarg(eap, NULL); set_vim_var_nr(VV_CMDBANG, (long)eap->forceit); } else save_cmdarg = NULL; /* avoid gcc warning */ #endif retval = TRUE; /* mark the last pattern, to avoid an endless loop when more patterns * are added when executing autocommands */ for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next) ap->last = FALSE; ap->last = TRUE; check_lnums(TRUE); /* make sure cursor and topline are valid */ do_cmdline(NULL, getnextac, (void *)&patcmd, DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT); #ifdef FEAT_EVAL if (eap != NULL) { (void)set_cmdarg(NULL, save_cmdarg); set_vim_var_nr(VV_CMDBANG, save_cmdbang); } #endif /* delete from active_apc_list */ if (active_apc_list == &patcmd) /* just in case */ active_apc_list = patcmd.next; } --RedrawingDisabled; autocmd_busy = save_autocmd_busy; filechangeshell_busy = FALSE; autocmd_nested = save_autocmd_nested; vim_free(sourcing_name); sourcing_name = save_sourcing_name; sourcing_lnum = save_sourcing_lnum; vim_free(autocmd_fname); autocmd_fname = save_autocmd_fname; autocmd_fname_full = save_autocmd_fname_full; autocmd_bufnr = save_autocmd_bufnr; autocmd_match = save_autocmd_match; #ifdef FEAT_EVAL current_SID = save_current_SID; restore_funccal(save_funccalp); # ifdef FEAT_PROFILE if (do_profiling == PROF_YES) prof_child_exit(&wait_time); # endif #endif vim_free(fname); vim_free(sfname); --nesting; /* see matching increment above */ /* * When stopping to execute autocommands, restore the search patterns and * the redo buffer. */ if (!autocmd_busy) { restore_search_patterns(); restoreRedobuff(); did_filetype = FALSE; } /* * Some events don't set or reset the Changed flag. * Check if still in the same buffer! */ if (curbuf == old_curbuf && (event == EVENT_BUFREADPOST || event == EVENT_BUFWRITEPOST || event == EVENT_FILEAPPENDPOST || event == EVENT_VIMLEAVE || event == EVENT_VIMLEAVEPRE)) { #ifdef FEAT_TITLE if (curbuf->b_changed != save_changed) need_maketitle = TRUE; #endif curbuf->b_changed = save_changed; } au_cleanup(); /* may really delete removed patterns/commands now */ BYPASS_AU: /* When wiping out a buffer make sure all its buffer-local autocommands * are deleted. */ if (event == EVENT_BUFWIPEOUT && buf != NULL) aubuflocal_remove(buf); return retval; } # ifdef FEAT_EVAL static char_u *old_termresponse = NULL; # endif /* * Block triggering autocommands until unblock_autocmd() is called. * Can be used recursively, so long as it's symmetric. */ void block_autocmds() { # ifdef FEAT_EVAL /* Remember the value of v:termresponse. */ if (autocmd_blocked == 0) old_termresponse = get_vim_var_str(VV_TERMRESPONSE); # endif ++autocmd_blocked; } void unblock_autocmds() { --autocmd_blocked; # ifdef FEAT_EVAL /* When v:termresponse was set while autocommands were blocked, trigger * the autocommands now. Esp. useful when executing a shell command * during startup (vimdiff). */ if (autocmd_blocked == 0 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse) apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf); # endif } /* * Find next autocommand pattern that matches. */ static void auto_next_pat(apc, stop_at_last) AutoPatCmd *apc; int stop_at_last; /* stop when 'last' flag is set */ { AutoPat *ap; AutoCmd *cp; char_u *name; char *s; vim_free(sourcing_name); sourcing_name = NULL; for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next) { apc->curpat = NULL; /* Only use a pattern when it has not been removed, has commands and * the group matches. For buffer-local autocommands only check the * buffer number. */ if (ap->pat != NULL && ap->cmds != NULL && (apc->group == AUGROUP_ALL || apc->group == ap->group)) { /* execution-condition */ if (ap->buflocal_nr == 0 ? (match_file_pat(NULL, ap->reg_prog, apc->fname, apc->sfname, apc->tail, ap->allow_dirs)) : ap->buflocal_nr == apc->arg_bufnr) { name = event_nr2name(apc->event); s = _("%s Auto commands for \"%s\""); sourcing_name = alloc((unsigned)(STRLEN(s) + STRLEN(name) + ap->patlen + 1)); if (sourcing_name != NULL) { sprintf((char *)sourcing_name, s, (char *)name, (char *)ap->pat); if (p_verbose >= 8) { verbose_enter(); smsg((char_u *)_("Executing %s"), sourcing_name); verbose_leave(); } } apc->curpat = ap; apc->nextcmd = ap->cmds; /* mark last command */ for (cp = ap->cmds; cp->next != NULL; cp = cp->next) cp->last = FALSE; cp->last = TRUE; } line_breakcheck(); if (apc->curpat != NULL) /* found a match */ break; } if (stop_at_last && ap->last) break; } } /* * Get next autocommand command. * Called by do_cmdline() to get the next line for ":if". * Returns allocated string, or NULL for end of autocommands. */ static char_u * getnextac(c, cookie, indent) int c UNUSED; void *cookie; int indent UNUSED; { AutoPatCmd *acp = (AutoPatCmd *)cookie; char_u *retval; AutoCmd *ac; /* Can be called again after returning the last line. */ if (acp->curpat == NULL) return NULL; /* repeat until we find an autocommand to execute */ for (;;) { /* skip removed commands */ while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL) if (acp->nextcmd->last) acp->nextcmd = NULL; else acp->nextcmd = acp->nextcmd->next; if (acp->nextcmd != NULL) break; /* at end of commands, find next pattern that matches */ if (acp->curpat->last) acp->curpat = NULL; else acp->curpat = acp->curpat->next; if (acp->curpat != NULL) auto_next_pat(acp, TRUE); if (acp->curpat == NULL) return NULL; } ac = acp->nextcmd; if (p_verbose >= 9) { verbose_enter_scroll(); smsg((char_u *)_("autocommand %s"), ac->cmd); msg_puts((char_u *)"\n"); /* don't overwrite this either */ verbose_leave_scroll(); } retval = vim_strsave(ac->cmd); autocmd_nested = ac->nested; #ifdef FEAT_EVAL current_SID = ac->scriptID; #endif if (ac->last) acp->nextcmd = NULL; else acp->nextcmd = ac->next; return retval; } /* * Return TRUE if there is a matching autocommand for "fname". * To account for buffer-local autocommands, function needs to know * in which buffer the file will be opened. */ int has_autocmd(event, sfname, buf) event_T event; char_u *sfname; buf_T *buf; { AutoPat *ap; char_u *fname; char_u *tail = gettail(sfname); int retval = FALSE; fname = FullName_save(sfname, FALSE); if (fname == NULL) return FALSE; #ifdef BACKSLASH_IN_FILENAME /* * Replace all backslashes with forward slashes. This makes the * autocommand patterns portable between Unix and MS-DOS. */ sfname = vim_strsave(sfname); if (sfname != NULL) forward_slash(sfname); forward_slash(fname); #endif for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next) if (ap->pat != NULL && ap->cmds != NULL && (ap->buflocal_nr == 0 ? match_file_pat(NULL, ap->reg_prog, fname, sfname, tail, ap->allow_dirs) : buf != NULL && ap->buflocal_nr == buf->b_fnum )) { retval = TRUE; break; } vim_free(fname); #ifdef BACKSLASH_IN_FILENAME vim_free(sfname); #endif return retval; } #if defined(FEAT_CMDL_COMPL) || defined(PROTO) /* * Function given to ExpandGeneric() to obtain the list of autocommand group * names. */ char_u * get_augroup_name(xp, idx) expand_T *xp UNUSED; int idx; { if (idx == augroups.ga_len) /* add "END" add the end */ return (char_u *)"END"; if (idx >= augroups.ga_len) /* end of list */ return NULL; if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */ return (char_u *)""; return AUGROUP_NAME(idx); /* return a name */ } static int include_groups = FALSE; char_u * set_context_in_autocmd(xp, arg, doautocmd) expand_T *xp; char_u *arg; int doautocmd; /* TRUE for :doauto*, FALSE for :autocmd */ { char_u *p; int group; /* check for a group name, skip it if present */ include_groups = FALSE; p = arg; group = au_get_grouparg(&arg); if (group == AUGROUP_ERROR) return NULL; /* If there only is a group name that's what we expand. */ if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1])) { arg = p; group = AUGROUP_ALL; } /* skip over event name */ for (p = arg; *p != NUL && !vim_iswhite(*p); ++p) if (*p == ',') arg = p + 1; if (*p == NUL) { if (group == AUGROUP_ALL) include_groups = TRUE; xp->xp_context = EXPAND_EVENTS; /* expand event name */ xp->xp_pattern = arg; return NULL; } /* skip over pattern */ arg = skipwhite(p); while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\')) arg++; if (*arg) return arg; /* expand (next) command */ if (doautocmd) xp->xp_context = EXPAND_FILES; /* expand file names */ else xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */ return NULL; } /* * Function given to ExpandGeneric() to obtain the list of event names. */ char_u * get_event_name(xp, idx) expand_T *xp UNUSED; int idx; { if (idx < augroups.ga_len) /* First list group names, if wanted */ { if (!include_groups || AUGROUP_NAME(idx) == NULL) return (char_u *)""; /* skip deleted entries */ return AUGROUP_NAME(idx); /* return a name */ } return (char_u *)event_names[idx - augroups.ga_len].name; } #endif /* FEAT_CMDL_COMPL */ /* * Return TRUE if autocmd is supported. */ int autocmd_supported(name) char_u *name; { char_u *p; return (event_name2nr(name, &p) != NUM_EVENTS); } /* * Return TRUE if an autocommand is defined for a group, event and * pattern: The group can be omitted to accept any group. "event" and "pattern" * can be NULL to accept any event and pattern. "pattern" can be NULL to accept * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted. * Used for: * exists("#Group") or * exists("#Group#Event") or * exists("#Group#Event#pat") or * exists("#Event") or * exists("#Event#pat") */ int au_exists(arg) char_u *arg; { char_u *arg_save; char_u *pattern = NULL; char_u *event_name; char_u *p; event_T event; AutoPat *ap; buf_T *buflocal_buf = NULL; int group; int retval = FALSE; /* Make a copy so that we can change the '#' chars to a NUL. */ arg_save = vim_strsave(arg); if (arg_save == NULL) return FALSE; p = vim_strchr(arg_save, '#'); if (p != NULL) *p++ = NUL; /* First, look for an autocmd group name */ group = au_find_group(arg_save); if (group == AUGROUP_ERROR) { /* Didn't match a group name, assume the first argument is an event. */ group = AUGROUP_ALL; event_name = arg_save; } else { if (p == NULL) { /* "Group": group name is present and it's recognized */ retval = TRUE; goto theend; } /* Must be "Group#Event" or "Group#Event#pat". */ event_name = p; p = vim_strchr(event_name, '#'); if (p != NULL) *p++ = NUL; /* "Group#Event#pat" */ } pattern = p; /* "pattern" is NULL when there is no pattern */ /* find the index (enum) for the event name */ event = event_name2nr(event_name, &p); /* return FALSE if the event name is not recognized */ if (event == NUM_EVENTS) goto theend; /* Find the first autocommand for this event. * If there isn't any, return FALSE; * If there is one and no pattern given, return TRUE; */ ap = first_autopat[(int)event]; if (ap == NULL) goto theend; /* if pattern is "<buffer>", special handling is needed which uses curbuf */ /* for pattern "<buffer=N>, fnamecmp() will work fine */ if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0) buflocal_buf = curbuf; /* Check if there is an autocommand with the given pattern. */ for ( ; ap != NULL; ap = ap->next) /* only use a pattern when it has not been removed and has commands. */ /* For buffer-local autocommands, fnamecmp() works fine. */ if (ap->pat != NULL && ap->cmds != NULL && (group == AUGROUP_ALL || ap->group == group) && (pattern == NULL || (buflocal_buf == NULL ? fnamecmp(ap->pat, pattern) == 0 : ap->buflocal_nr == buflocal_buf->b_fnum))) { retval = TRUE; break; } theend: vim_free(arg_save); return retval; } #else /* FEAT_AUTOCMD */ /* * Prepare for executing commands for (hidden) buffer "buf". * This is the non-autocommand version, it simply saves "curbuf" and sets * "curbuf" and "curwin" to match "buf". */ void aucmd_prepbuf(aco, buf) aco_save_T *aco; /* structure to save values in */ buf_T *buf; /* new curbuf */ { aco->save_curbuf = curbuf; --curbuf->b_nwindows; curbuf = buf; curwin->w_buffer = buf; ++curbuf->b_nwindows; } /* * Restore after executing commands for a (hidden) buffer. * This is the non-autocommand version. */ void aucmd_restbuf(aco) aco_save_T *aco; /* structure holding saved values */ { --curbuf->b_nwindows; curbuf = aco->save_curbuf; curwin->w_buffer = curbuf; ++curbuf->b_nwindows; } #endif /* FEAT_AUTOCMD */ #if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO) /* * Try matching a filename with a "pattern" ("prog" is NULL), or use the * precompiled regprog "prog" ("pattern" is NULL). That avoids calling * vim_regcomp() often. * Used for autocommands and 'wildignore'. * Returns TRUE if there is a match, FALSE otherwise. */ int match_file_pat(pattern, prog, fname, sfname, tail, allow_dirs) char_u *pattern; /* pattern to match with */ regprog_T *prog; /* pre-compiled regprog or NULL */ char_u *fname; /* full path of file name */ char_u *sfname; /* short file name or NULL */ char_u *tail; /* tail of path */ int allow_dirs; /* allow matching with dir */ { regmatch_T regmatch; int result = FALSE; #ifdef FEAT_OSFILETYPE int no_pattern = FALSE; /* TRUE if check is filetype only */ char_u *type_start; char_u c; int match = FALSE; #endif #ifdef CASE_INSENSITIVE_FILENAME regmatch.rm_ic = TRUE; /* Always ignore case */ #else regmatch.rm_ic = FALSE; /* Don't ever ignore case */ #endif #ifdef FEAT_OSFILETYPE if (*pattern == '<') { /* There is a filetype condition specified with this pattern. * Check the filetype matches first. If not, don't bother with the * pattern (set regprog to NULL). * Always use magic for the regexp. */ for (type_start = pattern + 1; (c = *pattern); pattern++) { if ((c == ';' || c == '>') && match == FALSE) { *pattern = NUL; /* Terminate the string */ /* TODO: match with 'filetype' of buffer that "fname" comes * from. */ match = mch_check_filetype(fname, type_start); *pattern = c; /* Restore the terminator */ type_start = pattern + 1; } if (c == '>') break; } /* (c should never be NUL, but check anyway) */ if (match == FALSE || c == NUL) regmatch.regprog = NULL; /* Doesn't match - don't check pat. */ else if (*pattern == NUL) { regmatch.regprog = NULL; /* Vim will try to free regprog later */ no_pattern = TRUE; /* Always matches - don't check pat. */ } else regmatch.regprog = vim_regcomp(pattern + 1, RE_MAGIC); } else #endif { if (prog != NULL) regmatch.regprog = prog; else regmatch.regprog = vim_regcomp(pattern, RE_MAGIC); } /* * Try for a match with the pattern with: * 1. the full file name, when the pattern has a '/'. * 2. the short file name, when the pattern has a '/'. * 3. the tail of the file name, when the pattern has no '/'. */ if ( #ifdef FEAT_OSFILETYPE /* If the check is for a filetype only and we don't care * about the path then skip all the regexp stuff. */ no_pattern || #endif (regmatch.regprog != NULL && ((allow_dirs && (vim_regexec(&regmatch, fname, (colnr_T)0) || (sfname != NULL && vim_regexec(&regmatch, sfname, (colnr_T)0)))) || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))) result = TRUE; if (prog == NULL) vim_free(regmatch.regprog); return result; } #endif #if defined(FEAT_WILDIGN) || defined(PROTO) /* * Return TRUE if a file matches with a pattern in "list". * "list" is a comma-separated list of patterns, like 'wildignore'. * "sfname" is the short file name or NULL, "ffname" the long file name. */ int match_file_list(list, sfname, ffname) char_u *list; char_u *sfname; char_u *ffname; { char_u buf[100]; char_u *tail; char_u *regpat; char allow_dirs; int match; char_u *p; tail = gettail(sfname); /* try all patterns in 'wildignore' */ p = list; while (*p) { copy_option_part(&p, buf, 100, ","); regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE); if (regpat == NULL) break; match = match_file_pat(regpat, NULL, ffname, sfname, tail, (int)allow_dirs); vim_free(regpat); if (match) return TRUE; } return FALSE; } #endif /* * Convert the given pattern "pat" which has shell style wildcards in it, into * a regular expression, and return the result in allocated memory. If there * is a directory path separator to be matched, then TRUE is put in * allow_dirs, otherwise FALSE is put there -- webb. * Handle backslashes before special characters, like "\*" and "\ ". * * If FEAT_OSFILETYPE defined then pass initial <type> through unchanged. Eg: * '<html>myfile' becomes '<html>^myfile$' -- leonard. * * Returns NULL when out of memory. */ char_u * file_pat_to_reg_pat(pat, pat_end, allow_dirs, no_bslash) char_u *pat; char_u *pat_end; /* first char after pattern or NULL */ char *allow_dirs; /* Result passed back out in here */ int no_bslash UNUSED; /* Don't use a backward slash as pathsep */ { int size; char_u *endp; char_u *reg_pat; char_u *p; int i; int nested = 0; int add_dollar = TRUE; #ifdef FEAT_OSFILETYPE int check_length = 0; #endif if (allow_dirs != NULL) *allow_dirs = FALSE; if (pat_end == NULL) pat_end = pat + STRLEN(pat); #ifdef FEAT_OSFILETYPE /* Find out how much of the string is the filetype check */ if (*pat == '<') { /* Count chars until the next '>' */ for (p = pat + 1; p < pat_end && *p != '>'; p++) ; if (p < pat_end) { /* Pattern is of the form <.*>.* */ check_length = p - pat + 1; if (p + 1 >= pat_end) { /* The 'pattern' is a filetype check ONLY */ reg_pat = (char_u *)alloc(check_length + 1); if (reg_pat != NULL) { mch_memmove(reg_pat, pat, (size_t)check_length); reg_pat[check_length] = NUL; } return reg_pat; } } /* else: there was no closing '>' - assume it was a normal pattern */ } pat += check_length; size = 2 + check_length; #else size = 2; /* '^' at start, '$' at end */ #endif for (p = pat; p < pat_end; p++) { switch (*p) { case '*': case '.': case ',': case '{': case '}': case '~': size += 2; /* extra backslash */ break; #ifdef BACKSLASH_IN_FILENAME case '\\': case '/': size += 4; /* could become "[\/]" */ break; #endif default: size++; # ifdef FEAT_MBYTE if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1) { ++p; ++size; } # endif break; } } reg_pat = alloc(size + 1); if (reg_pat == NULL) return NULL; #ifdef FEAT_OSFILETYPE /* Copy the type check in to the start. */ if (check_length) mch_memmove(reg_pat, pat - check_length, (size_t)check_length); i = check_length; #else i = 0; #endif if (pat[0] == '*') while (pat[0] == '*' && pat < pat_end - 1) pat++; else reg_pat[i++] = '^'; endp = pat_end - 1; if (*endp == '*') { while (endp - pat > 0 && *endp == '*') endp--; add_dollar = FALSE; } for (p = pat; *p && nested >= 0 && p <= endp; p++) { switch (*p) { case '*': reg_pat[i++] = '.'; reg_pat[i++] = '*'; while (p[1] == '*') /* "**" matches like "*" */ ++p; break; case '.': case '~': reg_pat[i++] = '\\'; reg_pat[i++] = *p; break; case '?': reg_pat[i++] = '.'; break; case '\\': if (p[1] == NUL) break; #ifdef BACKSLASH_IN_FILENAME if (!no_bslash) { /* translate: * "\x" to "\\x" e.g., "dir\file" * "\*" to "\\.*" e.g., "dir\*.c" * "\?" to "\\." e.g., "dir\??.c" * "\+" to "\+" e.g., "fileX\+.c" */ if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?') && p[1] != '+') { reg_pat[i++] = '['; reg_pat[i++] = '\\'; reg_pat[i++] = '/'; reg_pat[i++] = ']'; if (allow_dirs != NULL) *allow_dirs = TRUE; break; } } #endif /* Undo escaping from ExpandEscape(): * foo\?bar -> foo?bar * foo\%bar -> foo%bar * foo\,bar -> foo,bar * foo\ bar -> foo bar * Don't unescape \, * and others that are also special in a * regexp. */ if (*++p == '?' #ifdef BACKSLASH_IN_FILENAME && no_bslash #endif ) reg_pat[i++] = '?'; else if (*p == ',' || *p == '%' || *p == '#' || *p == ' ') reg_pat[i++] = *p; else { if (allow_dirs != NULL && vim_ispathsep(*p) #ifdef BACKSLASH_IN_FILENAME && (!no_bslash || *p != '\\') #endif ) *allow_dirs = TRUE; reg_pat[i++] = '\\'; reg_pat[i++] = *p; } break; #ifdef BACKSLASH_IN_FILENAME case '/': reg_pat[i++] = '['; reg_pat[i++] = '\\'; reg_pat[i++] = '/'; reg_pat[i++] = ']'; if (allow_dirs != NULL) *allow_dirs = TRUE; break; #endif case '{': reg_pat[i++] = '\\'; reg_pat[i++] = '('; nested++; break; case '}': reg_pat[i++] = '\\'; reg_pat[i++] = ')'; --nested; break; case ',': if (nested) { reg_pat[i++] = '\\'; reg_pat[i++] = '|'; } else reg_pat[i++] = ','; break; default: # ifdef FEAT_MBYTE if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1) reg_pat[i++] = *p++; else # endif if (allow_dirs != NULL && vim_ispathsep(*p)) *allow_dirs = TRUE; reg_pat[i++] = *p; break; } } if (add_dollar) reg_pat[i++] = '$'; reg_pat[i] = NUL; if (nested != 0) { if (nested < 0) EMSG(_("E219: Missing {.")); else EMSG(_("E220: Missing }.")); vim_free(reg_pat); reg_pat = NULL; } return reg_pat; } #if defined(EINTR) || defined(PROTO) /* * Version of read() that retries when interrupted by EINTR (possibly * by a SIGWINCH). */ long read_eintr(fd, buf, bufsize) int fd; void *buf; size_t bufsize; { long ret; for (;;) { ret = vim_read(fd, buf, bufsize); if (ret >= 0 || errno != EINTR) break; } return ret; } /* * Version of write() that retries when interrupted by EINTR (possibly * by a SIGWINCH). */ long write_eintr(fd, buf, bufsize) int fd; void *buf; size_t bufsize; { long ret = 0; long wlen; /* Repeat the write() so long it didn't fail, other than being interrupted * by a signal. */ while (ret < (long)bufsize) { wlen = vim_write(fd, (char *)buf + ret, bufsize - ret); if (wlen < 0) { if (errno != EINTR) break; } else ret += wlen; } return ret; } #endif
zyz2011-vim
src/fileio.c
C
gpl2
263,065
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * os_win32.c * * Used for both the console version and the Win32 GUI. A lot of code is for * the console version only, so there is a lot of "#ifndef FEAT_GUI_W32". * * Win32 (Windows NT and Windows 95) system-dependent routines. * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code, * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5. * * George V. Reilly <george@reilly.org> wrote most of this. * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0. */ #include "vim.h" #ifdef FEAT_MZSCHEME # include "if_mzsch.h" #endif #include <sys/types.h> #include <signal.h> #include <limits.h> #include <process.h> #undef chdir #ifdef __GNUC__ # ifndef __MINGW32__ # include <dirent.h> # endif #else # include <direct.h> #endif #if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32) # include <shellapi.h> #endif #ifdef __MINGW32__ # ifndef FROM_LEFT_1ST_BUTTON_PRESSED # define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001 # endif # ifndef RIGHTMOST_BUTTON_PRESSED # define RIGHTMOST_BUTTON_PRESSED 0x0002 # endif # ifndef FROM_LEFT_2ND_BUTTON_PRESSED # define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004 # endif # ifndef FROM_LEFT_3RD_BUTTON_PRESSED # define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008 # endif # ifndef FROM_LEFT_4TH_BUTTON_PRESSED # define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010 # endif /* * EventFlags */ # ifndef MOUSE_MOVED # define MOUSE_MOVED 0x0001 # endif # ifndef DOUBLE_CLICK # define DOUBLE_CLICK 0x0002 # endif #endif /* Record all output and all keyboard & mouse input */ /* #define MCH_WRITE_DUMP */ #ifdef MCH_WRITE_DUMP FILE* fdDump = NULL; #endif /* * When generating prototypes for Win32 on Unix, these lines make the syntax * errors disappear. They do not need to be correct. */ #ifdef PROTO #define WINAPI #define WINBASEAPI typedef char * LPCSTR; typedef char * LPWSTR; typedef int ACCESS_MASK; typedef int BOOL; typedef int COLORREF; typedef int CONSOLE_CURSOR_INFO; typedef int COORD; typedef int DWORD; typedef int HANDLE; typedef int HDC; typedef int HFONT; typedef int HICON; typedef int HINSTANCE; typedef int HWND; typedef int INPUT_RECORD; typedef int KEY_EVENT_RECORD; typedef int LOGFONT; typedef int LPBOOL; typedef int LPCTSTR; typedef int LPDWORD; typedef int LPSTR; typedef int LPTSTR; typedef int LPVOID; typedef int MOUSE_EVENT_RECORD; typedef int PACL; typedef int PDWORD; typedef int PHANDLE; typedef int PRINTDLG; typedef int PSECURITY_DESCRIPTOR; typedef int PSID; typedef int SECURITY_INFORMATION; typedef int SHORT; typedef int SMALL_RECT; typedef int TEXTMETRIC; typedef int TOKEN_INFORMATION_CLASS; typedef int TRUSTEE; typedef int WORD; typedef int WCHAR; typedef void VOID; #endif #ifndef FEAT_GUI_W32 /* Undocumented API in kernel32.dll needed to work around dead key bug in * console-mode applications in NT 4.0. If you switch keyboard layouts * in a console app to a layout that includes dead keys and then hit a * dead key, a call to ToAscii will trash the stack. My thanks to Ian James * and Michael Dietrich for helping me figure out this workaround. */ /* WINBASEAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */ #ifndef WINBASEAPI # define WINBASEAPI __stdcall #endif #if defined(__BORLANDC__) typedef BOOL (__stdcall *PFNGCKLN)(LPSTR); #else typedef WINBASEAPI BOOL (WINAPI *PFNGCKLN)(LPSTR); #endif static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL; #endif #if defined(__BORLANDC__) /* Strangely Borland uses a non-standard name. */ # define wcsicmp(a, b) wcscmpi((a), (b)) #endif /* Enable common dialogs input unicode from IME if posible. */ #ifdef FEAT_MBYTE LRESULT (WINAPI *pDispatchMessage)(LPMSG) = DispatchMessage; BOOL (WINAPI *pGetMessage)(LPMSG, HWND, UINT, UINT) = GetMessage; BOOL (WINAPI *pIsDialogMessage)(HWND, LPMSG) = IsDialogMessage; BOOL (WINAPI *pPeekMessage)(LPMSG, HWND, UINT, UINT, UINT) = PeekMessage; #endif #ifndef FEAT_GUI_W32 /* Win32 Console handles for input and output */ static HANDLE g_hConIn = INVALID_HANDLE_VALUE; static HANDLE g_hConOut = INVALID_HANDLE_VALUE; /* Win32 Screen buffer,coordinate,console I/O information */ static SMALL_RECT g_srScrollRegion; static COORD g_coord; /* 0-based, but external coords are 1-based */ /* The attribute of the screen when the editor was started */ static WORD g_attrDefault = 7; /* lightgray text on black background */ static WORD g_attrCurrent; static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */ static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */ static int g_fForceExit = FALSE; /* set when forcefully exiting */ static void termcap_mode_start(void); static void termcap_mode_end(void); static void clear_chars(COORD coord, DWORD n); static void clear_screen(void); static void clear_to_end_of_display(void); static void clear_to_end_of_line(void); static void scroll(unsigned cLines); static void set_scroll_region(unsigned left, unsigned top, unsigned right, unsigned bottom); static void insert_lines(unsigned cLines); static void delete_lines(unsigned cLines); static void gotoxy(unsigned x, unsigned y); static void normvideo(void); static void textattr(WORD wAttr); static void textcolor(WORD wAttr); static void textbackground(WORD wAttr); static void standout(void); static void standend(void); static void visual_bell(void); static void cursor_visible(BOOL fVisible); static BOOL write_chars(LPCSTR pchBuf, DWORD cchToWrite); static char_u tgetch(int *pmodifiers, char_u *pch2); static void create_conin(void); static int s_cursor_visible = TRUE; static int did_create_conin = FALSE; #else static int s_dont_use_vimrun = TRUE; static int need_vimrun_warning = FALSE; static char *vimrun_path = "vimrun "; #endif #ifndef FEAT_GUI_W32 static int suppress_winsize = 1; /* don't fiddle with console */ #endif static char_u *exe_path = NULL; static void get_exe_name(void) { /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned * as the maximum length that works (plus a NUL byte). */ #define MAX_ENV_PATH_LEN 8192 char temp[MAX_ENV_PATH_LEN]; char_u *p; if (exe_name == NULL) { /* store the name of the executable, may be used for $VIM */ GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1); if (*temp != NUL) exe_name = FullName_save((char_u *)temp, FALSE); } if (exe_path == NULL && exe_name != NULL) { exe_path = vim_strnsave(exe_name, (int)(gettail_sep(exe_name) - exe_name)); if (exe_path != NULL) { /* Append our starting directory to $PATH, so that when doing * "!xxd" it's found in our starting directory. Needed because * SearchPath() also looks there. */ p = mch_getenv("PATH"); if (p == NULL || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN) { if (p == NULL || *p == NUL) temp[0] = NUL; else { STRCPY(temp, p); STRCAT(temp, ";"); } STRCAT(temp, exe_path); vim_setenv((char_u *)"PATH", temp); } } } } /* * Unescape characters in "p" that appear in "escaped". */ static void unescape_shellxquote(char_u *p, char_u *escaped) { int l = (int)STRLEN(p); int n; while (*p != NUL) { if (*p == '^' && vim_strchr(escaped, p[1]) != NULL) mch_memmove(p, p + 1, l--); #ifdef FEAT_MBYTE n = (*mb_ptr2len)(p); #else n = 1; #endif p += n; l -= n; } } /* * Load library "name". */ HINSTANCE vimLoadLib(char *name) { HINSTANCE dll = NULL; char old_dir[MAXPATHL]; if (exe_path == NULL) get_exe_name(); if (exe_path != NULL && mch_dirname(old_dir, MAXPATHL) == OK) { /* Change directory to where the executable is, both to make sure we * find a .dll there and to avoid looking for a .dll in the current * directory. */ mch_chdir(exe_path); dll = LoadLibrary(name); mch_chdir(old_dir); } return dll; } #if defined(DYNAMIC_GETTEXT) || defined(PROTO) # ifndef GETTEXT_DLL # define GETTEXT_DLL "libintl.dll" # endif /* Dummy funcitons */ static char *null_libintl_gettext(const char *); static char *null_libintl_textdomain(const char *); static char *null_libintl_bindtextdomain(const char *, const char *); static char *null_libintl_bind_textdomain_codeset(const char *, const char *); static HINSTANCE hLibintlDLL = NULL; char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext; char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain; char *(*dyn_libintl_bindtextdomain)(const char *, const char *) = null_libintl_bindtextdomain; char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *) = null_libintl_bind_textdomain_codeset; int dyn_libintl_init(char *libname) { int i; static struct { char *name; FARPROC *ptr; } libintl_entry[] = { {"gettext", (FARPROC*)&dyn_libintl_gettext}, {"textdomain", (FARPROC*)&dyn_libintl_textdomain}, {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain}, {NULL, NULL} }; /* No need to initialize twice. */ if (hLibintlDLL) return 1; /* Load gettext library (libintl.dll) */ hLibintlDLL = vimLoadLib(libname != NULL ? libname : GETTEXT_DLL); if (!hLibintlDLL) { if (p_verbose > 0) { verbose_enter(); EMSG2(_(e_loadlib), GETTEXT_DLL); verbose_leave(); } return 0; } for (i = 0; libintl_entry[i].name != NULL && libintl_entry[i].ptr != NULL; ++i) { if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL, libintl_entry[i].name)) == NULL) { dyn_libintl_end(); if (p_verbose > 0) { verbose_enter(); EMSG2(_(e_loadfunc), libintl_entry[i].name); verbose_leave(); } return 0; } } /* The bind_textdomain_codeset() function is optional. */ dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL, "bind_textdomain_codeset"); if (dyn_libintl_bind_textdomain_codeset == NULL) dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset; return 1; } void dyn_libintl_end() { if (hLibintlDLL) FreeLibrary(hLibintlDLL); hLibintlDLL = NULL; dyn_libintl_gettext = null_libintl_gettext; dyn_libintl_textdomain = null_libintl_textdomain; dyn_libintl_bindtextdomain = null_libintl_bindtextdomain; dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset; } /*ARGSUSED*/ static char * null_libintl_gettext(const char *msgid) { return (char*)msgid; } /*ARGSUSED*/ static char * null_libintl_bindtextdomain(const char *domainname, const char *dirname) { return NULL; } /*ARGSUSED*/ static char * null_libintl_bind_textdomain_codeset(const char *domainname, const char *codeset) { return NULL; } /*ARGSUSED*/ static char * null_libintl_textdomain(const char *domainname) { return NULL; } #endif /* DYNAMIC_GETTEXT */ /* This symbol is not defined in older versions of the SDK or Visual C++ */ #ifndef VER_PLATFORM_WIN32_WINDOWS # define VER_PLATFORM_WIN32_WINDOWS 1 #endif DWORD g_PlatformId; #ifdef HAVE_ACL # include <aclapi.h> /* * These are needed to dynamically load the ADVAPI DLL, which is not * implemented under Windows 95 (and causes VIM to crash) */ typedef DWORD (WINAPI *PSNSECINFO) (LPTSTR, enum SE_OBJECT_TYPE, SECURITY_INFORMATION, PSID, PSID, PACL, PACL); typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, enum SE_OBJECT_TYPE, SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *, PSECURITY_DESCRIPTOR *); static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */ static PSNSECINFO pSetNamedSecurityInfo; static PGNSECINFO pGetNamedSecurityInfo; #endif typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD); static BOOL allowPiping = FALSE; static PSETHANDLEINFORMATION pSetHandleInformation; /* * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or * VER_PLATFORM_WIN32_WINDOWS (Win95). */ void PlatformId(void) { static int done = FALSE; if (!done) { OSVERSIONINFO ovi; ovi.dwOSVersionInfoSize = sizeof(ovi); GetVersionEx(&ovi); g_PlatformId = ovi.dwPlatformId; #ifdef HAVE_ACL /* * Load the ADVAPI runtime if we are on anything * other than Windows 95 */ if (g_PlatformId == VER_PLATFORM_WIN32_NT) { /* * do this load. Problems: Doesn't unload at end of run (this is * theoretically okay, since Windows should unload it when VIM * terminates). Should we be using the 'mch_libcall' routines? * Seems like a lot of overhead to load/unload ADVAPI32.DLL each * time we verify security... */ advapi_lib = vimLoadLib("ADVAPI32.DLL"); if (advapi_lib != NULL) { pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib, "SetNamedSecurityInfoA"); pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib, "GetNamedSecurityInfoA"); if (pSetNamedSecurityInfo == NULL || pGetNamedSecurityInfo == NULL) { /* If we can't get the function addresses, set advapi_lib * to NULL so that we don't use them. */ FreeLibrary(advapi_lib); advapi_lib = NULL; } } } #endif /* * If we are on windows NT, try to load the pipe functions, only * available from Win2K. */ if (g_PlatformId == VER_PLATFORM_WIN32_NT) { HANDLE kernel32 = GetModuleHandle("kernel32"); pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress( kernel32, "SetHandleInformation"); allowPiping = pSetHandleInformation != NULL; } done = TRUE; } } /* * Return TRUE when running on Windows 95 (or 98 or ME). * Only to be used after mch_init(). */ int mch_windows95(void) { return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS; } #ifdef FEAT_GUI_W32 /* * Used to work around the "can't do synchronous spawn" * problem on Win32s, without resorting to Universal Thunk. */ static int old_num_windows; static int num_windows; /*ARGSUSED*/ static BOOL CALLBACK win32ssynch_cb(HWND hwnd, LPARAM lparam) { num_windows++; return TRUE; } #endif #ifndef FEAT_GUI_W32 #define SHIFT (SHIFT_PRESSED) #define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED) #define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED) #define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED) /* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode. * We map function keys to their ANSI terminal equivalents, as produced * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any * ANSI key with a value >= '\300' is nonstandard, but provided anyway * so that the user can have access to all SHIFT-, CTRL-, and ALT- * combinations of function/arrow/etc keys. */ static const struct { WORD wVirtKey; BOOL fAnsiKey; int chAlone; int chShift; int chCtrl; int chAlt; } VirtKeyMap[] = { /* Key ANSI alone shift ctrl alt */ { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, }, { VK_F1, TRUE, ';', 'T', '^', 'h', }, { VK_F2, TRUE, '<', 'U', '_', 'i', }, { VK_F3, TRUE, '=', 'V', '`', 'j', }, { VK_F4, TRUE, '>', 'W', 'a', 'k', }, { VK_F5, TRUE, '?', 'X', 'b', 'l', }, { VK_F6, TRUE, '@', 'Y', 'c', 'm', }, { VK_F7, TRUE, 'A', 'Z', 'd', 'n', }, { VK_F8, TRUE, 'B', '[', 'e', 'o', }, { VK_F9, TRUE, 'C', '\\', 'f', 'p', }, { VK_F10, TRUE, 'D', ']', 'g', 'q', }, { VK_F11, TRUE, '\205', '\207', '\211', '\213', }, { VK_F12, TRUE, '\206', '\210', '\212', '\214', }, { VK_HOME, TRUE, 'G', '\302', 'w', '\303', }, { VK_UP, TRUE, 'H', '\304', '\305', '\306', }, { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/ { VK_LEFT, TRUE, 'K', '\311', 's', '\312', }, { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', }, { VK_END, TRUE, 'O', '\315', 'u', '\316', }, { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', }, { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/ { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', }, { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', }, { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/ #if 0 /* Most people don't have F13-F20, but what the hell... */ { VK_F13, TRUE, '\332', '\333', '\334', '\335', }, { VK_F14, TRUE, '\336', '\337', '\340', '\341', }, { VK_F15, TRUE, '\342', '\343', '\344', '\345', }, { VK_F16, TRUE, '\346', '\347', '\350', '\351', }, { VK_F17, TRUE, '\352', '\353', '\354', '\355', }, { VK_F18, TRUE, '\356', '\357', '\360', '\361', }, { VK_F19, TRUE, '\362', '\363', '\364', '\365', }, { VK_F20, TRUE, '\366', '\367', '\370', '\371', }, #endif { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */ { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */ /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */ { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */ { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', }, { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', }, { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', }, { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', }, { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', }, { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', }, { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', }, { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', }, { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', }, /* Sorry, out of number space! <negri>*/ { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', }, }; #ifdef _MSC_VER // The ToAscii bug destroys several registers. Need to turn off optimization // or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions # pragma warning(push) # pragma warning(disable: 4748) # pragma optimize("", off) #endif #if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__) # define AChar AsciiChar #else # define AChar uChar.AsciiChar #endif /* The return code indicates key code size. */ static int #ifdef __BORLANDC__ __stdcall #endif win32_kbd_patch_key( KEY_EVENT_RECORD *pker) { UINT uMods = pker->dwControlKeyState; static int s_iIsDead = 0; static WORD awAnsiCode[2]; static BYTE abKeystate[256]; if (s_iIsDead == 2) { pker->AChar = (CHAR) awAnsiCode[1]; s_iIsDead = 0; return 1; } if (pker->AChar != 0) return 1; vim_memset(abKeystate, 0, sizeof (abKeystate)); // Should only be non-NULL on NT 4.0 if (s_pfnGetConsoleKeyboardLayoutName != NULL) { CHAR szKLID[KL_NAMELENGTH]; if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID)) (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE); } /* Clear any pending dead keys */ ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0); if (uMods & SHIFT_PRESSED) abKeystate[VK_SHIFT] = 0x80; if (uMods & CAPSLOCK_ON) abKeystate[VK_CAPITAL] = 1; if ((uMods & ALT_GR) == ALT_GR) { abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] = abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80; } s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode, abKeystate, awAnsiCode, 0); if (s_iIsDead > 0) pker->AChar = (CHAR) awAnsiCode[0]; return s_iIsDead; } #ifdef _MSC_VER /* MUST switch optimization on again here, otherwise a call to * decode_key_event() may crash (e.g. when hitting caps-lock) */ # pragma optimize("", on) # pragma warning(pop) # if (_MSC_VER < 1100) /* MUST turn off global optimisation for this next function, or * pressing ctrl-minus in insert mode crashes Vim when built with * VC4.1. -- negri. */ # pragma optimize("g", off) # endif #endif static BOOL g_fJustGotFocus = FALSE; /* * Decode a KEY_EVENT into one or two keystrokes */ static BOOL decode_key_event( KEY_EVENT_RECORD *pker, char_u *pch, char_u *pch2, int *pmodifiers, BOOL fDoPost) { int i; const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL); *pch = *pch2 = NUL; g_fJustGotFocus = FALSE; /* ignore key up events */ if (!pker->bKeyDown) return FALSE; /* ignore some keystrokes */ switch (pker->wVirtualKeyCode) { /* modifiers */ case VK_SHIFT: case VK_CONTROL: case VK_MENU: /* Alt key */ return FALSE; default: break; } /* special cases */ if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->AChar == NUL) { /* Ctrl-6 is Ctrl-^ */ if (pker->wVirtualKeyCode == '6') { *pch = Ctrl_HAT; return TRUE; } /* Ctrl-2 is Ctrl-@ */ else if (pker->wVirtualKeyCode == '2') { *pch = NUL; return TRUE; } /* Ctrl-- is Ctrl-_ */ else if (pker->wVirtualKeyCode == 0xBD) { *pch = Ctrl__; return TRUE; } } /* Shift-TAB */ if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED)) { *pch = K_NUL; *pch2 = '\017'; return TRUE; } for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; ) { if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode) { if (nModifs == 0) *pch = VirtKeyMap[i].chAlone; else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0) *pch = VirtKeyMap[i].chShift; else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0) *pch = VirtKeyMap[i].chCtrl; else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0) *pch = VirtKeyMap[i].chAlt; if (*pch != 0) { if (VirtKeyMap[i].fAnsiKey) { *pch2 = *pch; *pch = K_NUL; } return TRUE; } } } i = win32_kbd_patch_key(pker); if (i < 0) *pch = NUL; else { *pch = (i > 0) ? pker->AChar : NUL; if (pmodifiers != NULL) { /* Pass on the ALT key as a modifier, but only when not combined * with CTRL (which is ALTGR). */ if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0) *pmodifiers |= MOD_MASK_ALT; /* Pass on SHIFT only for special keys, because we don't know when * it's already included with the character. */ if ((nModifs & SHIFT) != 0 && *pch <= 0x20) *pmodifiers |= MOD_MASK_SHIFT; /* Pass on CTRL only for non-special keys, because we don't know * when it's already included with the character. And not when * combined with ALT (which is ALTGR). */ if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0 && *pch >= 0x20 && *pch < 0x80) *pmodifiers |= MOD_MASK_CTRL; } } return (*pch != NUL); } #ifdef _MSC_VER # pragma optimize("", on) #endif #endif /* FEAT_GUI_W32 */ #ifdef FEAT_MOUSE /* * For the GUI the mouse handling is in gui_w32.c. */ # ifdef FEAT_GUI_W32 /*ARGSUSED*/ void mch_setmouse(int on) { } # else static int g_fMouseAvail = FALSE; /* mouse present */ static int g_fMouseActive = FALSE; /* mouse enabled */ static int g_nMouseClick = -1; /* mouse status */ static int g_xMouse; /* mouse x coordinate */ static int g_yMouse; /* mouse y coordinate */ /* * Enable or disable mouse input */ void mch_setmouse(int on) { DWORD cmodein; if (!g_fMouseAvail) return; g_fMouseActive = on; GetConsoleMode(g_hConIn, &cmodein); if (g_fMouseActive) cmodein |= ENABLE_MOUSE_INPUT; else cmodein &= ~ENABLE_MOUSE_INPUT; SetConsoleMode(g_hConIn, cmodein); } /* * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT, * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type, * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick, * and we return the mouse position in g_xMouse and g_yMouse. * * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only * by MOUSE_LEFT, _MIDDLE, or _RIGHT. * * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE, * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, .... * * Windows will send us MOUSE_MOVED notifications whenever the mouse * moves, even if it stays within the same character cell. We ignore * all MOUSE_MOVED messages if the position hasn't really changed, and * we ignore all MOUSE_MOVED messages where no button is held down (i.e., * we're only interested in MOUSE_DRAG). * * All of this is complicated by the code that fakes MOUSE_MIDDLE on * 2-button mouses by pressing the left & right buttons simultaneously. * In practice, it's almost impossible to click both at the same time, * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE * in such cases, if the user is clicking quickly. */ static BOOL decode_mouse_event( MOUSE_EVENT_RECORD *pmer) { static int s_nOldButton = -1; static int s_nOldMouseClick = -1; static int s_xOldMouse = -1; static int s_yOldMouse = -1; static linenr_T s_old_topline = 0; #ifdef FEAT_DIFF static int s_old_topfill = 0; #endif static int s_cClicks = 1; static BOOL s_fReleased = TRUE; static DWORD s_dwLastClickTime = 0; static BOOL s_fNextIsMiddle = FALSE; static DWORD cButtons = 0; /* number of buttons supported */ const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED; const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED; const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED; const DWORD LEFT_RIGHT = LEFT | RIGHT; int nButton; if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons)) cButtons = 2; if (!g_fMouseAvail || !g_fMouseActive) { g_nMouseClick = -1; return FALSE; } /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */ if (g_fJustGotFocus) { g_fJustGotFocus = FALSE; return FALSE; } /* unprocessed mouse click? */ if (g_nMouseClick != -1) return TRUE; nButton = -1; g_xMouse = pmer->dwMousePosition.X; g_yMouse = pmer->dwMousePosition.Y; if (pmer->dwEventFlags == MOUSE_MOVED) { /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these * events even when the mouse moves only within a char cell.) */ if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse) return FALSE; } /* If no buttons are pressed... */ if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0) { /* If the last thing returned was MOUSE_RELEASE, ignore this */ if (s_fReleased) return FALSE; nButton = MOUSE_RELEASE; s_fReleased = TRUE; } else /* one or more buttons pressed */ { /* on a 2-button mouse, hold down left and right buttons * simultaneously to get MIDDLE. */ if (cButtons == 2 && s_nOldButton != MOUSE_DRAG) { DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT); /* if either left or right button only is pressed, see if the * the next mouse event has both of them pressed */ if (dwLR == LEFT || dwLR == RIGHT) { for (;;) { /* wait a short time for next input event */ if (WaitForSingleObject(g_hConIn, p_mouset / 3) != WAIT_OBJECT_0) break; else { DWORD cRecords = 0; INPUT_RECORD ir; MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent; PeekConsoleInput(g_hConIn, &ir, 1, &cRecords); if (cRecords == 0 || ir.EventType != MOUSE_EVENT || !(pmer2->dwButtonState & LEFT_RIGHT)) break; else { if (pmer2->dwEventFlags != MOUSE_MOVED) { ReadConsoleInput(g_hConIn, &ir, 1, &cRecords); return decode_mouse_event(pmer2); } else if (s_xOldMouse == pmer2->dwMousePosition.X && s_yOldMouse == pmer2->dwMousePosition.Y) { /* throw away spurious mouse move */ ReadConsoleInput(g_hConIn, &ir, 1, &cRecords); /* are there any more mouse events in queue? */ PeekConsoleInput(g_hConIn, &ir, 1, &cRecords); if (cRecords==0 || ir.EventType != MOUSE_EVENT) break; } else break; } } } } } if (s_fNextIsMiddle) { nButton = (pmer->dwEventFlags == MOUSE_MOVED) ? MOUSE_DRAG : MOUSE_MIDDLE; s_fNextIsMiddle = FALSE; } else if (cButtons == 2 && ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT)) { nButton = MOUSE_MIDDLE; if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED) { s_fNextIsMiddle = TRUE; nButton = MOUSE_RELEASE; } } else if ((pmer->dwButtonState & LEFT) == LEFT) nButton = MOUSE_LEFT; else if ((pmer->dwButtonState & MIDDLE) == MIDDLE) nButton = MOUSE_MIDDLE; else if ((pmer->dwButtonState & RIGHT) == RIGHT) nButton = MOUSE_RIGHT; if (! s_fReleased && ! s_fNextIsMiddle && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG) return FALSE; s_fReleased = s_fNextIsMiddle; } if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK) { /* button pressed or released, without mouse moving */ if (nButton != -1 && nButton != MOUSE_RELEASE) { DWORD dwCurrentTime = GetTickCount(); if (s_xOldMouse != g_xMouse || s_yOldMouse != g_yMouse || s_nOldButton != nButton || s_old_topline != curwin->w_topline #ifdef FEAT_DIFF || s_old_topfill != curwin->w_topfill #endif || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset) { s_cClicks = 1; } else if (++s_cClicks > 4) { s_cClicks = 1; } s_dwLastClickTime = dwCurrentTime; } } else if (pmer->dwEventFlags == MOUSE_MOVED) { if (nButton != -1 && nButton != MOUSE_RELEASE) nButton = MOUSE_DRAG; s_cClicks = 1; } if (nButton == -1) return FALSE; if (nButton != MOUSE_RELEASE) s_nOldButton = nButton; g_nMouseClick = nButton; if (pmer->dwControlKeyState & SHIFT_PRESSED) g_nMouseClick |= MOUSE_SHIFT; if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)) g_nMouseClick |= MOUSE_CTRL; if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)) g_nMouseClick |= MOUSE_ALT; if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE) SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks); /* only pass on interesting (i.e., different) mouse events */ if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse && s_nOldMouseClick == g_nMouseClick) { g_nMouseClick = -1; return FALSE; } s_xOldMouse = g_xMouse; s_yOldMouse = g_yMouse; s_old_topline = curwin->w_topline; #ifdef FEAT_DIFF s_old_topfill = curwin->w_topfill; #endif s_nOldMouseClick = g_nMouseClick; return TRUE; } # endif /* FEAT_GUI_W32 */ #endif /* FEAT_MOUSE */ #ifdef MCH_CURSOR_SHAPE /* * Set the shape of the cursor. * 'thickness' can be from 1 (thin) to 99 (block) */ static void mch_set_cursor_shape(int thickness) { CONSOLE_CURSOR_INFO ConsoleCursorInfo; ConsoleCursorInfo.dwSize = thickness; ConsoleCursorInfo.bVisible = s_cursor_visible; SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo); if (s_cursor_visible) SetConsoleCursorPosition(g_hConOut, g_coord); } void mch_update_cursor(void) { int idx; int thickness; /* * How the cursor is drawn depends on the current mode. */ idx = get_shape_idx(FALSE); if (shape_table[idx].shape == SHAPE_BLOCK) thickness = 99; /* 100 doesn't work on W95 */ else thickness = shape_table[idx].percentage; mch_set_cursor_shape(thickness); } #endif #ifndef FEAT_GUI_W32 /* this isn't used for the GUI */ /* * Handle FOCUS_EVENT. */ static void handle_focus_event(INPUT_RECORD ir) { g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus; ui_focus_change((int)g_fJustGotFocus); } /* * Wait until console input from keyboard or mouse is available, * or the time is up. * Return TRUE if something is available FALSE if not. */ static int WaitForChar(long msec) { DWORD dwNow = 0, dwEndTime = 0; INPUT_RECORD ir; DWORD cRecords; char_u ch, ch2; if (msec > 0) /* Wait until the specified time has elapsed. */ dwEndTime = GetTickCount() + msec; else if (msec < 0) /* Wait forever. */ dwEndTime = INFINITE; /* We need to loop until the end of the time period, because * we might get multiple unusable mouse events in that time. */ for (;;) { #ifdef FEAT_MZSCHEME mzvim_check_threads(); #endif #ifdef FEAT_CLIENTSERVER serverProcessPendingMessages(); #endif if (0 #ifdef FEAT_MOUSE || g_nMouseClick != -1 #endif #ifdef FEAT_CLIENTSERVER || input_available() #endif ) return TRUE; if (msec > 0) { /* If the specified wait time has passed, return. */ dwNow = GetTickCount(); if (dwNow >= dwEndTime) break; } if (msec != 0) { DWORD dwWaitTime = dwEndTime - dwNow; #ifdef FEAT_MZSCHEME if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || (long)dwWaitTime > p_mzq)) dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */ #endif #ifdef FEAT_CLIENTSERVER /* Wait for either an event on the console input or a message in * the client-server window. */ if (MsgWaitForMultipleObjects(1, &g_hConIn, FALSE, dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0) #else if (WaitForSingleObject(g_hConIn, dwWaitTime) != WAIT_OBJECT_0) #endif continue; } cRecords = 0; PeekConsoleInput(g_hConIn, &ir, 1, &cRecords); #ifdef FEAT_MBYTE_IME if (State & CMDLINE && msg_row == Rows - 1) { CONSOLE_SCREEN_BUFFER_INFO csbi; if (GetConsoleScreenBufferInfo(g_hConOut, &csbi)) { if (csbi.dwCursorPosition.Y != msg_row) { /* The screen is now messed up, must redraw the * command line and later all the windows. */ redraw_all_later(CLEAR); cmdline_row -= (msg_row - csbi.dwCursorPosition.Y); redrawcmd(); } } } #endif if (cRecords > 0) { if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown) { #ifdef FEAT_MBYTE_IME /* Windows IME sends two '\n's with only one 'ENTER'. First: * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */ if (ir.Event.KeyEvent.uChar.UnicodeChar == 0 && ir.Event.KeyEvent.wVirtualKeyCode == 13) { ReadConsoleInput(g_hConIn, &ir, 1, &cRecords); continue; } #endif if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2, NULL, FALSE)) return TRUE; } ReadConsoleInput(g_hConIn, &ir, 1, &cRecords); if (ir.EventType == FOCUS_EVENT) handle_focus_event(ir); else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT) shell_resized(); #ifdef FEAT_MOUSE else if (ir.EventType == MOUSE_EVENT && decode_mouse_event(&ir.Event.MouseEvent)) return TRUE; #endif } else if (msec == 0) break; } #ifdef FEAT_CLIENTSERVER /* Something might have been received while we were waiting. */ if (input_available()) return TRUE; #endif return FALSE; } #ifndef FEAT_GUI_MSWIN /* * return non-zero if a character is available */ int mch_char_avail(void) { return WaitForChar(0L); } #endif /* * Create the console input. Used when reading stdin doesn't work. */ static void create_conin(void) { g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, (LPSECURITY_ATTRIBUTES) NULL, OPEN_EXISTING, 0, (HANDLE)NULL); did_create_conin = TRUE; } /* * Get a keystroke or a mouse event */ static char_u tgetch(int *pmodifiers, char_u *pch2) { char_u ch; for (;;) { INPUT_RECORD ir; DWORD cRecords = 0; #ifdef FEAT_CLIENTSERVER (void)WaitForChar(-1L); if (input_available()) return 0; # ifdef FEAT_MOUSE if (g_nMouseClick != -1) return 0; # endif #endif if (ReadConsoleInput(g_hConIn, &ir, 1, &cRecords) == 0) { if (did_create_conin) read_error_exit(); create_conin(); continue; } if (ir.EventType == KEY_EVENT) { if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2, pmodifiers, TRUE)) return ch; } else if (ir.EventType == FOCUS_EVENT) handle_focus_event(ir); else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT) shell_resized(); #ifdef FEAT_MOUSE else if (ir.EventType == MOUSE_EVENT) { if (decode_mouse_event(&ir.Event.MouseEvent)) return 0; } #endif } } #endif /* !FEAT_GUI_W32 */ /* * mch_inchar(): low-level input funcion. * Get one or more characters from the keyboard or the mouse. * If time == 0, do not wait for characters. * If time == n, wait a short time for characters. * If time == -1, wait forever for characters. * Returns the number of characters read into buf. */ /*ARGSUSED*/ int mch_inchar( char_u *buf, int maxlen, long time, int tb_change_cnt) { #ifndef FEAT_GUI_W32 /* this isn't used for the GUI */ int len; int c; #define TYPEAHEADLEN 20 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */ static int typeaheadlen = 0; /* First use any typeahead that was kept because "buf" was too small. */ if (typeaheadlen > 0) goto theend; #ifdef FEAT_SNIFF if (want_sniff_request) { if (sniff_request_waiting) { /* return K_SNIFF */ typeahead[typeaheadlen++] = CSI; typeahead[typeaheadlen++] = (char_u)KS_EXTRA; typeahead[typeaheadlen++] = (char_u)KE_SNIFF; sniff_request_waiting = 0; want_sniff_request = 0; goto theend; } else if (time < 0 || time > 250) { /* don't wait too long, a request might be pending */ time = 250; } } #endif if (time >= 0) { if (!WaitForChar(time)) /* no character available */ return 0; } else /* time == -1, wait forever */ { mch_set_winsize_now(); /* Allow winsize changes from now on */ /* * If there is no character available within 2 seconds (default) * write the autoscript file to disk. Or cause the CursorHold event * to be triggered. */ if (!WaitForChar(p_ut)) { #ifdef FEAT_AUTOCMD if (trigger_cursorhold() && maxlen >= 3) { buf[0] = K_SPECIAL; buf[1] = KS_EXTRA; buf[2] = (int)KE_CURSORHOLD; return 3; } #endif before_blocking(); } } /* * Try to read as many characters as there are, until the buffer is full. */ /* we will get at least one key. Get more if they are available. */ g_fCBrkPressed = FALSE; #ifdef MCH_WRITE_DUMP if (fdDump) fputc('[', fdDump); #endif /* Keep looping until there is something in the typeahead buffer and more * to get and still room in the buffer (up to two bytes for a char and * three bytes for a modifier). */ while ((typeaheadlen == 0 || WaitForChar(0L)) && typeaheadlen + 5 <= TYPEAHEADLEN) { if (typebuf_changed(tb_change_cnt)) { /* "buf" may be invalid now if a client put something in the * typeahead buffer and "buf" is in the typeahead buffer. */ typeaheadlen = 0; break; } #ifdef FEAT_MOUSE if (g_nMouseClick != -1) { # ifdef MCH_WRITE_DUMP if (fdDump) fprintf(fdDump, "{%02x @ %d, %d}", g_nMouseClick, g_xMouse, g_yMouse); # endif typeahead[typeaheadlen++] = ESC + 128; typeahead[typeaheadlen++] = 'M'; typeahead[typeaheadlen++] = g_nMouseClick; typeahead[typeaheadlen++] = g_xMouse + '!'; typeahead[typeaheadlen++] = g_yMouse + '!'; g_nMouseClick = -1; } else #endif { char_u ch2 = NUL; int modifiers = 0; c = tgetch(&modifiers, &ch2); if (typebuf_changed(tb_change_cnt)) { /* "buf" may be invalid now if a client put something in the * typeahead buffer and "buf" is in the typeahead buffer. */ typeaheadlen = 0; break; } if (c == Ctrl_C && ctrl_c_interrupts) { #if defined(FEAT_CLIENTSERVER) trash_input_buf(); #endif got_int = TRUE; } #ifdef FEAT_MOUSE if (g_nMouseClick == -1) #endif { int n = 1; /* A key may have one or two bytes. */ typeahead[typeaheadlen] = c; if (ch2 != NUL) { typeahead[typeaheadlen + 1] = ch2; ++n; } #ifdef FEAT_MBYTE /* Only convert normal characters, not special keys. Need to * convert before applying ALT, otherwise mapping <M-x> breaks * when 'tenc' is set. */ if (input_conv.vc_type != CONV_NONE && (ch2 == NUL || c != K_NUL)) n = convert_input(typeahead + typeaheadlen, n, TYPEAHEADLEN - typeaheadlen); #endif /* Use the ALT key to set the 8th bit of the character * when it's one byte, the 8th bit isn't set yet and not * using a double-byte encoding (would become a lead * byte). */ if ((modifiers & MOD_MASK_ALT) && n == 1 && (typeahead[typeaheadlen] & 0x80) == 0 #ifdef FEAT_MBYTE && !enc_dbcs #endif ) { #ifdef FEAT_MBYTE n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80, typeahead + typeaheadlen); #else typeahead[typeaheadlen] |= 0x80; #endif modifiers &= ~MOD_MASK_ALT; } if (modifiers != 0) { /* Prepend modifiers to the character. */ mch_memmove(typeahead + typeaheadlen + 3, typeahead + typeaheadlen, n); typeahead[typeaheadlen++] = K_SPECIAL; typeahead[typeaheadlen++] = (char_u)KS_MODIFIER; typeahead[typeaheadlen++] = modifiers; } typeaheadlen += n; #ifdef MCH_WRITE_DUMP if (fdDump) fputc(c, fdDump); #endif } } } #ifdef MCH_WRITE_DUMP if (fdDump) { fputs("]\n", fdDump); fflush(fdDump); } #endif theend: /* Move typeahead to "buf", as much as fits. */ len = 0; while (len < maxlen && typeaheadlen > 0) { buf[len++] = typeahead[0]; mch_memmove(typeahead, typeahead + 1, --typeaheadlen); } return len; #else /* FEAT_GUI_W32 */ return 0; #endif /* FEAT_GUI_W32 */ } #ifndef __MINGW32__ # include <shellapi.h> /* required for FindExecutable() */ #endif /* * Return TRUE if "name" is in $PATH. * TODO: Should somehow check if it's really executable. */ static int executable_exists(char *name) { char *dum; char fname[_MAX_PATH]; #ifdef FEAT_MBYTE if (enc_codepage >= 0 && (int)GetACP() != enc_codepage) { WCHAR *p = enc_to_utf16(name, NULL); WCHAR fnamew[_MAX_PATH]; WCHAR *dumw; long n; if (p != NULL) { n = (long)SearchPathW(NULL, p, NULL, _MAX_PATH, fnamew, &dumw); vim_free(p); if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) { if (n == 0) return FALSE; if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY) return FALSE; return TRUE; } /* Retry with non-wide function (for Windows 98). */ } } #endif if (SearchPath(NULL, name, NULL, _MAX_PATH, fname, &dum) == 0) return FALSE; if (mch_isdir(fname)) return FALSE; return TRUE; } #if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \ __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400) /* * Bad parameter handler. * * Certain MS CRT functions will intentionally crash when passed invalid * parameters to highlight possible security holes. Setting this function as * the bad parameter handler will prevent the crash. * * In debug builds the parameters contain CRT information that might help track * down the source of a problem, but in non-debug builds the arguments are all * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is * worth allowing these to make debugging of issues easier. */ static void bad_param_handler(const wchar_t *expression, const wchar_t *function, const wchar_t *file, unsigned int line, uintptr_t pReserved) { } # define SET_INVALID_PARAM_HANDLER \ ((void)_set_invalid_parameter_handler(bad_param_handler)) #else # define SET_INVALID_PARAM_HANDLER #endif #ifdef FEAT_GUI_W32 /* * GUI version of mch_init(). */ void mch_init(void) { #ifndef __MINGW32__ extern int _fmode; #endif /* Silently handle invalid parameters to CRT functions */ SET_INVALID_PARAM_HANDLER; /* Let critical errors result in a failure, not in a dialog box. Required * for the timestamp test to work on removed floppies. */ SetErrorMode(SEM_FAILCRITICALERRORS); _fmode = O_BINARY; /* we do our own CR-LF translation */ /* Specify window size. Is there a place to get the default from? */ Rows = 25; Columns = 80; /* Look for 'vimrun' */ if (!gui_is_win32s()) { char_u vimrun_location[_MAX_PATH + 4]; /* First try in same directory as gvim.exe */ STRCPY(vimrun_location, exe_name); STRCPY(gettail(vimrun_location), "vimrun.exe"); if (mch_getperm(vimrun_location) >= 0) { if (*skiptowhite(vimrun_location) != NUL) { /* Enclose path with white space in double quotes. */ mch_memmove(vimrun_location + 1, vimrun_location, STRLEN(vimrun_location) + 1); *vimrun_location = '"'; STRCPY(gettail(vimrun_location), "vimrun\" "); } else STRCPY(gettail(vimrun_location), "vimrun "); vimrun_path = (char *)vim_strsave(vimrun_location); s_dont_use_vimrun = FALSE; } else if (executable_exists("vimrun.exe")) s_dont_use_vimrun = FALSE; /* Don't give the warning for a missing vimrun.exe right now, but only * when vimrun was supposed to be used. Don't bother people that do * not need vimrun.exe. */ if (s_dont_use_vimrun) need_vimrun_warning = TRUE; } /* * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'. * Otherwise the default "findstr /n" is used. */ if (!executable_exists("findstr.exe")) set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0); #ifdef FEAT_CLIPBOARD clip_init(TRUE); /* * Vim's own clipboard format recognises whether the text is char, line, * or rectangular block. Only useful for copying between two Vims. * "VimClipboard" was used for previous versions, using the first * character to specify MCHAR, MLINE or MBLOCK. */ clip_star.format = RegisterClipboardFormat("VimClipboard2"); clip_star.format_raw = RegisterClipboardFormat("VimRawBytes"); #endif } #else /* FEAT_GUI_W32 */ #define SRWIDTH(sr) ((sr).Right - (sr).Left + 1) #define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1) /* * ClearConsoleBuffer() * Description: * Clears the entire contents of the console screen buffer, using the * specified attribute. * Returns: * TRUE on success */ static BOOL ClearConsoleBuffer(WORD wAttribute) { CONSOLE_SCREEN_BUFFER_INFO csbi; COORD coord; DWORD NumCells, dummy; if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi)) return FALSE; NumCells = csbi.dwSize.X * csbi.dwSize.Y; coord.X = 0; coord.Y = 0; if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells, coord, &dummy)) { return FALSE; } if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells, coord, &dummy)) { return FALSE; } return TRUE; } /* * FitConsoleWindow() * Description: * Checks if the console window will fit within given buffer dimensions. * Also, if requested, will shrink the window to fit. * Returns: * TRUE on success */ static BOOL FitConsoleWindow( COORD dwBufferSize, BOOL WantAdjust) { CONSOLE_SCREEN_BUFFER_INFO csbi; COORD dwWindowSize; BOOL NeedAdjust = FALSE; if (GetConsoleScreenBufferInfo(g_hConOut, &csbi)) { /* * A buffer resize will fail if the current console window does * not lie completely within that buffer. To avoid this, we might * have to move and possibly shrink the window. */ if (csbi.srWindow.Right >= dwBufferSize.X) { dwWindowSize.X = SRWIDTH(csbi.srWindow); if (dwWindowSize.X > dwBufferSize.X) dwWindowSize.X = dwBufferSize.X; csbi.srWindow.Right = dwBufferSize.X - 1; csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X; NeedAdjust = TRUE; } if (csbi.srWindow.Bottom >= dwBufferSize.Y) { dwWindowSize.Y = SRHEIGHT(csbi.srWindow); if (dwWindowSize.Y > dwBufferSize.Y) dwWindowSize.Y = dwBufferSize.Y; csbi.srWindow.Bottom = dwBufferSize.Y - 1; csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y; NeedAdjust = TRUE; } if (NeedAdjust && WantAdjust) { if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow)) return FALSE; } return TRUE; } return FALSE; } typedef struct ConsoleBufferStruct { BOOL IsValid; CONSOLE_SCREEN_BUFFER_INFO Info; PCHAR_INFO Buffer; COORD BufferSize; } ConsoleBuffer; /* * SaveConsoleBuffer() * Description: * Saves important information about the console buffer, including the * actual buffer contents. The saved information is suitable for later * restoration by RestoreConsoleBuffer(). * Returns: * TRUE if all information was saved; FALSE otherwise * If FALSE, still sets cb->IsValid if buffer characteristics were saved. */ static BOOL SaveConsoleBuffer( ConsoleBuffer *cb) { DWORD NumCells; COORD BufferCoord; SMALL_RECT ReadRegion; WORD Y, Y_incr; if (cb == NULL) return FALSE; if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info)) { cb->IsValid = FALSE; return FALSE; } cb->IsValid = TRUE; /* * Allocate a buffer large enough to hold the entire console screen * buffer. If this ConsoleBuffer structure has already been initialized * with a buffer of the correct size, then just use that one. */ if (!cb->IsValid || cb->Buffer == NULL || cb->BufferSize.X != cb->Info.dwSize.X || cb->BufferSize.Y != cb->Info.dwSize.Y) { cb->BufferSize.X = cb->Info.dwSize.X; cb->BufferSize.Y = cb->Info.dwSize.Y; NumCells = cb->BufferSize.X * cb->BufferSize.Y; vim_free(cb->Buffer); cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO)); if (cb->Buffer == NULL) return FALSE; } /* * We will now copy the console screen buffer into our buffer. * ReadConsoleOutput() seems to be limited as far as how much you * can read at a time. Empirically, this number seems to be about * 12000 cells (rows * columns). Start at position (0, 0) and copy * in chunks until it is all copied. The chunks will all have the * same horizontal characteristics, so initialize them now. The * height of each chunk will be (12000 / width). */ BufferCoord.X = 0; ReadRegion.Left = 0; ReadRegion.Right = cb->Info.dwSize.X - 1; Y_incr = 12000 / cb->Info.dwSize.X; for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr) { /* * Read into position (0, Y) in our buffer. */ BufferCoord.Y = Y; /* * Read the region whose top left corner is (0, Y) and whose bottom * right corner is (width - 1, Y + Y_incr - 1). This should define * a region of size width by Y_incr. Don't worry if this region is * too large for the remaining buffer; it will be cropped. */ ReadRegion.Top = Y; ReadRegion.Bottom = Y + Y_incr - 1; if (!ReadConsoleOutput(g_hConOut, /* output handle */ cb->Buffer, /* our buffer */ cb->BufferSize, /* dimensions of our buffer */ BufferCoord, /* offset in our buffer */ &ReadRegion)) /* region to save */ { vim_free(cb->Buffer); cb->Buffer = NULL; return FALSE; } } return TRUE; } /* * RestoreConsoleBuffer() * Description: * Restores important information about the console buffer, including the * actual buffer contents, if desired. The information to restore is in * the same format used by SaveConsoleBuffer(). * Returns: * TRUE on success */ static BOOL RestoreConsoleBuffer( ConsoleBuffer *cb, BOOL RestoreScreen) { COORD BufferCoord; SMALL_RECT WriteRegion; if (cb == NULL || !cb->IsValid) return FALSE; /* * Before restoring the buffer contents, clear the current buffer, and * restore the cursor position and window information. Doing this now * prevents old buffer contents from "flashing" onto the screen. */ if (RestoreScreen) ClearConsoleBuffer(cb->Info.wAttributes); FitConsoleWindow(cb->Info.dwSize, TRUE); if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize)) return FALSE; if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes)) return FALSE; if (!RestoreScreen) { /* * No need to restore the screen buffer contents, so we're done. */ return TRUE; } if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition)) return FALSE; if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow)) return FALSE; /* * Restore the screen buffer contents. */ if (cb->Buffer != NULL) { BufferCoord.X = 0; BufferCoord.Y = 0; WriteRegion.Left = 0; WriteRegion.Top = 0; WriteRegion.Right = cb->Info.dwSize.X - 1; WriteRegion.Bottom = cb->Info.dwSize.Y - 1; if (!WriteConsoleOutput(g_hConOut, /* output handle */ cb->Buffer, /* our buffer */ cb->BufferSize, /* dimensions of our buffer */ BufferCoord, /* offset in our buffer */ &WriteRegion)) /* region to restore */ { return FALSE; } } return TRUE; } #define FEAT_RESTORE_ORIG_SCREEN #ifdef FEAT_RESTORE_ORIG_SCREEN static ConsoleBuffer g_cbOrig = { 0 }; #endif static ConsoleBuffer g_cbNonTermcap = { 0 }; static ConsoleBuffer g_cbTermcap = { 0 }; #ifdef FEAT_TITLE #ifdef __BORLANDC__ typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID); #else typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID); #endif char g_szOrigTitle[256] = { 0 }; HWND g_hWnd = NULL; /* also used in os_mswin.c */ static HICON g_hOrigIconSmall = NULL; static HICON g_hOrigIcon = NULL; static HICON g_hVimIcon = NULL; static BOOL g_fCanChangeIcon = FALSE; /* ICON* are not defined in VC++ 4.0 */ #ifndef ICON_SMALL #define ICON_SMALL 0 #endif #ifndef ICON_BIG #define ICON_BIG 1 #endif /* * GetConsoleIcon() * Description: * Attempts to retrieve the small icon and/or the big icon currently in * use by a given window. * Returns: * TRUE on success */ static BOOL GetConsoleIcon( HWND hWnd, HICON *phIconSmall, HICON *phIcon) { if (hWnd == NULL) return FALSE; if (phIconSmall != NULL) *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON, (WPARAM)ICON_SMALL, (LPARAM)0); if (phIcon != NULL) *phIcon = (HICON)SendMessage(hWnd, WM_GETICON, (WPARAM)ICON_BIG, (LPARAM)0); return TRUE; } /* * SetConsoleIcon() * Description: * Attempts to change the small icon and/or the big icon currently in * use by a given window. * Returns: * TRUE on success */ static BOOL SetConsoleIcon( HWND hWnd, HICON hIconSmall, HICON hIcon) { HICON hPrevIconSmall; HICON hPrevIcon; if (hWnd == NULL) return FALSE; if (hIconSmall != NULL) hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIconSmall); if (hIcon != NULL) hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON, (WPARAM)ICON_BIG,(LPARAM) hIcon); return TRUE; } /* * SaveConsoleTitleAndIcon() * Description: * Saves the current console window title in g_szOrigTitle, for later * restoration. Also, attempts to obtain a handle to the console window, * and use it to save the small and big icons currently in use by the * console window. This is not always possible on some versions of Windows; * nor is it possible when running Vim remotely using Telnet (since the * console window the user sees is owned by a remote process). */ static void SaveConsoleTitleAndIcon(void) { GETCONSOLEWINDOWPROC GetConsoleWindowProc; /* Save the original title. */ if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle))) return; /* * Obtain a handle to the console window using GetConsoleWindow() from * KERNEL32.DLL; we need to handle in order to change the window icon. * This function only exists on NT-based Windows, starting with Windows * 2000. On older operating systems, we can't change the window icon * anyway. */ if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC) GetProcAddress(GetModuleHandle("KERNEL32.DLL"), "GetConsoleWindow")) != NULL) { g_hWnd = (*GetConsoleWindowProc)(); } if (g_hWnd == NULL) return; /* Save the original console window icon. */ GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon); if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL) return; /* Extract the first icon contained in the Vim executable. */ g_hVimIcon = ExtractIcon(NULL, exe_name, 0); if (g_hVimIcon != NULL) g_fCanChangeIcon = TRUE; } #endif static int g_fWindInitCalled = FALSE; static int g_fTermcapMode = FALSE; static CONSOLE_CURSOR_INFO g_cci; static DWORD g_cmodein = 0; static DWORD g_cmodeout = 0; /* * non-GUI version of mch_init(). */ void mch_init(void) { #ifndef FEAT_RESTORE_ORIG_SCREEN CONSOLE_SCREEN_BUFFER_INFO csbi; #endif #ifndef __MINGW32__ extern int _fmode; #endif /* Silently handle invalid parameters to CRT functions */ SET_INVALID_PARAM_HANDLER; /* Let critical errors result in a failure, not in a dialog box. Required * for the timestamp test to work on removed floppies. */ SetErrorMode(SEM_FAILCRITICALERRORS); _fmode = O_BINARY; /* we do our own CR-LF translation */ out_flush(); /* Obtain handles for the standard Console I/O devices */ if (read_cmd_fd == 0) g_hConIn = GetStdHandle(STD_INPUT_HANDLE); else create_conin(); g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE); #ifdef FEAT_RESTORE_ORIG_SCREEN /* Save the initial console buffer for later restoration */ SaveConsoleBuffer(&g_cbOrig); g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes; #else /* Get current text attributes */ GetConsoleScreenBufferInfo(g_hConOut, &csbi); g_attrCurrent = g_attrDefault = csbi.wAttributes; #endif if (cterm_normal_fg_color == 0) cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1; if (cterm_normal_bg_color == 0) cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1; /* set termcap codes to current text attributes */ update_tcap(g_attrCurrent); GetConsoleCursorInfo(g_hConOut, &g_cci); GetConsoleMode(g_hConIn, &g_cmodein); GetConsoleMode(g_hConOut, &g_cmodeout); #ifdef FEAT_TITLE SaveConsoleTitleAndIcon(); /* * Set both the small and big icons of the console window to Vim's icon. * Note that Vim presently only has one size of icon (32x32), but it * automatically gets scaled down to 16x16 when setting the small icon. */ if (g_fCanChangeIcon) SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon); #endif ui_get_shellsize(); #ifdef MCH_WRITE_DUMP fdDump = fopen("dump", "wt"); if (fdDump) { time_t t; time(&t); fputs(ctime(&t), fdDump); fflush(fdDump); } #endif g_fWindInitCalled = TRUE; #ifdef FEAT_MOUSE g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT); #endif #ifdef FEAT_CLIPBOARD clip_init(TRUE); /* * Vim's own clipboard format recognises whether the text is char, line, or * rectangular block. Only useful for copying between two Vims. * "VimClipboard" was used for previous versions, using the first * character to specify MCHAR, MLINE or MBLOCK. */ clip_star.format = RegisterClipboardFormat("VimClipboard2"); clip_star.format_raw = RegisterClipboardFormat("VimRawBytes"); #endif /* This will be NULL on anything but NT 4.0 */ s_pfnGetConsoleKeyboardLayoutName = (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"), "GetConsoleKeyboardLayoutNameA"); } /* * non-GUI version of mch_exit(). * Shut down and exit with status `r' * Careful: mch_exit() may be called before mch_init()! */ void mch_exit(int r) { stoptermcap(); if (g_fWindInitCalled) settmode(TMODE_COOK); ml_close_all(TRUE); /* remove all memfiles */ if (g_fWindInitCalled) { #ifdef FEAT_TITLE mch_restore_title(3); /* * Restore both the small and big icons of the console window to * what they were at startup. Don't do this when the window is * closed, Vim would hang here. */ if (g_fCanChangeIcon && !g_fForceExit) SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon); #endif #ifdef MCH_WRITE_DUMP if (fdDump) { time_t t; time(&t); fputs(ctime(&t), fdDump); fclose(fdDump); } fdDump = NULL; #endif } SetConsoleCursorInfo(g_hConOut, &g_cci); SetConsoleMode(g_hConIn, g_cmodein); SetConsoleMode(g_hConOut, g_cmodeout); #ifdef DYNAMIC_GETTEXT dyn_libintl_end(); #endif exit(r); } #endif /* !FEAT_GUI_W32 */ /* * Do we have an interactive window? */ /*ARGSUSED*/ int mch_check_win( int argc, char **argv) { get_exe_name(); #ifdef FEAT_GUI_W32 return OK; /* GUI always has a tty */ #else if (isatty(1)) return OK; return FAIL; #endif } /* * fname_case(): Set the case of the file name, if it already exists. * When "len" is > 0, also expand short to long filenames. */ void fname_case( char_u *name, int len) { char szTrueName[_MAX_PATH + 2]; char szTrueNameTemp[_MAX_PATH + 2]; char *ptrue, *ptruePrev; char *porig, *porigPrev; int flen; WIN32_FIND_DATA fb; HANDLE hFind; int c; int slen; flen = (int)STRLEN(name); if (flen == 0 || flen > _MAX_PATH) return; slash_adjust(name); /* Build the new name in szTrueName[] one component at a time. */ porig = name; ptrue = szTrueName; if (isalpha(porig[0]) && porig[1] == ':') { /* copy leading drive letter */ *ptrue++ = *porig++; *ptrue++ = *porig++; *ptrue = NUL; /* in case nothing follows */ } while (*porig != NUL) { /* copy \ characters */ while (*porig == psepc) *ptrue++ = *porig++; ptruePrev = ptrue; porigPrev = porig; while (*porig != NUL && *porig != psepc) { #ifdef FEAT_MBYTE int l; if (enc_dbcs) { l = (*mb_ptr2len)(porig); while (--l >= 0) *ptrue++ = *porig++; } else #endif *ptrue++ = *porig++; } *ptrue = NUL; /* To avoid a slow failure append "\*" when searching a directory, * server or network share. */ STRCPY(szTrueNameTemp, szTrueName); slen = (int)strlen(szTrueNameTemp); if (*porig == psepc && slen + 2 < _MAX_PATH) STRCPY(szTrueNameTemp + slen, "\\*"); /* Skip "", "." and "..". */ if (ptrue > ptruePrev && (ptruePrev[0] != '.' || (ptruePrev[1] != NUL && (ptruePrev[1] != '.' || ptruePrev[2] != NUL))) && (hFind = FindFirstFile(szTrueNameTemp, &fb)) != INVALID_HANDLE_VALUE) { c = *porig; *porig = NUL; /* Only use the match when it's the same name (ignoring case) or * expansion is allowed and there is a match with the short name * and there is enough room. */ if (_stricoll(porigPrev, fb.cFileName) == 0 || (len > 0 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0 && (int)(ptruePrev - szTrueName) + (int)strlen(fb.cFileName) < len))) { STRCPY(ptruePrev, fb.cFileName); /* Look for exact match and prefer it if found. Must be a * long name, otherwise there would be only one match. */ while (FindNextFile(hFind, &fb)) { if (*fb.cAlternateFileName != NUL && (strcoll(porigPrev, fb.cFileName) == 0 || (len > 0 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0 && (int)(ptruePrev - szTrueName) + (int)strlen(fb.cFileName) < len)))) { STRCPY(ptruePrev, fb.cFileName); break; } } } FindClose(hFind); *porig = c; ptrue = ptruePrev + strlen(ptruePrev); } } STRCPY(name, szTrueName); } /* * Insert user name in s[len]. */ int mch_get_user_name( char_u *s, int len) { char szUserName[256 + 1]; /* UNLEN is 256 */ DWORD cch = sizeof szUserName; if (GetUserName(szUserName, &cch)) { vim_strncpy(s, szUserName, len - 1); return OK; } s[0] = NUL; return FAIL; } /* * Insert host name in s[len]. */ void mch_get_host_name( char_u *s, int len) { DWORD cch = len; if (!GetComputerName(s, &cch)) vim_strncpy(s, "PC (Win32 Vim)", len - 1); } /* * return process ID */ long mch_get_pid(void) { return (long)GetCurrentProcessId(); } /* * Get name of current directory into buffer 'buf' of length 'len' bytes. * Return OK for success, FAIL for failure. */ int mch_dirname( char_u *buf, int len) { /* * Originally this was: * return (getcwd(buf, len) != NULL ? OK : FAIL); * But the Win32s known bug list says that getcwd() doesn't work * so use the Win32 system call instead. <Negri> */ #ifdef FEAT_MBYTE if (enc_codepage >= 0 && (int)GetACP() != enc_codepage) { WCHAR wbuf[_MAX_PATH + 1]; if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0) { char_u *p = utf16_to_enc(wbuf, NULL); if (p != NULL) { vim_strncpy(buf, p, len - 1); vim_free(p); return OK; } } /* Retry with non-wide function (for Windows 98). */ } #endif return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL); } /* * get file permissions for `name' * -1 : error * else FILE_ATTRIBUTE_* defined in winnt.h */ long mch_getperm(char_u *name) { #ifdef FEAT_MBYTE if (enc_codepage >= 0 && (int)GetACP() != enc_codepage) { WCHAR *p = enc_to_utf16(name, NULL); long n; if (p != NULL) { n = (long)GetFileAttributesW(p); vim_free(p); if (n >= 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) return n; /* Retry with non-wide function (for Windows 98). */ } } #endif return (long)GetFileAttributes((char *)name); } /* * set file permission for `name' to `perm' */ int mch_setperm( char_u *name, long perm) { perm |= FILE_ATTRIBUTE_ARCHIVE; /* file has changed, set archive bit */ #ifdef FEAT_MBYTE if (enc_codepage >= 0 && (int)GetACP() != enc_codepage) { WCHAR *p = enc_to_utf16(name, NULL); long n; if (p != NULL) { n = (long)SetFileAttributesW(p, perm); vim_free(p); if (n || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) return n ? OK : FAIL; /* Retry with non-wide function (for Windows 98). */ } } #endif return SetFileAttributes((char *)name, perm) ? OK : FAIL; } /* * Set hidden flag for "name". */ void mch_hide(char_u *name) { int perm; #ifdef FEAT_MBYTE WCHAR *p = NULL; if (enc_codepage >= 0 && (int)GetACP() != enc_codepage) p = enc_to_utf16(name, NULL); #endif #ifdef FEAT_MBYTE if (p != NULL) { perm = GetFileAttributesW(p); if (perm < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED) { /* Retry with non-wide function (for Windows 98). */ vim_free(p); p = NULL; } } if (p == NULL) #endif perm = GetFileAttributes((char *)name); if (perm >= 0) { perm |= FILE_ATTRIBUTE_HIDDEN; #ifdef FEAT_MBYTE if (p != NULL) { if (SetFileAttributesW(p, perm) == 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED) { /* Retry with non-wide function (for Windows 98). */ vim_free(p); p = NULL; } } if (p == NULL) #endif SetFileAttributes((char *)name, perm); } #ifdef FEAT_MBYTE vim_free(p); #endif } /* * return TRUE if "name" is a directory * return FALSE if "name" is not a directory or upon error */ int mch_isdir(char_u *name) { int f = mch_getperm(name); if (f == -1) return FALSE; /* file does not exist at all */ return (f & FILE_ATTRIBUTE_DIRECTORY) != 0; } /* * Create directory "name". * Return 0 on success, -1 on error. */ int mch_mkdir(char_u *name) { #ifdef FEAT_MBYTE if (enc_codepage >= 0 && (int)GetACP() != enc_codepage) { WCHAR *p; int retval; p = enc_to_utf16(name, NULL); if (p == NULL) return -1; retval = _wmkdir(p); vim_free(p); return retval; } #endif return _mkdir(name); } /* * Return TRUE if file "fname" has more than one link. */ int mch_is_linked(char_u *fname) { BY_HANDLE_FILE_INFORMATION info; return win32_fileinfo(fname, &info) == FILEINFO_OK && info.nNumberOfLinks > 1; } /* * Get the by-handle-file-information for "fname". * Returns FILEINFO_OK when OK. * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed. * Returns FILEINFO_READ_FAIL when CreateFile() failed. * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed. */ int win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info) { HANDLE hFile; int res = FILEINFO_READ_FAIL; #ifdef FEAT_MBYTE WCHAR *wn = NULL; if (enc_codepage >= 0 && (int)GetACP() != enc_codepage) { wn = enc_to_utf16(fname, NULL); if (wn == NULL) res = FILEINFO_ENC_FAIL; } if (wn != NULL) { hFile = CreateFileW(wn, /* file name */ GENERIC_READ, /* access mode */ FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */ NULL, /* security descriptor */ OPEN_EXISTING, /* creation disposition */ FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */ NULL); /* handle to template file */ if (hFile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED) { /* Retry with non-wide function (for Windows 98). */ vim_free(wn); wn = NULL; } } if (wn == NULL) #endif hFile = CreateFile(fname, /* file name */ GENERIC_READ, /* access mode */ FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */ NULL, /* security descriptor */ OPEN_EXISTING, /* creation disposition */ FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */ NULL); /* handle to template file */ if (hFile != INVALID_HANDLE_VALUE) { if (GetFileInformationByHandle(hFile, info) != 0) res = FILEINFO_OK; else res = FILEINFO_INFO_FAIL; CloseHandle(hFile); } #ifdef FEAT_MBYTE vim_free(wn); #endif return res; } /* * Return TRUE if file or directory "name" is writable (not readonly). * Strange semantics of Win32: a readonly directory is writable, but you can't * delete a file. Let's say this means it is writable. */ int mch_writable(char_u *name) { int perm = mch_getperm(name); return (perm != -1 && (!(perm & FILE_ATTRIBUTE_READONLY) || (perm & FILE_ATTRIBUTE_DIRECTORY))); } /* * Return 1 if "name" can be executed, 0 if not. * Return -1 if unknown. */ int mch_can_exe(char_u *name) { char_u buf[_MAX_PATH]; int len = (int)STRLEN(name); char_u *p; if (len >= _MAX_PATH) /* safety check */ return FALSE; /* If there already is an extension try using the name directly. Also do * this with a Unix-shell like 'shell'. */ if (vim_strchr(gettail(name), '.') != NULL || strstr((char *)gettail(p_sh), "sh") != NULL) if (executable_exists((char *)name)) return TRUE; /* * Loop over all extensions in $PATHEXT. */ vim_strncpy(buf, name, _MAX_PATH - 1); p = mch_getenv("PATHEXT"); if (p == NULL) p = (char_u *)".com;.exe;.bat;.cmd"; while (*p) { if (p[0] == '.' && (p[1] == NUL || p[1] == ';')) { /* A single "." means no extension is added. */ buf[len] = NUL; ++p; if (*p) ++p; } else copy_option_part(&p, buf + len, _MAX_PATH - len, ";"); if (executable_exists((char *)buf)) return TRUE; } return FALSE; } /* * Check what "name" is: * NODE_NORMAL: file or directory (or doesn't exist) * NODE_WRITABLE: writable device, socket, fifo, etc. * NODE_OTHER: non-writable things */ int mch_nodetype(char_u *name) { HANDLE hFile; int type; /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to * read from it later will cause Vim to hang. Thus return NODE_WRITABLE * here. */ if (STRNCMP(name, "\\\\.\\", 4) == 0) return NODE_WRITABLE; hFile = CreateFile(name, /* file name */ GENERIC_WRITE, /* access mode */ 0, /* share mode */ NULL, /* security descriptor */ OPEN_EXISTING, /* creation disposition */ 0, /* file attributes */ NULL); /* handle to template file */ if (hFile == INVALID_HANDLE_VALUE) return NODE_NORMAL; type = GetFileType(hFile); CloseHandle(hFile); if (type == FILE_TYPE_CHAR) return NODE_WRITABLE; if (type == FILE_TYPE_DISK) return NODE_NORMAL; return NODE_OTHER; } #ifdef HAVE_ACL struct my_acl { PSECURITY_DESCRIPTOR pSecurityDescriptor; PSID pSidOwner; PSID pSidGroup; PACL pDacl; PACL pSacl; }; #endif /* * Return a pointer to the ACL of file "fname" in allocated memory. * Return NULL if the ACL is not available for whatever reason. */ vim_acl_T mch_get_acl(char_u *fname) { #ifndef HAVE_ACL return (vim_acl_T)NULL; #else struct my_acl *p = NULL; /* This only works on Windows NT and 2000. */ if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL) { p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl)); if (p != NULL) { if (pGetNamedSecurityInfo( (LPTSTR)fname, // Abstract filename SE_FILE_OBJECT, // File Object // Retrieve the entire security descriptor. OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION, &p->pSidOwner, // Ownership information. &p->pSidGroup, // Group membership. &p->pDacl, // Discretionary information. &p->pSacl, // For auditing purposes. &p->pSecurityDescriptor ) != ERROR_SUCCESS) { mch_free_acl((vim_acl_T)p); p = NULL; } } } return (vim_acl_T)p; #endif } /* * Set the ACL of file "fname" to "acl" (unless it's NULL). * Errors are ignored. * This must only be called with "acl" equal to what mch_get_acl() returned. */ void mch_set_acl(char_u *fname, vim_acl_T acl) { #ifdef HAVE_ACL struct my_acl *p = (struct my_acl *)acl; if (p != NULL && advapi_lib != NULL) (void)pSetNamedSecurityInfo( (LPTSTR)fname, // Abstract filename SE_FILE_OBJECT, // File Object // Retrieve the entire security descriptor. OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION, p->pSidOwner, // Ownership information. p->pSidGroup, // Group membership. p->pDacl, // Discretionary information. p->pSacl // For auditing purposes. ); #endif } void mch_free_acl(vim_acl_T acl) { #ifdef HAVE_ACL struct my_acl *p = (struct my_acl *)acl; if (p != NULL) { LocalFree(p->pSecurityDescriptor); // Free the memory just in case vim_free(p); } #endif } #ifndef FEAT_GUI_W32 /* * handler for ctrl-break, ctrl-c interrupts, and fatal events. */ static BOOL WINAPI handler_routine( DWORD dwCtrlType) { switch (dwCtrlType) { case CTRL_C_EVENT: if (ctrl_c_interrupts) g_fCtrlCPressed = TRUE; return TRUE; case CTRL_BREAK_EVENT: g_fCBrkPressed = TRUE; return TRUE; /* fatal events: shut down gracefully */ case CTRL_CLOSE_EVENT: case CTRL_LOGOFF_EVENT: case CTRL_SHUTDOWN_EVENT: windgoto((int)Rows - 1, 0); g_fForceExit = TRUE; vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"), (dwCtrlType == CTRL_CLOSE_EVENT ? _("close") : dwCtrlType == CTRL_LOGOFF_EVENT ? _("logoff") : _("shutdown"))); #ifdef DEBUG OutputDebugString(IObuff); #endif preserve_exit(); /* output IObuff, preserve files and exit */ return TRUE; /* not reached */ default: return FALSE; } } /* * set the tty in (raw) ? "raw" : "cooked" mode */ void mch_settmode(int tmode) { DWORD cmodein; DWORD cmodeout; BOOL bEnableHandler; GetConsoleMode(g_hConIn, &cmodein); GetConsoleMode(g_hConOut, &cmodeout); if (tmode == TMODE_RAW) { cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT); #ifdef FEAT_MOUSE if (g_fMouseActive) cmodein |= ENABLE_MOUSE_INPUT; #endif cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT); bEnableHandler = TRUE; } else /* cooked */ { cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT); cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT); bEnableHandler = FALSE; } SetConsoleMode(g_hConIn, cmodein); SetConsoleMode(g_hConOut, cmodeout); SetConsoleCtrlHandler(handler_routine, bEnableHandler); #ifdef MCH_WRITE_DUMP if (fdDump) { fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n", tmode == TMODE_RAW ? "raw" : tmode == TMODE_COOK ? "cooked" : "normal", cmodein, cmodeout); fflush(fdDump); } #endif } /* * Get the size of the current window in `Rows' and `Columns' * Return OK when size could be determined, FAIL otherwise. */ int mch_get_shellsize(void) { CONSOLE_SCREEN_BUFFER_INFO csbi; if (!g_fTermcapMode && g_cbTermcap.IsValid) { /* * For some reason, we are trying to get the screen dimensions * even though we are not in termcap mode. The 'Rows' and 'Columns' * variables are really intended to mean the size of Vim screen * while in termcap mode. */ Rows = g_cbTermcap.Info.dwSize.Y; Columns = g_cbTermcap.Info.dwSize.X; } else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi)) { Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1; Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1; } else { Rows = 25; Columns = 80; } return OK; } /* * Set a console window to `xSize' * `ySize' */ static void ResizeConBufAndWindow( HANDLE hConsole, int xSize, int ySize) { CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */ SMALL_RECT srWindowRect; /* hold the new console size */ COORD coordScreen; #ifdef MCH_WRITE_DUMP if (fdDump) { fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize); fflush(fdDump); } #endif /* get the largest size we can size the console window to */ coordScreen = GetLargestConsoleWindowSize(hConsole); /* define the new console window size and scroll position */ srWindowRect.Left = srWindowRect.Top = (SHORT) 0; srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1); srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1); if (GetConsoleScreenBufferInfo(g_hConOut, &csbi)) { int sx, sy; sx = csbi.srWindow.Right - csbi.srWindow.Left + 1; sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1; if (sy < ySize || sx < xSize) { /* * Increasing number of lines/columns, do buffer first. * Use the maximal size in x and y direction. */ if (sy < ySize) coordScreen.Y = ySize; else coordScreen.Y = sy; if (sx < xSize) coordScreen.X = xSize; else coordScreen.X = sx; SetConsoleScreenBufferSize(hConsole, coordScreen); } } if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect)) { #ifdef MCH_WRITE_DUMP if (fdDump) { fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n", GetLastError()); fflush(fdDump); } #endif } /* define the new console buffer size */ coordScreen.X = xSize; coordScreen.Y = ySize; if (!SetConsoleScreenBufferSize(hConsole, coordScreen)) { #ifdef MCH_WRITE_DUMP if (fdDump) { fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n", GetLastError()); fflush(fdDump); } #endif } } /* * Set the console window to `Rows' * `Columns' */ void mch_set_shellsize(void) { COORD coordScreen; /* Don't change window size while still starting up */ if (suppress_winsize != 0) { suppress_winsize = 2; return; } if (term_console) { coordScreen = GetLargestConsoleWindowSize(g_hConOut); /* Clamp Rows and Columns to reasonable values */ if (Rows > coordScreen.Y) Rows = coordScreen.Y; if (Columns > coordScreen.X) Columns = coordScreen.X; ResizeConBufAndWindow(g_hConOut, Columns, Rows); } } /* * Rows and/or Columns has changed. */ void mch_new_shellsize(void) { set_scroll_region(0, 0, Columns - 1, Rows - 1); } /* * Called when started up, to set the winsize that was delayed. */ void mch_set_winsize_now(void) { if (suppress_winsize == 2) { suppress_winsize = 0; mch_set_shellsize(); shell_resized(); } suppress_winsize = 0; } #endif /* FEAT_GUI_W32 */ #if defined(FEAT_GUI_W32) || defined(PROTO) /* * Specialised version of system() for Win32 GUI mode. * This version proceeds as follows: * 1. Create a console window for use by the subprocess * 2. Run the subprocess (it gets the allocated console by default) * 3. Wait for the subprocess to terminate and get its exit code * 4. Prompt the user to press a key to close the console window */ static int mch_system_classic(char *cmd, int options) { STARTUPINFO si; PROCESS_INFORMATION pi; DWORD ret = 0; HWND hwnd = GetFocus(); si.cb = sizeof(si); si.lpReserved = NULL; si.lpDesktop = NULL; si.lpTitle = NULL; si.dwFlags = STARTF_USESHOWWINDOW; /* * It's nicer to run a filter command in a minimized window, but in * Windows 95 this makes the command MUCH slower. We can't do it under * Win32s either as it stops the synchronous spawn workaround working. * Don't activate the window to keep focus on Vim. */ if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s()) si.wShowWindow = SW_SHOWMINNOACTIVE; else si.wShowWindow = SW_SHOWNORMAL; si.cbReserved2 = 0; si.lpReserved2 = NULL; /* There is a strange error on Windows 95 when using "c:\\command.com". * When the "c:\\" is left out it works OK...? */ if (mch_windows95() && (STRNICMP(cmd, "c:/command.com", 14) == 0 || STRNICMP(cmd, "c:\\command.com", 14) == 0)) cmd += 3; /* Now, run the command */ CreateProcess(NULL, /* Executable name */ cmd, /* Command to execute */ NULL, /* Process security attributes */ NULL, /* Thread security attributes */ FALSE, /* Inherit handles */ CREATE_DEFAULT_ERROR_MODE | /* Creation flags */ CREATE_NEW_CONSOLE, NULL, /* Environment */ NULL, /* Current directory */ &si, /* Startup information */ &pi); /* Process information */ /* Wait for the command to terminate before continuing */ if (g_PlatformId != VER_PLATFORM_WIN32s) { #ifdef FEAT_GUI int delay = 1; /* Keep updating the window while waiting for the shell to finish. */ for (;;) { MSG msg; if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); pDispatchMessage(&msg); } if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT) break; /* We start waiting for a very short time and then increase it, so * that we respond quickly when the process is quick, and don't * consume too much overhead when it's slow. */ if (delay < 50) delay += 10; } #else WaitForSingleObject(pi.hProcess, INFINITE); #endif /* Get the command exit code */ GetExitCodeProcess(pi.hProcess, &ret); } else { /* * This ugly code is the only quick way of performing * a synchronous spawn under Win32s. Yuk. */ num_windows = 0; EnumWindows(win32ssynch_cb, 0); old_num_windows = num_windows; do { Sleep(1000); num_windows = 0; EnumWindows(win32ssynch_cb, 0); } while (num_windows == old_num_windows); ret = 0; } /* Close the handles to the subprocess, so that it goes away */ CloseHandle(pi.hThread); CloseHandle(pi.hProcess); /* Try to get input focus back. Doesn't always work though. */ PostMessage(hwnd, WM_SETFOCUS, 0, 0); return ret; } /* * Thread launched by the gui to send the current buffer data to the * process. This way avoid to hang up vim totally if the children * process take a long time to process the lines. */ static DWORD WINAPI sub_process_writer(LPVOID param) { HANDLE g_hChildStd_IN_Wr = param; linenr_T lnum = curbuf->b_op_start.lnum; DWORD len = 0; DWORD l; char_u *lp = ml_get(lnum); char_u *s; int written = 0; for (;;) { l = (DWORD)STRLEN(lp + written); if (l == 0) len = 0; else if (lp[written] == NL) { /* NL -> NUL translation */ WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL); } else { s = vim_strchr(lp + written, NL); WriteFile(g_hChildStd_IN_Wr, (char *)lp + written, s == NULL ? l : (DWORD)(s - (lp + written)), &len, NULL); } if (len == (int)l) { /* Finished a line, add a NL, unless this line should not have * one. */ if (lnum != curbuf->b_op_end.lnum || !curbuf->b_p_bin || (lnum != curbuf->b_no_eol_lnum && (lnum != curbuf->b_ml.ml_line_count || curbuf->b_p_eol))) { WriteFile(g_hChildStd_IN_Wr, "\n", 1, &ignored, NULL); } ++lnum; if (lnum > curbuf->b_op_end.lnum) break; lp = ml_get(lnum); written = 0; } else if (len > 0) written += len; } /* finished all the lines, close pipe */ CloseHandle(g_hChildStd_IN_Wr); ExitThread(0); } # define BUFLEN 100 /* length for buffer, stolen from unix version */ /* * This function read from the children's stdout and write the * data on screen or in the buffer accordingly. */ static void dump_pipe(int options, HANDLE g_hChildStd_OUT_Rd, garray_T *ga, char_u buffer[], DWORD *buffer_off) { DWORD availableBytes = 0; DWORD i; int ret; DWORD len; DWORD toRead; int repeatCount; /* we query the pipe to see if there is any data to read * to avoid to perform a blocking read */ ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */ NULL, /* optional buffer */ 0, /* buffe size */ NULL, /* number of read bytes */ &availableBytes, /* available bytes total */ NULL); /* byteLeft */ repeatCount = 0; /* We got real data in the pipe, read it */ while (ret != 0 && availableBytes > 0 && availableBytes > 0) { repeatCount++; toRead = # ifdef FEAT_MBYTE (DWORD)(BUFLEN - *buffer_off); # else (DWORD)BUFLEN; # endif toRead = availableBytes < toRead ? availableBytes : toRead; ReadFile(g_hChildStd_OUT_Rd, buffer # ifdef FEAT_MBYTE + *buffer_off, toRead # else , toRead # endif , &len, NULL); /* If we haven't read anything, there is a problem */ if (len == 0) break; availableBytes -= len; if (options & SHELL_READ) { /* Do NUL -> NL translation, append NL separated * lines to the current buffer. */ for (i = 0; i < len; ++i) { if (buffer[i] == NL) append_ga_line(ga); else if (buffer[i] == NUL) ga_append(ga, NL); else ga_append(ga, buffer[i]); } } # ifdef FEAT_MBYTE else if (has_mbyte) { int l; int c; char_u *p; len += *buffer_off; buffer[len] = NUL; /* Check if the last character in buffer[] is * incomplete, keep these bytes for the next * round. */ for (p = buffer; p < buffer + len; p += l) { l = mb_cptr2len(p); if (l == 0) l = 1; /* NUL byte? */ else if (MB_BYTE2LEN(*p) != l) break; } if (p == buffer) /* no complete character */ { /* avoid getting stuck at an illegal byte */ if (len >= 12) ++p; else { *buffer_off = len; return; } } c = *p; *p = NUL; msg_puts(buffer); if (p < buffer + len) { *p = c; *buffer_off = (DWORD)((buffer + len) - p); mch_memmove(buffer, p, *buffer_off); return; } *buffer_off = 0; } # endif /* FEAT_MBYTE */ else { buffer[len] = NUL; msg_puts(buffer); } windgoto(msg_row, msg_col); cursor_on(); out_flush(); } } /* * Version of system to use for windows NT > 5.0 (Win2K), use pipe * for communication and doesn't open any new window. */ static int mch_system_piped(char *cmd, int options) { STARTUPINFO si; PROCESS_INFORMATION pi; DWORD ret = 0; HANDLE g_hChildStd_IN_Rd = NULL; HANDLE g_hChildStd_IN_Wr = NULL; HANDLE g_hChildStd_OUT_Rd = NULL; HANDLE g_hChildStd_OUT_Wr = NULL; char_u buffer[BUFLEN + 1]; /* reading buffer + size */ DWORD len; /* buffer used to receive keys */ char_u ta_buf[BUFLEN + 1]; /* TypeAHead */ int ta_len = 0; /* valid bytes in ta_buf[] */ DWORD i; int c; int noread_cnt = 0; garray_T ga; int delay = 1; DWORD buffer_off = 0; /* valid bytes in buffer[] */ char *p = NULL; SECURITY_ATTRIBUTES saAttr; /* Set the bInheritHandle flag so pipe handles are inherited. */ saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0) /* Ensure the read handle to the pipe for STDOUT is not inherited. */ || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0) /* Create a pipe for the child process's STDIN. */ || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0) /* Ensure the write handle to the pipe for STDIN is not inherited. */ || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) ) { CloseHandle(g_hChildStd_IN_Rd); CloseHandle(g_hChildStd_IN_Wr); CloseHandle(g_hChildStd_OUT_Rd); CloseHandle(g_hChildStd_OUT_Wr); MSG_PUTS(_("\nCannot create pipes\n")); } si.cb = sizeof(si); si.lpReserved = NULL; si.lpDesktop = NULL; si.lpTitle = NULL; si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; /* set-up our file redirection */ si.hStdError = g_hChildStd_OUT_Wr; si.hStdOutput = g_hChildStd_OUT_Wr; si.hStdInput = g_hChildStd_IN_Rd; si.wShowWindow = SW_HIDE; si.cbReserved2 = 0; si.lpReserved2 = NULL; if (options & SHELL_READ) ga_init2(&ga, 1, BUFLEN); if (cmd != NULL) { p = (char *)vim_strsave((char_u *)cmd); if (p != NULL) unescape_shellxquote((char_u *)p, p_sxe); else p = cmd; } /* Now, run the command */ CreateProcess(NULL, /* Executable name */ p, /* Command to execute */ NULL, /* Process security attributes */ NULL, /* Thread security attributes */ // this command can be litigeous, handle inheritence was // deactivated for pending temp file, but, if we deactivate // it, the pipes don't work for some reason. TRUE, /* Inherit handles, first deactivated, * but needed */ CREATE_DEFAULT_ERROR_MODE, /* Creation flags */ NULL, /* Environment */ NULL, /* Current directory */ &si, /* Startup information */ &pi); /* Process information */ if (p != cmd) vim_free(p); /* Close our unused side of the pipes */ CloseHandle(g_hChildStd_IN_Rd); CloseHandle(g_hChildStd_OUT_Wr); if (options & SHELL_WRITE) { HANDLE thread = CreateThread(NULL, /* security attributes */ 0, /* default stack size */ sub_process_writer, /* function to be executed */ g_hChildStd_IN_Wr, /* parameter */ 0, /* creation flag, start immediately */ NULL); /* we don't care about thread id */ CloseHandle(thread); g_hChildStd_IN_Wr = NULL; } /* Keep updating the window while waiting for the shell to finish. */ for (;;) { MSG msg; if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } /* write pipe information in the window */ if ((options & (SHELL_READ|SHELL_WRITE)) # ifdef FEAT_GUI || gui.in_use # endif ) { len = 0; if (!(options & SHELL_EXPAND) && ((options & (SHELL_READ|SHELL_WRITE|SHELL_COOKED)) != (SHELL_READ|SHELL_WRITE|SHELL_COOKED) # ifdef FEAT_GUI || gui.in_use # endif ) && (ta_len > 0 || noread_cnt > 4)) { if (ta_len == 0) { /* Get extra characters when we don't have any. Reset the * counter and timer. */ noread_cnt = 0; # if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H) gettimeofday(&start_tv, NULL); # endif len = ui_inchar(ta_buf, BUFLEN, 10L, 0); } if (ta_len > 0 || len > 0) { /* * For pipes: Check for CTRL-C: send interrupt signal to * child. Check for CTRL-D: EOF, close pipe to child. */ if (len == 1 && cmd != NULL) { if (ta_buf[ta_len] == Ctrl_C) { /* Learn what exit code is expected, for * now put 9 as SIGKILL */ TerminateProcess(pi.hProcess, 9); } if (ta_buf[ta_len] == Ctrl_D) { CloseHandle(g_hChildStd_IN_Wr); g_hChildStd_IN_Wr = NULL; } } /* replace K_BS by <BS> and K_DEL by <DEL> */ for (i = ta_len; i < ta_len + len; ++i) { if (ta_buf[i] == CSI && len - i > 2) { c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]); if (c == K_DEL || c == K_KDEL || c == K_BS) { mch_memmove(ta_buf + i + 1, ta_buf + i + 3, (size_t)(len - i - 2)); if (c == K_DEL || c == K_KDEL) ta_buf[i] = DEL; else ta_buf[i] = Ctrl_H; len -= 2; } } else if (ta_buf[i] == '\r') ta_buf[i] = '\n'; # ifdef FEAT_MBYTE if (has_mbyte) i += (*mb_ptr2len_len)(ta_buf + i, ta_len + len - i) - 1; # endif } /* * For pipes: echo the typed characters. For a pty this * does not seem to work. */ for (i = ta_len; i < ta_len + len; ++i) { if (ta_buf[i] == '\n' || ta_buf[i] == '\b') msg_putchar(ta_buf[i]); # ifdef FEAT_MBYTE else if (has_mbyte) { int l = (*mb_ptr2len)(ta_buf + i); msg_outtrans_len(ta_buf + i, l); i += l - 1; } # endif else msg_outtrans_len(ta_buf + i, 1); } windgoto(msg_row, msg_col); out_flush(); ta_len += len; /* * Write the characters to the child, unless EOF has been * typed for pipes. Write one character at a time, to * avoid losing too much typeahead. When writing buffer * lines, drop the typed characters (only check for * CTRL-C). */ if (options & SHELL_WRITE) ta_len = 0; else if (g_hChildStd_IN_Wr != NULL) { WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf, 1, &len, NULL); // if we are typing in, we want to keep things reactive delay = 1; if (len > 0) { ta_len -= len; mch_memmove(ta_buf, ta_buf + len, ta_len); } } } } } if (ta_len) ui_inchar_undo(ta_buf, ta_len); if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT) { dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off); break; } ++noread_cnt; dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off); /* We start waiting for a very short time and then increase it, so * that we respond quickly when the process is quick, and don't * consume too much overhead when it's slow. */ if (delay < 50) delay += 10; } /* Close the pipe */ CloseHandle(g_hChildStd_OUT_Rd); if (g_hChildStd_IN_Wr != NULL) CloseHandle(g_hChildStd_IN_Wr); WaitForSingleObject(pi.hProcess, INFINITE); /* Get the command exit code */ GetExitCodeProcess(pi.hProcess, &ret); if (options & SHELL_READ) { if (ga.ga_len > 0) { append_ga_line(&ga); /* remember that the NL was missing */ curbuf->b_no_eol_lnum = curwin->w_cursor.lnum; } else curbuf->b_no_eol_lnum = 0; ga_clear(&ga); } /* Close the handles to the subprocess, so that it goes away */ CloseHandle(pi.hThread); CloseHandle(pi.hProcess); return ret; } static int mch_system(char *cmd, int options) { /* if we can pipe and the shelltemp option is off */ if (allowPiping && !p_stmp) return mch_system_piped(cmd, options); else return mch_system_classic(cmd, options); } #else # define mch_system(c, o) system(c) #endif /* * Either execute a command by calling the shell or start a new shell */ int mch_call_shell( char_u *cmd, int options) /* SHELL_*, see vim.h */ { int x = 0; int tmode = cur_tmode; #ifdef FEAT_TITLE char szShellTitle[512]; /* Change the title to reflect that we are in a subshell. */ if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0) { if (cmd == NULL) strcat(szShellTitle, " :sh"); else { strcat(szShellTitle, " - !"); if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle))) strcat(szShellTitle, cmd); } mch_settitle(szShellTitle, NULL); } #endif out_flush(); #ifdef MCH_WRITE_DUMP if (fdDump) { fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options); fflush(fdDump); } #endif /* * Catch all deadly signals while running the external command, because a * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us. */ signal(SIGINT, SIG_IGN); #if defined(__GNUC__) && !defined(__MINGW32__) signal(SIGKILL, SIG_IGN); #else signal(SIGBREAK, SIG_IGN); #endif signal(SIGILL, SIG_IGN); signal(SIGFPE, SIG_IGN); signal(SIGSEGV, SIG_IGN); signal(SIGTERM, SIG_IGN); signal(SIGABRT, SIG_IGN); if (options & SHELL_COOKED) settmode(TMODE_COOK); /* set to normal mode */ if (cmd == NULL) { x = mch_system(p_sh, options); } else { /* we use "command" or "cmd" to start the shell; slow but easy */ char_u *newcmd = NULL; char_u *cmdbase = cmd; long_u cmdlen; /* Skip a leading ", ( and "(. */ if (*cmdbase == '"' ) ++cmdbase; if (*cmdbase == '(') ++cmdbase; if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5])) { STARTUPINFO si; PROCESS_INFORMATION pi; DWORD flags = CREATE_NEW_CONSOLE; char_u *p; si.cb = sizeof(si); si.lpReserved = NULL; si.lpDesktop = NULL; si.lpTitle = NULL; si.dwFlags = 0; si.cbReserved2 = 0; si.lpReserved2 = NULL; cmdbase = skipwhite(cmdbase + 5); if ((STRNICMP(cmdbase, "/min", 4) == 0) && vim_iswhite(cmdbase[4])) { cmdbase = skipwhite(cmdbase + 4); si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_SHOWMINNOACTIVE; } else if ((STRNICMP(cmdbase, "/b", 2) == 0) && vim_iswhite(cmdbase[2])) { cmdbase = skipwhite(cmdbase + 2); flags = CREATE_NO_WINDOW; si.dwFlags = STARTF_USESTDHANDLES; si.hStdInput = CreateFile("\\\\.\\NUL", // File name GENERIC_READ, // Access flags 0, // Share flags NULL, // Security att. OPEN_EXISTING, // Open flags FILE_ATTRIBUTE_NORMAL, // File att. NULL); // Temp file si.hStdOutput = si.hStdInput; si.hStdError = si.hStdInput; } /* Remove a trailing ", ) and )" if they have a match * at the start of the command. */ if (cmdbase > cmd) { p = cmdbase + STRLEN(cmdbase); if (p > cmdbase && p[-1] == '"' && *cmd == '"') *--p = NUL; if (p > cmdbase && p[-1] == ')' && (*cmd =='(' || cmd[1] == '(')) *--p = NUL; } newcmd = cmdbase; unescape_shellxquote(cmdbase, p_sxe); /* * If creating new console, arguments are passed to the * 'cmd.exe' as-is. If it's not, arguments are not treated * correctly for current 'cmd.exe'. So unescape characters in * shellxescape except '|' for avoiding to be treated as * argument to them. Pass the arguments to sub-shell. */ if (flags != CREATE_NEW_CONSOLE) { char_u *subcmd; char_u *cmd_shell = mch_getenv("COMSPEC"); if (cmd_shell == NULL || *cmd_shell == NUL) cmd_shell = default_shell(); subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE); if (subcmd != NULL) { /* make "cmd.exe /c arguments" */ cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5; newcmd = lalloc(cmdlen, TRUE); if (newcmd != NULL) vim_snprintf((char *)newcmd, cmdlen, "%s /c %s", cmd_shell, subcmd); else newcmd = cmdbase; vim_free(subcmd); } } /* * Now, start the command as a process, so that it doesn't * inherit our handles which causes unpleasant dangling swap * files if we exit before the spawned process */ if (CreateProcess(NULL, // Executable name newcmd, // Command to execute NULL, // Process security attributes NULL, // Thread security attributes FALSE, // Inherit handles flags, // Creation flags NULL, // Environment NULL, // Current directory &si, // Startup information &pi)) // Process information x = 0; else { x = -1; #ifdef FEAT_GUI_W32 EMSG(_("E371: Command not found")); #endif } if (newcmd != cmdbase) vim_free(newcmd); if (si.hStdInput != NULL) { /* Close the handle to \\.\NUL */ CloseHandle(si.hStdInput); } /* Close the handles to the subprocess, so that it goes away */ CloseHandle(pi.hThread); CloseHandle(pi.hProcess); } else { cmdlen = ( #ifdef FEAT_GUI_W32 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) + #endif STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10); newcmd = lalloc(cmdlen, TRUE); if (newcmd != NULL) { #if defined(FEAT_GUI_W32) if (need_vimrun_warning) { MessageBox(NULL, _("VIMRUN.EXE not found in your $PATH.\n" "External commands will not pause after completion.\n" "See :help win32-vimrun for more information."), _("Vim Warning"), MB_ICONWARNING); need_vimrun_warning = FALSE; } if (!s_dont_use_vimrun && (!allowPiping || p_stmp)) /* Use vimrun to execute the command. It opens a console * window, which can be closed without killing Vim. */ vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s", vimrun_path, (msg_silent != 0 || (options & SHELL_DOOUT)) ? "-s " : "", p_sh, p_shcf, cmd); else #endif vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd); x = mch_system((char *)newcmd, options); vim_free(newcmd); } } } if (tmode == TMODE_RAW) settmode(TMODE_RAW); /* set to raw mode */ /* Print the return value, unless "vimrun" was used. */ if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent #if defined(FEAT_GUI_W32) && ((options & SHELL_DOOUT) || s_dont_use_vimrun || (allowPiping && !p_stmp)) #endif ) { smsg(_("shell returned %d"), x); msg_putchar('\n'); } #ifdef FEAT_TITLE resettitle(); #endif signal(SIGINT, SIG_DFL); #if defined(__GNUC__) && !defined(__MINGW32__) signal(SIGKILL, SIG_DFL); #else signal(SIGBREAK, SIG_DFL); #endif signal(SIGILL, SIG_DFL); signal(SIGFPE, SIG_DFL); signal(SIGSEGV, SIG_DFL); signal(SIGTERM, SIG_DFL); signal(SIGABRT, SIG_DFL); return x; } #ifndef FEAT_GUI_W32 /* * Start termcap mode */ static void termcap_mode_start(void) { DWORD cmodein; if (g_fTermcapMode) return; SaveConsoleBuffer(&g_cbNonTermcap); if (g_cbTermcap.IsValid) { /* * We've been in termcap mode before. Restore certain screen * characteristics, including the buffer size and the window * size. Since we will be redrawing the screen, we don't need * to restore the actual contents of the buffer. */ RestoreConsoleBuffer(&g_cbTermcap, FALSE); SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow); Rows = g_cbTermcap.Info.dwSize.Y; Columns = g_cbTermcap.Info.dwSize.X; } else { /* * This is our first time entering termcap mode. Clear the console * screen buffer, and resize the buffer to match the current window * size. We will use this as the size of our editing environment. */ ClearConsoleBuffer(g_attrCurrent); ResizeConBufAndWindow(g_hConOut, Columns, Rows); } #ifdef FEAT_TITLE resettitle(); #endif GetConsoleMode(g_hConIn, &cmodein); #ifdef FEAT_MOUSE if (g_fMouseActive) cmodein |= ENABLE_MOUSE_INPUT; else cmodein &= ~ENABLE_MOUSE_INPUT; #endif cmodein |= ENABLE_WINDOW_INPUT; SetConsoleMode(g_hConIn, cmodein); redraw_later_clear(); g_fTermcapMode = TRUE; } /* * End termcap mode */ static void termcap_mode_end(void) { DWORD cmodein; ConsoleBuffer *cb; COORD coord; DWORD dwDummy; if (!g_fTermcapMode) return; SaveConsoleBuffer(&g_cbTermcap); GetConsoleMode(g_hConIn, &cmodein); cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT); SetConsoleMode(g_hConIn, cmodein); #ifdef FEAT_RESTORE_ORIG_SCREEN cb = exiting ? &g_cbOrig : &g_cbNonTermcap; #else cb = &g_cbNonTermcap; #endif RestoreConsoleBuffer(cb, p_rs); SetConsoleCursorInfo(g_hConOut, &g_cci); if (p_rs || exiting) { /* * Clear anything that happens to be on the current line. */ coord.X = 0; coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1)); FillConsoleOutputCharacter(g_hConOut, ' ', cb->Info.dwSize.X, coord, &dwDummy); /* * The following is just for aesthetics. If we are exiting without * restoring the screen, then we want to have a prompt string * appear at the bottom line. However, the command interpreter * seems to always advance the cursor one line before displaying * the prompt string, which causes the screen to scroll. To * counter this, move the cursor up one line before exiting. */ if (exiting && !p_rs) coord.Y--; /* * Position the cursor at the leftmost column of the desired row. */ SetConsoleCursorPosition(g_hConOut, coord); } g_fTermcapMode = FALSE; } #endif /* FEAT_GUI_W32 */ #ifdef FEAT_GUI_W32 /*ARGSUSED*/ void mch_write( char_u *s, int len) { /* never used */ } #else /* * clear `n' chars, starting from `coord' */ static void clear_chars( COORD coord, DWORD n) { DWORD dwDummy; FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy); FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy); } /* * Clear the screen */ static void clear_screen(void) { g_coord.X = g_coord.Y = 0; clear_chars(g_coord, Rows * Columns); } /* * Clear to end of display */ static void clear_to_end_of_display(void) { clear_chars(g_coord, (Rows - g_coord.Y - 1) * Columns + (Columns - g_coord.X)); } /* * Clear to end of line */ static void clear_to_end_of_line(void) { clear_chars(g_coord, Columns - g_coord.X); } /* * Scroll the scroll region up by `cLines' lines */ static void scroll(unsigned cLines) { COORD oldcoord = g_coord; gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1); delete_lines(cLines); g_coord = oldcoord; } /* * Set the scroll region */ static void set_scroll_region( unsigned left, unsigned top, unsigned right, unsigned bottom) { if (left >= right || top >= bottom || right > (unsigned) Columns - 1 || bottom > (unsigned) Rows - 1) return; g_srScrollRegion.Left = left; g_srScrollRegion.Top = top; g_srScrollRegion.Right = right; g_srScrollRegion.Bottom = bottom; } /* * Insert `cLines' lines at the current cursor position */ static void insert_lines(unsigned cLines) { SMALL_RECT source; COORD dest; CHAR_INFO fill; dest.X = 0; dest.Y = g_coord.Y + cLines; source.Left = 0; source.Top = g_coord.Y; source.Right = g_srScrollRegion.Right; source.Bottom = g_srScrollRegion.Bottom - cLines; fill.Char.AsciiChar = ' '; fill.Attributes = g_attrCurrent; ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill); /* Here we have to deal with a win32 console flake: If the scroll * region looks like abc and we scroll c to a and fill with d we get * cbd... if we scroll block c one line at a time to a, we get cdd... * vim expects cdd consistently... So we have to deal with that * here... (this also occurs scrolling the same way in the other * direction). */ if (source.Bottom < dest.Y) { COORD coord; coord.X = 0; coord.Y = source.Bottom; clear_chars(coord, Columns * (dest.Y - source.Bottom)); } } /* * Delete `cLines' lines at the current cursor position */ static void delete_lines(unsigned cLines) { SMALL_RECT source; COORD dest; CHAR_INFO fill; int nb; dest.X = 0; dest.Y = g_coord.Y; source.Left = 0; source.Top = g_coord.Y + cLines; source.Right = g_srScrollRegion.Right; source.Bottom = g_srScrollRegion.Bottom; fill.Char.AsciiChar = ' '; fill.Attributes = g_attrCurrent; ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill); /* Here we have to deal with a win32 console flake: If the scroll * region looks like abc and we scroll c to a and fill with d we get * cbd... if we scroll block c one line at a time to a, we get cdd... * vim expects cdd consistently... So we have to deal with that * here... (this also occurs scrolling the same way in the other * direction). */ nb = dest.Y + (source.Bottom - source.Top) + 1; if (nb < source.Top) { COORD coord; coord.X = 0; coord.Y = nb; clear_chars(coord, Columns * (source.Top - nb)); } } /* * Set the cursor position */ static void gotoxy( unsigned x, unsigned y) { if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows) return; /* external cursor coords are 1-based; internal are 0-based */ g_coord.X = x - 1; g_coord.Y = y - 1; SetConsoleCursorPosition(g_hConOut, g_coord); } /* * Set the current text attribute = (foreground | background) * See ../doc/os_win32.txt for the numbers. */ static void textattr(WORD wAttr) { g_attrCurrent = wAttr; SetConsoleTextAttribute(g_hConOut, wAttr); } static void textcolor(WORD wAttr) { g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr; SetConsoleTextAttribute(g_hConOut, g_attrCurrent); } static void textbackground(WORD wAttr) { g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4); SetConsoleTextAttribute(g_hConOut, g_attrCurrent); } /* * restore the default text attribute (whatever we started with) */ static void normvideo(void) { textattr(g_attrDefault); } static WORD g_attrPreStandout = 0; /* * Make the text standout, by brightening it */ static void standout(void) { g_attrPreStandout = g_attrCurrent; textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY)); } /* * Turn off standout mode */ static void standend(void) { if (g_attrPreStandout) { textattr(g_attrPreStandout); g_attrPreStandout = 0; } } /* * Set normal fg/bg color, based on T_ME. Called when t_me has been set. */ void mch_set_normal_colors(void) { char_u *p; int n; cterm_normal_fg_color = (g_attrDefault & 0xf) + 1; cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1; if (T_ME[0] == ESC && T_ME[1] == '|') { p = T_ME + 2; n = getdigits(&p); if (*p == 'm' && n > 0) { cterm_normal_fg_color = (n & 0xf) + 1; cterm_normal_bg_color = ((n >> 4) & 0xf) + 1; } } } /* * visual bell: flash the screen */ static void visual_bell(void) { COORD coordOrigin = {0, 0}; WORD attrFlash = ~g_attrCurrent & 0xff; DWORD dwDummy; LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD)); if (oldattrs == NULL) return; ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns, coordOrigin, &dwDummy); FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns, coordOrigin, &dwDummy); Sleep(15); /* wait for 15 msec */ WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns, coordOrigin, &dwDummy); vim_free(oldattrs); } /* * Make the cursor visible or invisible */ static void cursor_visible(BOOL fVisible) { s_cursor_visible = fVisible; #ifdef MCH_CURSOR_SHAPE mch_update_cursor(); #endif } /* * write `cchToWrite' characters in `pchBuf' to the screen * Returns the number of characters actually written (at least one). */ static BOOL write_chars( LPCSTR pchBuf, DWORD cchToWrite) { COORD coord = g_coord; DWORD written; FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite, coord, &written); /* When writing fails or didn't write a single character, pretend one * character was written, otherwise we get stuck. */ if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite, coord, &written) == 0 || written == 0) written = 1; g_coord.X += (SHORT) written; while (g_coord.X > g_srScrollRegion.Right) { g_coord.X -= (SHORT) Columns; if (g_coord.Y < g_srScrollRegion.Bottom) g_coord.Y++; } gotoxy(g_coord.X + 1, g_coord.Y + 1); return written; } /* * mch_write(): write the output buffer to the screen, translating ESC * sequences into calls to console output routines. */ void mch_write( char_u *s, int len) { s[len] = NUL; if (!term_console) { write(1, s, (unsigned)len); return; } /* translate ESC | sequences into faked bios calls */ while (len--) { /* optimization: use one single write_chars for runs of text, * rather than once per character It ain't curses, but it helps. */ DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033"); if (p_wd) { WaitForChar(p_wd); if (prefix != 0) prefix = 1; } if (prefix != 0) { DWORD nWritten; nWritten = write_chars(s, prefix); #ifdef MCH_WRITE_DUMP if (fdDump) { fputc('>', fdDump); fwrite(s, sizeof(char_u), nWritten, fdDump); fputs("<\n", fdDump); } #endif len -= (nWritten - 1); s += nWritten; } else if (s[0] == '\n') { /* \n, newline: go to the beginning of the next line or scroll */ if (g_coord.Y == g_srScrollRegion.Bottom) { scroll(1); gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1); } else { gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2); } #ifdef MCH_WRITE_DUMP if (fdDump) fputs("\\n\n", fdDump); #endif s++; } else if (s[0] == '\r') { /* \r, carriage return: go to beginning of line */ gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1); #ifdef MCH_WRITE_DUMP if (fdDump) fputs("\\r\n", fdDump); #endif s++; } else if (s[0] == '\b') { /* \b, backspace: move cursor one position left */ if (g_coord.X > g_srScrollRegion.Left) g_coord.X--; else if (g_coord.Y > g_srScrollRegion.Top) { g_coord.X = g_srScrollRegion.Right; g_coord.Y--; } gotoxy(g_coord.X + 1, g_coord.Y + 1); #ifdef MCH_WRITE_DUMP if (fdDump) fputs("\\b\n", fdDump); #endif s++; } else if (s[0] == '\a') { /* \a, bell */ MessageBeep(0xFFFFFFFF); #ifdef MCH_WRITE_DUMP if (fdDump) fputs("\\a\n", fdDump); #endif s++; } else if (s[0] == ESC && len >= 3-1 && s[1] == '|') { #ifdef MCH_WRITE_DUMP char_u *old_s = s; #endif char_u *p; int arg1 = 0, arg2 = 0; switch (s[2]) { /* one or two numeric arguments, separated by ';' */ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': p = s + 2; arg1 = getdigits(&p); /* no check for length! */ if (p > s + len) break; if (*p == ';') { ++p; arg2 = getdigits(&p); /* no check for length! */ if (p > s + len) break; if (*p == 'H') gotoxy(arg2, arg1); else if (*p == 'r') set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1); } else if (*p == 'A') { /* move cursor up arg1 lines in same column */ gotoxy(g_coord.X + 1, max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1); } else if (*p == 'C') { /* move cursor right arg1 columns in same line */ gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1, g_coord.Y + 1); } else if (*p == 'H') { gotoxy(1, arg1); } else if (*p == 'L') { insert_lines(arg1); } else if (*p == 'm') { if (arg1 == 0) normvideo(); else textattr((WORD) arg1); } else if (*p == 'f') { textcolor((WORD) arg1); } else if (*p == 'b') { textbackground((WORD) arg1); } else if (*p == 'M') { delete_lines(arg1); } len -= (int)(p - s); s = p + 1; break; /* Three-character escape sequences */ case 'A': /* move cursor up one line in same column */ gotoxy(g_coord.X + 1, max(g_srScrollRegion.Top, g_coord.Y - 1) + 1); goto got3; case 'B': visual_bell(); goto got3; case 'C': /* move cursor right one column in same line */ gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1, g_coord.Y + 1); goto got3; case 'E': termcap_mode_end(); goto got3; case 'F': standout(); goto got3; case 'f': standend(); goto got3; case 'H': gotoxy(1, 1); goto got3; case 'j': clear_to_end_of_display(); goto got3; case 'J': clear_screen(); goto got3; case 'K': clear_to_end_of_line(); goto got3; case 'L': insert_lines(1); goto got3; case 'M': delete_lines(1); goto got3; case 'S': termcap_mode_start(); goto got3; case 'V': cursor_visible(TRUE); goto got3; case 'v': cursor_visible(FALSE); goto got3; got3: s += 3; len -= 2; } #ifdef MCH_WRITE_DUMP if (fdDump) { fputs("ESC | ", fdDump); fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump); fputc('\n', fdDump); } #endif } else { /* Write a single character */ DWORD nWritten; nWritten = write_chars(s, 1); #ifdef MCH_WRITE_DUMP if (fdDump) { fputc('>', fdDump); fwrite(s, sizeof(char_u), nWritten, fdDump); fputs("<\n", fdDump); } #endif len -= (nWritten - 1); s += nWritten; } } #ifdef MCH_WRITE_DUMP if (fdDump) fflush(fdDump); #endif } #endif /* FEAT_GUI_W32 */ /* * Delay for half a second. */ /*ARGSUSED*/ void mch_delay( long msec, int ignoreinput) { #ifdef FEAT_GUI_W32 Sleep((int)msec); /* never wait for input */ #else /* Console */ if (ignoreinput) # ifdef FEAT_MZSCHEME if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq) { int towait = p_mzq; /* if msec is large enough, wait by portions in p_mzq */ while (msec > 0) { mzvim_check_threads(); if (msec < towait) towait = msec; Sleep(towait); msec -= towait; } } else # endif Sleep((int)msec); else WaitForChar(msec); #endif } /* * this version of remove is not scared by a readonly (backup) file * Return 0 for success, -1 for failure. */ int mch_remove(char_u *name) { #ifdef FEAT_MBYTE WCHAR *wn = NULL; int n; if (enc_codepage >= 0 && (int)GetACP() != enc_codepage) { wn = enc_to_utf16(name, NULL); if (wn != NULL) { SetFileAttributesW(wn, FILE_ATTRIBUTE_NORMAL); n = DeleteFileW(wn) ? 0 : -1; vim_free(wn); if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) return n; /* Retry with non-wide function (for Windows 98). */ } } #endif SetFileAttributes(name, FILE_ATTRIBUTE_NORMAL); return DeleteFile(name) ? 0 : -1; } /* * check for an "interrupt signal": CTRL-break or CTRL-C */ void mch_breakcheck(void) { #ifndef FEAT_GUI_W32 /* never used */ if (g_fCtrlCPressed || g_fCBrkPressed) { g_fCtrlCPressed = g_fCBrkPressed = FALSE; got_int = TRUE; } #endif } /* * How much memory is available? * Return sum of available physical and page file memory. */ /*ARGSUSED*/ long_u mch_avail_mem(int special) { MEMORYSTATUS ms; ms.dwLength = sizeof(MEMORYSTATUS); GlobalMemoryStatus(&ms); return (long_u) (ms.dwAvailPhys + ms.dwAvailPageFile); } #ifdef FEAT_MBYTE /* * Same code as below, but with wide functions and no comments. * Return 0 for success, non-zero for failure. */ int mch_wrename(WCHAR *wold, WCHAR *wnew) { WCHAR *p; int i; WCHAR szTempFile[_MAX_PATH + 1]; WCHAR szNewPath[_MAX_PATH + 1]; HANDLE hf; if (!mch_windows95()) { p = wold; for (i = 0; wold[i] != NUL; ++i) if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':') && wold[i + 1] != 0) p = wold + i + 1; if ((int)(wold + i - p) < 8 || p[6] != '~') return (MoveFileW(wold, wnew) == 0); } if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL) return -1; *p = NUL; if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0) return -2; if (!DeleteFileW(szTempFile)) return -3; if (!MoveFileW(wold, szTempFile)) return -4; if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) return -5; if (!CloseHandle(hf)) return -6; if (!MoveFileW(szTempFile, wnew)) { (void)MoveFileW(szTempFile, wold); return -7; } DeleteFileW(szTempFile); if (!DeleteFileW(wold)) return -8; return 0; } #endif /* * mch_rename() works around a bug in rename (aka MoveFile) in * Windows 95: rename("foo.bar", "foo.bar~") will generate a * file whose short file name is "FOO.BAR" (its long file name will * be correct: "foo.bar~"). Because a file can be accessed by * either its SFN or its LFN, "foo.bar" has effectively been * renamed to "foo.bar", which is not at all what was wanted. This * seems to happen only when renaming files with three-character * extensions by appending a suffix that does not include ".". * Windows NT gets it right, however, with an SFN of "FOO~1.BAR". * * There is another problem, which isn't really a bug but isn't right either: * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with * service pack 6. Doesn't seem to happen on Windows 98. * * Like rename(), returns 0 upon success, non-zero upon failure. * Should probably set errno appropriately when errors occur. */ int mch_rename( const char *pszOldFile, const char *pszNewFile) { char szTempFile[_MAX_PATH+1]; char szNewPath[_MAX_PATH+1]; char *pszFilePart; HANDLE hf; #ifdef FEAT_MBYTE WCHAR *wold = NULL; WCHAR *wnew = NULL; int retval = -1; if (enc_codepage >= 0 && (int)GetACP() != enc_codepage) { wold = enc_to_utf16((char_u *)pszOldFile, NULL); wnew = enc_to_utf16((char_u *)pszNewFile, NULL); if (wold != NULL && wnew != NULL) retval = mch_wrename(wold, wnew); vim_free(wold); vim_free(wnew); if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) return retval; /* Retry with non-wide function (for Windows 98). */ } #endif /* * No need to play tricks if not running Windows 95, unless the file name * contains a "~" as the seventh character. */ if (!mch_windows95()) { pszFilePart = (char *)gettail((char_u *)pszOldFile); if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~') return rename(pszOldFile, pszNewFile); } /* Get base path of new file name. Undocumented feature: If pszNewFile is * a directory, no error is returned and pszFilePart will be NULL. */ if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0 || pszFilePart == NULL) return -1; *pszFilePart = NUL; /* Get (and create) a unique temporary file name in directory of new file */ if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0) return -2; /* blow the temp file away */ if (!DeleteFile(szTempFile)) return -3; /* rename old file to the temp file */ if (!MoveFile(pszOldFile, szTempFile)) return -4; /* now create an empty file called pszOldFile; this prevents the operating * system using pszOldFile as an alias (SFN) if we're renaming within the * same directory. For example, we're editing a file called * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt * to filena~1.txt~ (i.e., we're making a backup while writing it), the * SFN for filena~1.txt~ will be filena~1.txt, by default, which will * cause all sorts of problems later in buf_write(). So, we create an * empty file called filena~1.txt and the system will have to find some * other SFN for filena~1.txt~, such as filena~2.txt */ if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) return -5; if (!CloseHandle(hf)) return -6; /* rename the temp file to the new file */ if (!MoveFile(szTempFile, pszNewFile)) { /* Renaming failed. Rename the file back to its old name, so that it * looks like nothing happened. */ (void)MoveFile(szTempFile, pszOldFile); return -7; } /* Seems to be left around on Novell filesystems */ DeleteFile(szTempFile); /* finally, remove the empty old file */ if (!DeleteFile(pszOldFile)) return -8; return 0; /* success */ } /* * Get the default shell for the current hardware platform */ char * default_shell(void) { char* psz = NULL; PlatformId(); if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */ psz = "cmd.exe"; else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */ psz = "command.com"; return psz; } /* * mch_access() extends access() to do more detailed check on network drives. * Returns 0 if file "n" has access rights according to "p", -1 otherwise. */ int mch_access(char *n, int p) { HANDLE hFile; DWORD am; int retval = -1; /* default: fail */ #ifdef FEAT_MBYTE WCHAR *wn = NULL; if (enc_codepage >= 0 && (int)GetACP() != enc_codepage) wn = enc_to_utf16(n, NULL); #endif if (mch_isdir(n)) { char TempName[_MAX_PATH + 16] = ""; #ifdef FEAT_MBYTE WCHAR TempNameW[_MAX_PATH + 16] = L""; #endif if (p & R_OK) { /* Read check is performed by seeing if we can do a find file on * the directory for any file. */ #ifdef FEAT_MBYTE if (wn != NULL) { int i; WIN32_FIND_DATAW d; for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i) TempNameW[i] = wn[i]; if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/') TempNameW[i++] = '\\'; TempNameW[i++] = '*'; TempNameW[i++] = 0; hFile = FindFirstFileW(TempNameW, &d); if (hFile == INVALID_HANDLE_VALUE) { if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) goto getout; /* Retry with non-wide function (for Windows 98). */ vim_free(wn); wn = NULL; } else (void)FindClose(hFile); } if (wn == NULL) #endif { char *pch; WIN32_FIND_DATA d; vim_strncpy(TempName, n, _MAX_PATH); pch = TempName + STRLEN(TempName) - 1; if (*pch != '\\' && *pch != '/') *++pch = '\\'; *++pch = '*'; *++pch = NUL; hFile = FindFirstFile(TempName, &d); if (hFile == INVALID_HANDLE_VALUE) goto getout; (void)FindClose(hFile); } } if (p & W_OK) { /* Trying to create a temporary file in the directory should catch * directories on read-only network shares. However, in * directories whose ACL allows writes but denies deletes will end * up keeping the temporary file :-(. */ #ifdef FEAT_MBYTE if (wn != NULL) { if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW)) { if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) goto getout; /* Retry with non-wide function (for Windows 98). */ vim_free(wn); wn = NULL; } else DeleteFileW(TempNameW); } if (wn == NULL) #endif { if (!GetTempFileName(n, "VIM", 0, TempName)) goto getout; mch_remove((char_u *)TempName); } } } else { /* Trying to open the file for the required access does ACL, read-only * network share, and file attribute checks. */ am = ((p & W_OK) ? GENERIC_WRITE : 0) | ((p & R_OK) ? GENERIC_READ : 0); #ifdef FEAT_MBYTE if (wn != NULL) { hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL); if (hFile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED) { /* Retry with non-wide function (for Windows 98). */ vim_free(wn); wn = NULL; } } if (wn == NULL) #endif hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL); if (hFile == INVALID_HANDLE_VALUE) goto getout; CloseHandle(hFile); } retval = 0; /* success */ getout: #ifdef FEAT_MBYTE vim_free(wn); #endif return retval; } #if defined(FEAT_MBYTE) || defined(PROTO) /* * Version of open() that may use UTF-16 file name. */ int mch_open(char *name, int flags, int mode) { /* _wopen() does not work with Borland C 5.5: creates a read-only file. */ # ifndef __BORLANDC__ WCHAR *wn; int f; if (enc_codepage >= 0 && (int)GetACP() != enc_codepage) { wn = enc_to_utf16(name, NULL); if (wn != NULL) { f = _wopen(wn, flags, mode); vim_free(wn); if (f >= 0) return f; /* Retry with non-wide function (for Windows 98). Can't use * GetLastError() here and it's unclear what errno gets set to if * the _wopen() fails for missing wide functions. */ } } # endif return open(name, flags, mode); } /* * Version of fopen() that may use UTF-16 file name. */ FILE * mch_fopen(char *name, char *mode) { WCHAR *wn, *wm; FILE *f = NULL; if (enc_codepage >= 0 && (int)GetACP() != enc_codepage # ifdef __BORLANDC__ /* Wide functions of Borland C 5.5 do not work on Windows 98. */ && g_PlatformId == VER_PLATFORM_WIN32_NT # endif ) { # if defined(DEBUG) && _MSC_VER >= 1400 /* Work around an annoying assertion in the Microsoft debug CRT * when mode's text/binary setting doesn't match _get_fmode(). */ char newMode = mode[strlen(mode) - 1]; int oldMode = 0; _get_fmode(&oldMode); if (newMode == 't') _set_fmode(_O_TEXT); else if (newMode == 'b') _set_fmode(_O_BINARY); # endif wn = enc_to_utf16(name, NULL); wm = enc_to_utf16(mode, NULL); if (wn != NULL && wm != NULL) f = _wfopen(wn, wm); vim_free(wn); vim_free(wm); # if defined(DEBUG) && _MSC_VER >= 1400 _set_fmode(oldMode); # endif if (f != NULL) return f; /* Retry with non-wide function (for Windows 98). Can't use * GetLastError() here and it's unclear what errno gets set to if * the _wfopen() fails for missing wide functions. */ } return fopen(name, mode); } #endif #ifdef FEAT_MBYTE /* * SUB STREAM (aka info stream) handling: * * NTFS can have sub streams for each file. Normal contents of file is * stored in the main stream, and extra contents (author information and * title and so on) can be stored in sub stream. After Windows 2000, user * can access and store those informations in sub streams via explorer's * property menuitem in right click menu. Those informations in sub streams * were lost when copying only the main stream. So we have to copy sub * streams. * * Incomplete explanation: * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp * More useful info and an example: * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams */ /* * Copy info stream data "substream". Read from the file with BackupRead(sh) * and write to stream "substream" of file "to". * Errors are ignored. */ static void copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len) { HANDLE hTo; WCHAR *to_name; to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR)); wcscpy(to_name, to); wcscat(to_name, substream); hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hTo != INVALID_HANDLE_VALUE) { long done; DWORD todo; DWORD readcnt, written; char buf[4096]; /* Copy block of bytes at a time. Abort when something goes wrong. */ for (done = 0; done < len; done += written) { /* (size_t) cast for Borland C 5.5 */ todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf) : (size_t)(len - done)); if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt, FALSE, FALSE, context) || readcnt != todo || !WriteFile(hTo, buf, todo, &written, NULL) || written != todo) break; } CloseHandle(hTo); } free(to_name); } /* * Copy info streams from file "from" to file "to". */ static void copy_infostreams(char_u *from, char_u *to) { WCHAR *fromw; WCHAR *tow; HANDLE sh; WIN32_STREAM_ID sid; int headersize; WCHAR streamname[_MAX_PATH]; DWORD readcount; void *context = NULL; DWORD lo, hi; int len; /* Convert the file names to wide characters. */ fromw = enc_to_utf16(from, NULL); tow = enc_to_utf16(to, NULL); if (fromw != NULL && tow != NULL) { /* Open the file for reading. */ sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); if (sh != INVALID_HANDLE_VALUE) { /* Use BackupRead() to find the info streams. Repeat until we * have done them all.*/ for (;;) { /* Get the header to find the length of the stream name. If * the "readcount" is zero we have done all info streams. */ ZeroMemory(&sid, sizeof(WIN32_STREAM_ID)); headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId); if (!BackupRead(sh, (LPBYTE)&sid, headersize, &readcount, FALSE, FALSE, &context) || readcount == 0) break; /* We only deal with streams that have a name. The normal * file data appears to be without a name, even though docs * suggest it is called "::$DATA". */ if (sid.dwStreamNameSize > 0) { /* Read the stream name. */ if (!BackupRead(sh, (LPBYTE)streamname, sid.dwStreamNameSize, &readcount, FALSE, FALSE, &context)) break; /* Copy an info stream with a name ":anything:$DATA". * Skip "::$DATA", it has no stream name (examples suggest * it might be used for the normal file contents). * Note that BackupRead() counts bytes, but the name is in * wide characters. */ len = readcount / sizeof(WCHAR); streamname[len] = 0; if (len > 7 && wcsicmp(streamname + len - 6, L":$DATA") == 0) { streamname[len - 6] = 0; copy_substream(sh, &context, tow, streamname, (long)sid.Size.u.LowPart); } } /* Advance to the next stream. We might try seeking too far, * but BackupSeek() doesn't skip over stream borders, thus * that's OK. */ (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart, &lo, &hi, &context); } /* Clear the context. */ (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context); CloseHandle(sh); } } vim_free(fromw); vim_free(tow); } #endif /* * Copy file attributes from file "from" to file "to". * For Windows NT and later we copy info streams. * Always returns zero, errors are ignored. */ int mch_copy_file_attribute(char_u *from, char_u *to) { #ifdef FEAT_MBYTE /* File streams only work on Windows NT and later. */ PlatformId(); if (g_PlatformId == VER_PLATFORM_WIN32_NT) copy_infostreams(from, to); #endif return 0; } #if defined(MYRESETSTKOFLW) || defined(PROTO) /* * Recreate a destroyed stack guard page in win32. * Written by Benjamin Peterson. */ /* These magic numbers are from the MS header files */ #define MIN_STACK_WIN9X 17 #define MIN_STACK_WINNT 2 /* * This function does the same thing as _resetstkoflw(), which is only * available in DevStudio .net and later. * Returns 0 for failure, 1 for success. */ int myresetstkoflw(void) { BYTE *pStackPtr; BYTE *pGuardPage; BYTE *pStackBase; BYTE *pLowestPossiblePage; MEMORY_BASIC_INFORMATION mbi; SYSTEM_INFO si; DWORD nPageSize; DWORD dummy; /* This code will not work on win32s. */ PlatformId(); if (g_PlatformId == VER_PLATFORM_WIN32s) return 0; /* We need to know the system page size. */ GetSystemInfo(&si); nPageSize = si.dwPageSize; /* ...and the current stack pointer */ pStackPtr = (BYTE*)_alloca(1); /* ...and the base of the stack. */ if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0) return 0; pStackBase = (BYTE*)mbi.AllocationBase; /* ...and the page thats min_stack_req pages away from stack base; this is * the lowest page we could use. */ pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT) ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize; /* On Win95, we want the next page down from the end of the stack. */ if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) { /* Find the page that's only 1 page down from the page that the stack * ptr is in. */ pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr / (DWORD)nPageSize) - 1)); if (pGuardPage < pLowestPossiblePage) return 0; /* Apply the noaccess attribute to the page -- there's no guard * attribute in win95-type OSes. */ if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy)) return 0; } else { /* On NT, however, we want the first committed page in the stack Start * at the stack base and move forward through memory until we find a * committed block. */ BYTE *pBlock = pStackBase; for (;;) { if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0) return 0; pBlock += mbi.RegionSize; if (mbi.State & MEM_COMMIT) break; } /* mbi now describes the first committed block in the stack. */ if (mbi.Protect & PAGE_GUARD) return 1; /* decide where the guard page should start */ if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage) pGuardPage = pLowestPossiblePage; else pGuardPage = (BYTE*)mbi.BaseAddress; /* allocate the guard page */ if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE)) return 0; /* apply the guard attribute to the page */ if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD, &dummy)) return 0; } return 1; } #endif #if defined(FEAT_MBYTE) || defined(PROTO) /* * The command line arguments in UCS2 */ static int nArgsW = 0; static LPWSTR *ArglistW = NULL; static int global_argc = 0; static char **global_argv; static int used_file_argc = 0; /* last argument in global_argv[] used for the argument list. */ static int *used_file_indexes = NULL; /* indexes in global_argv[] for command line arguments added to the argument list */ static int used_file_count = 0; /* nr of entries in used_file_indexes */ static int used_file_literal = FALSE; /* take file names literally */ static int used_file_full_path = FALSE; /* file name was full path */ static int used_file_diff_mode = FALSE; /* file name was with diff mode */ static int used_alist_count = 0; /* * Get the command line arguments. Unicode version. * Returns argc. Zero when something fails. */ int get_cmd_argsW(char ***argvp) { char **argv = NULL; int argc = 0; int i; ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW); if (ArglistW != NULL) { argv = malloc((nArgsW + 1) * sizeof(char *)); if (argv != NULL) { argc = nArgsW; argv[argc] = NULL; for (i = 0; i < argc; ++i) { int len; /* Convert each Unicode argument to the current codepage. */ WideCharToMultiByte_alloc(GetACP(), 0, ArglistW[i], (int)wcslen(ArglistW[i]) + 1, (LPSTR *)&argv[i], &len, 0, 0); if (argv[i] == NULL) { /* Out of memory, clear everything. */ while (i > 0) free(argv[--i]); free(argv); argc = 0; } } } } global_argc = argc; global_argv = argv; if (argc > 0) used_file_indexes = malloc(argc * sizeof(int)); if (argvp != NULL) *argvp = argv; return argc; } void free_cmd_argsW(void) { if (ArglistW != NULL) { GlobalFree(ArglistW); ArglistW = NULL; } } /* * Remember "name" is an argument that was added to the argument list. * This avoids that we have to re-parse the argument list when fix_arg_enc() * is called. */ void used_file_arg(char *name, int literal, int full_path, int diff_mode) { int i; if (used_file_indexes == NULL) return; for (i = used_file_argc + 1; i < global_argc; ++i) if (STRCMP(global_argv[i], name) == 0) { used_file_argc = i; used_file_indexes[used_file_count++] = i; break; } used_file_literal = literal; used_file_full_path = full_path; used_file_diff_mode = diff_mode; } /* * Remember the length of the argument list as it was. If it changes then we * leave it alone when 'encoding' is set. */ void set_alist_count(void) { used_alist_count = GARGCOUNT; } /* * Fix the encoding of the command line arguments. Invoked when 'encoding' * has been changed while starting up. Use the UCS-2 command line arguments * and convert them to 'encoding'. */ void fix_arg_enc(void) { int i; int idx; char_u *str; int *fnum_list; /* Safety checks: * - if argument count differs between the wide and non-wide argument * list, something must be wrong. * - the file name arguments must have been located. * - the length of the argument list wasn't changed by the user. */ if (global_argc != nArgsW || ArglistW == NULL || used_file_indexes == NULL || used_file_count == 0 || used_alist_count != GARGCOUNT) return; /* Remember the buffer numbers for the arguments. */ fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT); if (fnum_list == NULL) return; /* out of memory */ for (i = 0; i < GARGCOUNT; ++i) fnum_list[i] = GARGLIST[i].ae_fnum; /* Clear the argument list. Make room for the new arguments. */ alist_clear(&global_alist); if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL) return; /* out of memory */ for (i = 0; i < used_file_count; ++i) { idx = used_file_indexes[i]; str = utf16_to_enc(ArglistW[idx], NULL); if (str != NULL) { #ifdef FEAT_DIFF /* When using diff mode may need to concatenate file name to * directory name. Just like it's done in main(). */ if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0 && !mch_isdir(alist_name(&GARGLIST[0]))) { char_u *r; r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE); if (r != NULL) { vim_free(str); str = r; } } #endif /* Re-use the old buffer by renaming it. When not using literal * names it's done by alist_expand() below. */ if (used_file_literal) buf_set_name(fnum_list[i], str); alist_add(&global_alist, str, used_file_literal ? 2 : 0); } } if (!used_file_literal) { /* Now expand wildcards in the arguments. */ /* Temporarily add '(' and ')' to 'isfname'. These are valid * filename characters but are excluded from 'isfname' to make * "gf" work on a file name in parenthesis (e.g.: see vim.h). */ do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)"); alist_expand(fnum_list, used_alist_count); do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF"); } /* If wildcard expansion failed, we are editing the first file of the * arglist and there is no file name: Edit the first argument now. */ if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL) { do_cmdline_cmd((char_u *)":rewind"); if (GARGCOUNT == 1 && used_file_full_path) (void)vim_chdirfile(alist_name(&GARGLIST[0])); } set_alist_count(); } #endif
zyz2011-vim
src/os_win32.c
C
gpl2
144,236
/* vi:set ts=8 sts=4 sw=4: * * MzScheme interface by Sergey Khorev <sergey.khorev@gmail.com> * Original work by Brent Fulgham <bfulgham@debian.org> * (Based on lots of help from Matthew Flatt) * * TODO Convert byte-strings to char strings? * * This consists of six parts: * 1. MzScheme interpreter main program * 2. Routines that handle the external interface between MzScheme and * Vim. * 3. MzScheme input/output handlers: writes output via [e]msg(). * 4. Implementation of the Vim Features for MzScheme * 5. Vim Window-related Manipulation Functions. * 6. Vim Buffer-related Manipulation Functions * * NOTES * 1. Memory, allocated with scheme_malloc*, need not to be freed explicitly, * garbage collector will do it self * 2. Requires at least NORMAL features. I can't imagine why one may want * to build with SMALL or TINY features but with MzScheme interface. * 3. I don't use K&R-style functions. Anyways, MzScheme headers are ANSI. */ #include "vim.h" #include "if_mzsch.h" /* Only do the following when the feature is enabled. Needed for "make * depend". */ #if defined(FEAT_MZSCHEME) || defined(PROTO) /* Base data structures */ #define SCHEME_VIMBUFFERP(obj) SAME_TYPE(SCHEME_TYPE(obj), mz_buffer_type) #define SCHEME_VIMWINDOWP(obj) SAME_TYPE(SCHEME_TYPE(obj), mz_window_type) typedef struct { Scheme_Object so; buf_T *buf; } vim_mz_buffer; #define INVALID_BUFFER_VALUE ((buf_T *)(-1)) typedef struct { Scheme_Object so; win_T *win; } vim_mz_window; #define INVALID_WINDOW_VALUE ((win_T *)(-1)) /* * Prims that form MzScheme Vim interface */ typedef struct { Scheme_Closed_Prim *prim; char *name; int mina; /* arity information */ int maxa; } Vim_Prim; typedef struct { char *name; Scheme_Object *port; } Port_Info; /* *======================================================================== * Vim-Control Commands *======================================================================== */ /* *======================================================================== * Utility functions for the vim/mzscheme interface *======================================================================== */ #ifdef HAVE_SANDBOX static Scheme_Object *sandbox_file_guard(int, Scheme_Object **); static Scheme_Object *sandbox_network_guard(int, Scheme_Object **); static void sandbox_check(void); #endif /* Buffer-related commands */ static Scheme_Object *buffer_new(buf_T *buf); static Scheme_Object *get_buffer_by_name(void *, int, Scheme_Object **); static Scheme_Object *get_buffer_by_num(void *, int, Scheme_Object **); static Scheme_Object *get_buffer_count(void *, int, Scheme_Object **); static Scheme_Object *get_buffer_line(void *, int, Scheme_Object **); static Scheme_Object *get_buffer_line_list(void *, int, Scheme_Object **); static Scheme_Object *get_buffer_name(void *, int, Scheme_Object **); static Scheme_Object *get_buffer_num(void *, int, Scheme_Object **); static Scheme_Object *get_buffer_size(void *, int, Scheme_Object **); static Scheme_Object *get_curr_buffer(void *, int, Scheme_Object **); static Scheme_Object *get_next_buffer(void *, int, Scheme_Object **); static Scheme_Object *get_prev_buffer(void *, int, Scheme_Object **); static Scheme_Object *mzscheme_open_buffer(void *, int, Scheme_Object **); static Scheme_Object *set_buffer_line(void *, int, Scheme_Object **); static Scheme_Object *set_buffer_line_list(void *, int, Scheme_Object **); static Scheme_Object *insert_buffer_line_list(void *, int, Scheme_Object **); static Scheme_Object *get_range_start(void *, int, Scheme_Object **); static Scheme_Object *get_range_end(void *, int, Scheme_Object **); static vim_mz_buffer *get_vim_curr_buffer(void); /* Window-related commands */ static Scheme_Object *window_new(win_T *win); static Scheme_Object *get_curr_win(void *, int, Scheme_Object **); static Scheme_Object *get_window_count(void *, int, Scheme_Object **); static Scheme_Object *get_window_by_num(void *, int, Scheme_Object **); static Scheme_Object *get_window_num(void *, int, Scheme_Object **); static Scheme_Object *get_window_buffer(void *, int, Scheme_Object **); static Scheme_Object *get_window_height(void *, int, Scheme_Object **); static Scheme_Object *set_window_height(void *, int, Scheme_Object **); #ifdef FEAT_VERTSPLIT static Scheme_Object *get_window_width(void *, int, Scheme_Object **); static Scheme_Object *set_window_width(void *, int, Scheme_Object **); #endif static Scheme_Object *get_cursor(void *, int, Scheme_Object **); static Scheme_Object *set_cursor(void *, int, Scheme_Object **); static Scheme_Object *get_window_list(void *, int, Scheme_Object **); static vim_mz_window *get_vim_curr_window(void); /* Vim-related commands */ static Scheme_Object *mzscheme_beep(void *, int, Scheme_Object **); static Scheme_Object *get_option(void *, int, Scheme_Object **); static Scheme_Object *set_option(void *, int, Scheme_Object **); static Scheme_Object *vim_command(void *, int, Scheme_Object **); static Scheme_Object *vim_eval(void *, int, Scheme_Object **); static Scheme_Object *vim_bufferp(void *data, int, Scheme_Object **); static Scheme_Object *vim_windowp(void *data, int, Scheme_Object **); static Scheme_Object *vim_buffer_validp(void *data, int, Scheme_Object **); static Scheme_Object *vim_window_validp(void *data, int, Scheme_Object **); /* *======================================================================== * Internal Function Prototypes *======================================================================== */ static int vim_error_check(void); static int do_mzscheme_command(exarg_T *, void *, Scheme_Closed_Prim *what); static void startup_mzscheme(void); static char *string_to_line(Scheme_Object *obj); static void do_output(char *mesg, long len); static void do_printf(char *format, ...); static void do_flush(void); static Scheme_Object *_apply_thunk_catch_exceptions( Scheme_Object *, Scheme_Object **); static Scheme_Object *extract_exn_message(Scheme_Object *v); static Scheme_Object *do_eval(void *, int noargc, Scheme_Object **noargv); static Scheme_Object *do_load(void *, int noargc, Scheme_Object **noargv); static void register_vim_exn(void); static vim_mz_buffer *get_buffer_arg(const char *fname, int argnum, int argc, Scheme_Object **argv); static vim_mz_window *get_window_arg(const char *fname, int argnum, int argc, Scheme_Object **argv); static int line_in_range(linenr_T, buf_T *); static void check_line_range(linenr_T, buf_T *); static void mz_fix_cursor(int lo, int hi, int extra); static int eval_with_exn_handling(void *, Scheme_Closed_Prim *, Scheme_Object **ret); static void make_modules(void); static void init_exn_catching_apply(void); static int mzscheme_env_main(Scheme_Env *env, int argc, char **argv); static int mzscheme_init(void); #ifdef FEAT_EVAL static Scheme_Object *vim_to_mzscheme(typval_T *vim_value, int depth, Scheme_Hash_Table *visited); static int mzscheme_to_vim(Scheme_Object *obj, typval_T *tv, int depth, Scheme_Hash_Table *visited); #endif #ifdef MZ_PRECISE_GC static int buffer_size_proc(void *obj UNUSED) { return gcBYTES_TO_WORDS(sizeof(vim_mz_buffer)); } static int buffer_mark_proc(void *obj) { return buffer_size_proc(obj); } static int buffer_fixup_proc(void *obj) { return buffer_size_proc(obj); } static int window_size_proc(void *obj UNUSED) { return gcBYTES_TO_WORDS(sizeof(vim_mz_window)); } static int window_mark_proc(void *obj) { return window_size_proc(obj); } static int window_fixup_proc(void *obj) { return window_size_proc(obj); } #endif #ifdef DYNAMIC_MZSCHEME static Scheme_Object *dll_scheme_eof; static Scheme_Object *dll_scheme_false; static Scheme_Object *dll_scheme_void; static Scheme_Object *dll_scheme_null; static Scheme_Object *dll_scheme_true; static Scheme_Thread **dll_scheme_current_thread_ptr; static void (**dll_scheme_console_printf_ptr)(char *str, ...); static void (**dll_scheme_console_output_ptr)(char *str, long len); static void (**dll_scheme_notify_multithread_ptr)(int on); static void *(*dll_GC_malloc)(size_t size_in_bytes); static void *(*dll_GC_malloc_atomic)(size_t size_in_bytes); static Scheme_Env *(*dll_scheme_basic_env)(void); static void (*dll_scheme_check_threads)(void); static void (*dll_scheme_register_static)(void *ptr, long size); static void (*dll_scheme_set_stack_base)(void *base, int no_auto_statics); static void (*dll_scheme_add_global)(const char *name, Scheme_Object *val, Scheme_Env *env); static void (*dll_scheme_add_global_symbol)(Scheme_Object *name, Scheme_Object *val, Scheme_Env *env); static Scheme_Object *(*dll_scheme_apply)(Scheme_Object *rator, int num_rands, Scheme_Object **rands); static Scheme_Object *(*dll_scheme_builtin_value)(const char *name); # if MZSCHEME_VERSION_MAJOR >= 299 static Scheme_Object *(*dll_scheme_byte_string_to_char_string)(Scheme_Object *s); # endif static void (*dll_scheme_close_input_port)(Scheme_Object *port); static void (*dll_scheme_count_lines)(Scheme_Object *port); #if MZSCHEME_VERSION_MAJOR < 360 static Scheme_Object *(*dll_scheme_current_continuation_marks)(void); #else static Scheme_Object *(*dll_scheme_current_continuation_marks)(Scheme_Object *prompt_tag); #endif static void (*dll_scheme_display)(Scheme_Object *obj, Scheme_Object *port); static char *(*dll_scheme_display_to_string)(Scheme_Object *obj, long *len); static int (*dll_scheme_eq)(Scheme_Object *obj1, Scheme_Object *obj2); static Scheme_Object *(*dll_scheme_do_eval)(Scheme_Object *obj, int _num_rands, Scheme_Object **rands, int val); static void (*dll_scheme_dont_gc_ptr)(void *p); static Scheme_Object *(*dll_scheme_eval)(Scheme_Object *obj, Scheme_Env *env); static Scheme_Object *(*dll_scheme_eval_string)(const char *str, Scheme_Env *env); static Scheme_Object *(*dll_scheme_eval_string_all)(const char *str, Scheme_Env *env, int all); static void (*dll_scheme_finish_primitive_module)(Scheme_Env *env); # if MZSCHEME_VERSION_MAJOR < 299 static char *(*dll_scheme_format)(char *format, int flen, int argc, Scheme_Object **argv, long *rlen); # else static char *(*dll_scheme_format_utf8)(char *format, int flen, int argc, Scheme_Object **argv, long *rlen); static Scheme_Object *(*dll_scheme_get_param)(Scheme_Config *c, int pos); # endif static void (*dll_scheme_gc_ptr_ok)(void *p); # if MZSCHEME_VERSION_MAJOR < 299 static char *(*dll_scheme_get_sized_string_output)(Scheme_Object *, long *len); # else static char *(*dll_scheme_get_sized_byte_string_output)(Scheme_Object *, long *len); # endif static Scheme_Object *(*dll_scheme_intern_symbol)(const char *name); static Scheme_Object *(*dll_scheme_lookup_global)(Scheme_Object *symbol, Scheme_Env *env); static Scheme_Object *(*dll_scheme_make_closed_prim_w_arity) (Scheme_Closed_Prim *prim, void *data, const char *name, mzshort mina, mzshort maxa); static Scheme_Object *(*dll_scheme_make_integer_value)(long i); static Scheme_Object *(*dll_scheme_make_pair)(Scheme_Object *car, Scheme_Object *cdr); static Scheme_Object *(*dll_scheme_make_prim_w_arity)(Scheme_Prim *prim, const char *name, mzshort mina, mzshort maxa); # if MZSCHEME_VERSION_MAJOR < 299 static Scheme_Object *(*dll_scheme_make_string)(const char *chars); static Scheme_Object *(*dll_scheme_make_string_output_port)(); # else static Scheme_Object *(*dll_scheme_make_byte_string)(const char *chars); static Scheme_Object *(*dll_scheme_make_byte_string_output_port)(); # endif static Scheme_Object *(*dll_scheme_make_struct_instance)(Scheme_Object *stype, int argc, Scheme_Object **argv); static Scheme_Object **(*dll_scheme_make_struct_names)(Scheme_Object *base, Scheme_Object *field_names, int flags, int *count_out); static Scheme_Object *(*dll_scheme_make_struct_type)(Scheme_Object *base, Scheme_Object *parent, Scheme_Object *inspector, int num_fields, int num_uninit_fields, Scheme_Object *uninit_val, Scheme_Object *properties # if MZSCHEME_VERSION_MAJOR >= 299 , Scheme_Object *guard # endif ); static Scheme_Object **(*dll_scheme_make_struct_values)( Scheme_Object *struct_type, Scheme_Object **names, int count, int flags); static Scheme_Type (*dll_scheme_make_type)(const char *name); static Scheme_Object *(*dll_scheme_make_vector)(int size, Scheme_Object *fill); static void *(*dll_scheme_malloc_fail_ok)(void *(*f)(size_t), size_t); static Scheme_Object *(*dll_scheme_open_input_file)(const char *name, const char *who); static Scheme_Env *(*dll_scheme_primitive_module)(Scheme_Object *name, Scheme_Env *for_env); static int (*dll_scheme_proper_list_length)(Scheme_Object *list); static void (*dll_scheme_raise)(Scheme_Object *exn); static Scheme_Object *(*dll_scheme_read)(Scheme_Object *port); static void (*dll_scheme_signal_error)(const char *msg, ...); static void (*dll_scheme_wrong_type)(const char *name, const char *expected, int which, int argc, Scheme_Object **argv); # if MZSCHEME_VERSION_MAJOR >= 299 static void (*dll_scheme_set_param)(Scheme_Config *c, int pos, Scheme_Object *o); static Scheme_Config *(*dll_scheme_current_config)(void); static Scheme_Object *(*dll_scheme_char_string_to_byte_string) (Scheme_Object *s); static Scheme_Object *(*dll_scheme_char_string_to_path) (Scheme_Object *s); # endif static Scheme_Hash_Table *(*dll_scheme_make_hash_table)(int type); static void (*dll_scheme_hash_set)(Scheme_Hash_Table *table, Scheme_Object *key, Scheme_Object *value); static Scheme_Object *(*dll_scheme_hash_get)(Scheme_Hash_Table *table, Scheme_Object *key); static Scheme_Object *(*dll_scheme_make_double)(double d); # ifdef INCLUDE_MZSCHEME_BASE static Scheme_Object *(*dll_scheme_make_sized_byte_string)(char *chars, long len, int copy); static Scheme_Object *(*dll_scheme_namespace_require)(Scheme_Object *req); # endif /* arrays are imported directly */ # define scheme_eof dll_scheme_eof # define scheme_false dll_scheme_false # define scheme_void dll_scheme_void # define scheme_null dll_scheme_null # define scheme_true dll_scheme_true /* pointers are GetProceAddress'ed as pointers to pointer */ # define scheme_current_thread (*dll_scheme_current_thread_ptr) # define scheme_console_printf (*dll_scheme_console_printf_ptr) # define scheme_console_output (*dll_scheme_console_output_ptr) # define scheme_notify_multithread (*dll_scheme_notify_multithread_ptr) /* and functions in a usual way */ # define GC_malloc dll_GC_malloc # define GC_malloc_atomic dll_GC_malloc_atomic # define scheme_add_global dll_scheme_add_global # define scheme_add_global_symbol dll_scheme_add_global_symbol # define scheme_apply dll_scheme_apply # define scheme_basic_env dll_scheme_basic_env # define scheme_builtin_value dll_scheme_builtin_value # if MZSCHEME_VERSION_MAJOR >= 299 # define scheme_byte_string_to_char_string dll_scheme_byte_string_to_char_string # endif # define scheme_check_threads dll_scheme_check_threads # define scheme_close_input_port dll_scheme_close_input_port # define scheme_count_lines dll_scheme_count_lines # define scheme_current_continuation_marks \ dll_scheme_current_continuation_marks # define scheme_display dll_scheme_display # define scheme_display_to_string dll_scheme_display_to_string # define scheme_do_eval dll_scheme_do_eval # define scheme_dont_gc_ptr dll_scheme_dont_gc_ptr # define scheme_eq dll_scheme_eq # define scheme_eval dll_scheme_eval # define scheme_eval_string dll_scheme_eval_string # define scheme_eval_string_all dll_scheme_eval_string_all # define scheme_finish_primitive_module dll_scheme_finish_primitive_module # if MZSCHEME_VERSION_MAJOR < 299 # define scheme_format dll_scheme_format # else # define scheme_format_utf8 dll_scheme_format_utf8 # endif # define scheme_gc_ptr_ok dll_scheme_gc_ptr_ok # if MZSCHEME_VERSION_MAJOR < 299 # define scheme_get_sized_string_output dll_scheme_get_sized_string_output # else # define scheme_get_sized_byte_string_output \ dll_scheme_get_sized_byte_string_output # define scheme_get_param dll_scheme_get_param # endif # define scheme_intern_symbol dll_scheme_intern_symbol # define scheme_lookup_global dll_scheme_lookup_global # define scheme_make_closed_prim_w_arity dll_scheme_make_closed_prim_w_arity # define scheme_make_integer_value dll_scheme_make_integer_value # define scheme_make_pair dll_scheme_make_pair # define scheme_make_prim_w_arity dll_scheme_make_prim_w_arity # if MZSCHEME_VERSION_MAJOR < 299 # define scheme_make_string dll_scheme_make_string # define scheme_make_string_output_port dll_scheme_make_string_output_port # else # define scheme_make_byte_string dll_scheme_make_byte_string # define scheme_make_byte_string_output_port \ dll_scheme_make_byte_string_output_port # endif # define scheme_make_struct_instance dll_scheme_make_struct_instance # define scheme_make_struct_names dll_scheme_make_struct_names # define scheme_make_struct_type dll_scheme_make_struct_type # define scheme_make_struct_values dll_scheme_make_struct_values # define scheme_make_type dll_scheme_make_type # define scheme_make_vector dll_scheme_make_vector # define scheme_malloc_fail_ok dll_scheme_malloc_fail_ok # define scheme_open_input_file dll_scheme_open_input_file # define scheme_primitive_module dll_scheme_primitive_module # define scheme_proper_list_length dll_scheme_proper_list_length # define scheme_raise dll_scheme_raise # define scheme_read dll_scheme_read # define scheme_register_static dll_scheme_register_static # define scheme_set_stack_base dll_scheme_set_stack_base # define scheme_signal_error dll_scheme_signal_error # define scheme_wrong_type dll_scheme_wrong_type # if MZSCHEME_VERSION_MAJOR >= 299 # define scheme_set_param dll_scheme_set_param # define scheme_current_config dll_scheme_current_config # define scheme_char_string_to_byte_string \ dll_scheme_char_string_to_byte_string # define scheme_char_string_to_path \ dll_scheme_char_string_to_path # endif # define scheme_make_hash_table dll_scheme_make_hash_table # define scheme_hash_set dll_scheme_hash_set # define scheme_hash_get dll_scheme_hash_get # define scheme_make_double dll_scheme_make_double # ifdef INCLUDE_MZSCHEME_BASE # define scheme_make_sized_byte_string dll_scheme_make_sized_byte_string # define scheme_namespace_require dll_scheme_namespace_require # endif typedef struct { char *name; void **ptr; } Thunk_Info; static Thunk_Info mzgc_imports[] = { {"GC_malloc", (void **)&dll_GC_malloc}, {"GC_malloc_atomic", (void **)&dll_GC_malloc_atomic}, {NULL, NULL}}; static Thunk_Info mzsch_imports[] = { {"scheme_eof", (void **)&dll_scheme_eof}, {"scheme_false", (void **)&dll_scheme_false}, {"scheme_void", (void **)&dll_scheme_void}, {"scheme_null", (void **)&dll_scheme_null}, {"scheme_true", (void **)&dll_scheme_true}, {"scheme_current_thread", (void **)&dll_scheme_current_thread_ptr}, {"scheme_console_printf", (void **)&dll_scheme_console_printf_ptr}, {"scheme_console_output", (void **)&dll_scheme_console_output_ptr}, {"scheme_notify_multithread", (void **)&dll_scheme_notify_multithread_ptr}, {"scheme_add_global", (void **)&dll_scheme_add_global}, {"scheme_add_global_symbol", (void **)&dll_scheme_add_global_symbol}, {"scheme_apply", (void **)&dll_scheme_apply}, {"scheme_basic_env", (void **)&dll_scheme_basic_env}, # if MZSCHEME_VERSION_MAJOR >= 299 {"scheme_byte_string_to_char_string", (void **)&dll_scheme_byte_string_to_char_string}, # endif {"scheme_builtin_value", (void **)&dll_scheme_builtin_value}, {"scheme_check_threads", (void **)&dll_scheme_check_threads}, {"scheme_close_input_port", (void **)&dll_scheme_close_input_port}, {"scheme_count_lines", (void **)&dll_scheme_count_lines}, {"scheme_current_continuation_marks", (void **)&dll_scheme_current_continuation_marks}, {"scheme_display", (void **)&dll_scheme_display}, {"scheme_display_to_string", (void **)&dll_scheme_display_to_string}, {"scheme_do_eval", (void **)&dll_scheme_do_eval}, {"scheme_dont_gc_ptr", (void **)&dll_scheme_dont_gc_ptr}, {"scheme_eq", (void **)&dll_scheme_eq}, {"scheme_eval", (void **)&dll_scheme_eval}, {"scheme_eval_string", (void **)&dll_scheme_eval_string}, {"scheme_eval_string_all", (void **)&dll_scheme_eval_string_all}, {"scheme_finish_primitive_module", (void **)&dll_scheme_finish_primitive_module}, # if MZSCHEME_VERSION_MAJOR < 299 {"scheme_format", (void **)&dll_scheme_format}, # else {"scheme_format_utf8", (void **)&dll_scheme_format_utf8}, {"scheme_get_param", (void **)&dll_scheme_get_param}, #endif {"scheme_gc_ptr_ok", (void **)&dll_scheme_gc_ptr_ok}, # if MZSCHEME_VERSION_MAJOR < 299 {"scheme_get_sized_string_output", (void **)&dll_scheme_get_sized_string_output}, # else {"scheme_get_sized_byte_string_output", (void **)&dll_scheme_get_sized_byte_string_output}, #endif {"scheme_intern_symbol", (void **)&dll_scheme_intern_symbol}, {"scheme_lookup_global", (void **)&dll_scheme_lookup_global}, {"scheme_make_closed_prim_w_arity", (void **)&dll_scheme_make_closed_prim_w_arity}, {"scheme_make_integer_value", (void **)&dll_scheme_make_integer_value}, {"scheme_make_pair", (void **)&dll_scheme_make_pair}, {"scheme_make_prim_w_arity", (void **)&dll_scheme_make_prim_w_arity}, # if MZSCHEME_VERSION_MAJOR < 299 {"scheme_make_string", (void **)&dll_scheme_make_string}, {"scheme_make_string_output_port", (void **)&dll_scheme_make_string_output_port}, # else {"scheme_make_byte_string", (void **)&dll_scheme_make_byte_string}, {"scheme_make_byte_string_output_port", (void **)&dll_scheme_make_byte_string_output_port}, # endif {"scheme_make_struct_instance", (void **)&dll_scheme_make_struct_instance}, {"scheme_make_struct_names", (void **)&dll_scheme_make_struct_names}, {"scheme_make_struct_type", (void **)&dll_scheme_make_struct_type}, {"scheme_make_struct_values", (void **)&dll_scheme_make_struct_values}, {"scheme_make_type", (void **)&dll_scheme_make_type}, {"scheme_make_vector", (void **)&dll_scheme_make_vector}, {"scheme_malloc_fail_ok", (void **)&dll_scheme_malloc_fail_ok}, {"scheme_open_input_file", (void **)&dll_scheme_open_input_file}, {"scheme_primitive_module", (void **)&dll_scheme_primitive_module}, {"scheme_proper_list_length", (void **)&dll_scheme_proper_list_length}, {"scheme_raise", (void **)&dll_scheme_raise}, {"scheme_read", (void **)&dll_scheme_read}, {"scheme_register_static", (void **)&dll_scheme_register_static}, {"scheme_set_stack_base", (void **)&dll_scheme_set_stack_base}, {"scheme_signal_error", (void **)&dll_scheme_signal_error}, {"scheme_wrong_type", (void **)&dll_scheme_wrong_type}, # if MZSCHEME_VERSION_MAJOR >= 299 {"scheme_set_param", (void **)&dll_scheme_set_param}, {"scheme_current_config", (void **)&dll_scheme_current_config}, {"scheme_char_string_to_byte_string", (void **)&dll_scheme_char_string_to_byte_string}, {"scheme_char_string_to_path", (void **)&dll_scheme_char_string_to_path}, # endif {"scheme_make_hash_table", (void **)&dll_scheme_make_hash_table}, {"scheme_hash_set", (void **)&dll_scheme_hash_set}, {"scheme_hash_get", (void **)&dll_scheme_hash_get}, {"scheme_make_double", (void **)&dll_scheme_make_double}, # ifdef INCLUDE_MZSCHEME_BASE {"scheme_make_sized_byte_string", (void **)&dll_scheme_make_sized_byte_string}, {"scheme_namespace_require", (void **)&dll_scheme_namespace_require}, #endif {NULL, NULL}}; static HINSTANCE hMzGC = 0; static HINSTANCE hMzSch = 0; static void dynamic_mzscheme_end(void); static int mzscheme_runtime_link_init(char *sch_dll, char *gc_dll, int verbose); static int mzscheme_runtime_link_init(char *sch_dll, char *gc_dll, int verbose) { Thunk_Info *thunk = NULL; if (hMzGC && hMzSch) return OK; hMzSch = vimLoadLib(sch_dll); hMzGC = vimLoadLib(gc_dll); if (!hMzGC) { if (verbose) EMSG2(_(e_loadlib), gc_dll); return FAIL; } if (!hMzSch) { if (verbose) EMSG2(_(e_loadlib), sch_dll); return FAIL; } for (thunk = mzsch_imports; thunk->name; thunk++) { if ((*thunk->ptr = (void *)GetProcAddress(hMzSch, thunk->name)) == NULL) { FreeLibrary(hMzSch); hMzSch = 0; FreeLibrary(hMzGC); hMzGC = 0; if (verbose) EMSG2(_(e_loadfunc), thunk->name); return FAIL; } } for (thunk = mzgc_imports; thunk->name; thunk++) { if ((*thunk->ptr = (void *)GetProcAddress(hMzGC, thunk->name)) == NULL) { FreeLibrary(hMzSch); hMzSch = 0; FreeLibrary(hMzGC); hMzGC = 0; if (verbose) EMSG2(_(e_loadfunc), thunk->name); return FAIL; } } return OK; } int mzscheme_enabled(int verbose) { return mzscheme_runtime_link_init( DYNAMIC_MZSCH_DLL, DYNAMIC_MZGC_DLL, verbose) == OK; } static void dynamic_mzscheme_end(void) { if (hMzSch) { FreeLibrary(hMzSch); hMzSch = 0; } if (hMzGC) { FreeLibrary(hMzGC); hMzGC = 0; } } #endif /* DYNAMIC_MZSCHEME */ /* need to put it here for dynamic stuff to work */ #if defined(INCLUDE_MZSCHEME_BASE) # include "mzscheme_base.c" #elif MZSCHEME_VERSION_MAJOR >= 400 # error MzScheme 4.x must include mzscheme_base.c, for MinGW32 you need to define MZSCHEME_GENERATE_BASE=yes #endif /* *======================================================================== * 1. MzScheme interpreter startup *======================================================================== */ static Scheme_Type mz_buffer_type; static Scheme_Type mz_window_type; static int initialized = FALSE; /* global environment */ static Scheme_Env *environment = NULL; /* output/error handlers */ static Scheme_Object *curout = NULL; static Scheme_Object *curerr = NULL; /* exn:vim exception */ static Scheme_Object *exn_catching_apply = NULL; static Scheme_Object *exn_p = NULL; static Scheme_Object *exn_message = NULL; static Scheme_Object *vim_exn = NULL; /* Vim Error exception */ #if !defined(MZ_PRECISE_GC) || MZSCHEME_VERSION_MAJOR < 400 static void *stack_base = NULL; #endif static long range_start; static long range_end; /* MzScheme threads scheduling stuff */ static int mz_threads_allow = 0; #if defined(FEAT_GUI_W32) static void CALLBACK timer_proc(HWND, UINT, UINT, DWORD); static UINT timer_id = 0; #elif defined(FEAT_GUI_GTK) static gint timer_proc(gpointer); static guint timer_id = 0; #elif defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA) static void timer_proc(XtPointer, XtIntervalId *); static XtIntervalId timer_id = (XtIntervalId)0; #elif defined(FEAT_GUI_MAC) pascal void timer_proc(EventLoopTimerRef, void *); static EventLoopTimerRef timer_id = NULL; static EventLoopTimerUPP timerUPP; #endif #ifndef FEAT_GUI_W32 /* Win32 console and Unix */ void mzvim_check_threads(void) { /* Last time MzScheme threads were scheduled */ static time_t mz_last_time = 0; if (mz_threads_allow && p_mzq > 0) { time_t now = time(NULL); if ((now - mz_last_time) * 1000 > p_mzq) { mz_last_time = now; scheme_check_threads(); } } } #endif #ifdef MZSCHEME_GUI_THREADS static void setup_timer(void); static void remove_timer(void); /* timers are presented in GUI only */ # if defined(FEAT_GUI_W32) static void CALLBACK timer_proc(HWND hwnd UNUSED, UINT uMsg UNUSED, UINT idEvent UNUSED, DWORD dwTime UNUSED) # elif defined(FEAT_GUI_GTK) static gint timer_proc(gpointer data UNUSED) # elif defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA) static void timer_proc(XtPointer timed_out UNUSED, XtIntervalId *interval_id UNUSED) # elif defined(FEAT_GUI_MAC) pascal void timer_proc(EventLoopTimerRef theTimer UNUSED, void *userData UNUSED) # endif { scheme_check_threads(); # if defined(FEAT_GUI_GTK) return TRUE; /* continue receiving notifications */ # elif defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA) /* renew timeout */ if (mz_threads_allow && p_mzq > 0) timer_id = XtAppAddTimeOut(app_context, p_mzq, timer_proc, NULL); # endif } static void setup_timer(void) { # if defined(FEAT_GUI_W32) timer_id = SetTimer(NULL, 0, p_mzq, timer_proc); # elif defined(FEAT_GUI_GTK) timer_id = gtk_timeout_add((guint32)p_mzq, (GtkFunction)timer_proc, NULL); # elif defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA) timer_id = XtAppAddTimeOut(app_context, p_mzq, timer_proc, NULL); # elif defined(FEAT_GUI_MAC) timerUPP = NewEventLoopTimerUPP(timer_proc); InstallEventLoopTimer(GetMainEventLoop(), p_mzq * kEventDurationMillisecond, p_mzq * kEventDurationMillisecond, timerUPP, NULL, &timer_id); # endif } static void remove_timer(void) { # if defined(FEAT_GUI_W32) KillTimer(NULL, timer_id); # elif defined(FEAT_GUI_GTK) gtk_timeout_remove(timer_id); # elif defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA) XtRemoveTimeOut(timer_id); # elif defined(FEAT_GUI_MAC) RemoveEventLoopTimer(timer_id); DisposeEventLoopTimerUPP(timerUPP); # endif timer_id = 0; } void mzvim_reset_timer(void) { if (timer_id != 0) remove_timer(); if (mz_threads_allow && p_mzq > 0 && gui.in_use) setup_timer(); } #endif /* MZSCHEME_GUI_THREADS */ static void notify_multithread(int on) { mz_threads_allow = on; #ifdef MZSCHEME_GUI_THREADS if (on && timer_id == 0 && p_mzq > 0 && gui.in_use) setup_timer(); if (!on && timer_id != 0) remove_timer(); #endif } void mzscheme_end(void) { #ifdef DYNAMIC_MZSCHEME dynamic_mzscheme_end(); #endif } #if MZSCHEME_VERSION_MAJOR >= 500 && defined(WIN32) && defined(USE_THREAD_LOCAL) static __declspec(thread) void *tls_space; #endif /* * Since version 4.x precise GC requires trampolined startup. * Futures and places in version 5.x need it too. */ #if defined(MZ_PRECISE_GC) && MZSCHEME_VERSION_MAJOR >= 400 \ || MZSCHEME_VERSION_MAJOR >= 500 && (defined(MZ_USE_FUTURES) || defined(MZ_USE_PLACES)) # ifdef DYNAMIC_MZSCHEME # error Precise GC v.4+ or Racket with futures/places do not support dynamic MzScheme # endif # define TRAMPOLINED_MZVIM_STARTUP #endif int mzscheme_main(int argc, char** argv) { #if MZSCHEME_VERSION_MAJOR >= 500 && defined(WIN32) && defined(USE_THREAD_LOCAL) scheme_register_tls_space(&tls_space, 0); #endif #ifdef TRAMPOLINED_MZVIM_STARTUP return scheme_main_setup(TRUE, mzscheme_env_main, argc, argv); #else return mzscheme_env_main(NULL, argc, argv); #endif } static int mzscheme_env_main(Scheme_Env *env, int argc, char **argv) { int vim_main_result; #ifdef TRAMPOLINED_MZVIM_STARTUP /* Scheme has created the environment for us */ environment = env; #else # ifdef MZ_PRECISE_GC Scheme_Object *dummy = NULL; MZ_GC_DECL_REG(1); MZ_GC_VAR_IN_REG(0, dummy); stack_base = &__gc_var_stack__; # else int dummy = 0; stack_base = (void *)&dummy; # endif #endif /* mzscheme_main is called as a trampoline from main. * We trampoline into vim_main2 * Passing argc, argv through from mzscheme_main */ vim_main_result = vim_main2(argc, argv); #if !defined(TRAMPOLINED_MZVIM_STARTUP) && defined(MZ_PRECISE_GC) /* releasing dummy */ MZ_GC_REG(); MZ_GC_UNREG(); #endif return vim_main_result; } static void startup_mzscheme(void) { #ifndef TRAMPOLINED_MZVIM_STARTUP scheme_set_stack_base(stack_base, 1); #endif MZ_REGISTER_STATIC(environment); MZ_REGISTER_STATIC(curout); MZ_REGISTER_STATIC(curerr); MZ_REGISTER_STATIC(exn_catching_apply); MZ_REGISTER_STATIC(exn_p); MZ_REGISTER_STATIC(exn_message); MZ_REGISTER_STATIC(vim_exn); #ifndef TRAMPOLINED_MZVIM_STARTUP /* in newer versions of precise GC the initial env has been created */ environment = scheme_basic_env(); #endif MZ_GC_CHECK(); #ifdef INCLUDE_MZSCHEME_BASE { /* * versions 4.x do not provide Scheme bindings by default * we need to add them explicitly */ Scheme_Object *scheme_base_symbol = NULL; MZ_GC_DECL_REG(1); MZ_GC_VAR_IN_REG(0, scheme_base_symbol); MZ_GC_REG(); /* invoke function from generated and included mzscheme_base.c */ declare_modules(environment); scheme_base_symbol = scheme_intern_symbol("scheme/base"); MZ_GC_CHECK(); scheme_namespace_require(scheme_base_symbol); MZ_GC_CHECK(); MZ_GC_UNREG(); } #endif register_vim_exn(); /* use new environment to initialise exception handling */ init_exn_catching_apply(); /* redirect output */ scheme_console_output = do_output; scheme_console_printf = do_printf; #ifdef MZSCHEME_COLLECTS /* setup 'current-library-collection-paths' parameter */ # if MZSCHEME_VERSION_MAJOR >= 299 { Scheme_Object *coll_byte_string = NULL; Scheme_Object *coll_char_string = NULL; Scheme_Object *coll_path = NULL; Scheme_Object *coll_pair = NULL; Scheme_Config *config = NULL; MZ_GC_DECL_REG(5); MZ_GC_VAR_IN_REG(0, coll_byte_string); MZ_GC_VAR_IN_REG(1, coll_char_string); MZ_GC_VAR_IN_REG(2, coll_path); MZ_GC_VAR_IN_REG(3, coll_pair); MZ_GC_VAR_IN_REG(4, config); MZ_GC_REG(); coll_byte_string = scheme_make_byte_string(MZSCHEME_COLLECTS); MZ_GC_CHECK(); coll_char_string = scheme_byte_string_to_char_string(coll_byte_string); MZ_GC_CHECK(); coll_path = scheme_char_string_to_path(coll_char_string); MZ_GC_CHECK(); coll_pair = scheme_make_pair(coll_path, scheme_null); MZ_GC_CHECK(); config = scheme_config; MZ_GC_CHECK(); scheme_set_param(config, MZCONFIG_COLLECTION_PATHS, coll_pair); MZ_GC_CHECK(); MZ_GC_UNREG(); } # else { Scheme_Object *coll_string = NULL; Scheme_Object *coll_pair = NULL; Scheme_Config *config = NULL; MZ_GC_DECL_REG(3); MZ_GC_VAR_IN_REG(0, coll_string); MZ_GC_VAR_IN_REG(1, coll_pair); MZ_GC_VAR_IN_REG(2, config); MZ_GC_REG(); coll_string = scheme_make_string(MZSCHEME_COLLECTS); MZ_GC_CHECK(); coll_pair = scheme_make_pair(coll_string, scheme_null); MZ_GC_CHECK(); config = scheme_config; MZ_GC_CHECK(); scheme_set_param(config, MZCONFIG_COLLECTION_PATHS, coll_pair); MZ_GC_CHECK(); MZ_GC_UNREG(); } # endif #endif #ifdef HAVE_SANDBOX { Scheme_Object *make_security_guard = NULL; MZ_GC_DECL_REG(1); MZ_GC_VAR_IN_REG(0, make_security_guard); MZ_GC_REG(); #if MZSCHEME_VERSION_MAJOR < 400 { Scheme_Object *make_security_guard_symbol = NULL; MZ_GC_DECL_REG(1); MZ_GC_VAR_IN_REG(0, make_security_guard_symbol); MZ_GC_REG(); make_security_guard_symbol = scheme_intern_symbol("make-security-guard"); MZ_GC_CHECK(); make_security_guard = scheme_lookup_global( make_security_guard_symbol, environment); MZ_GC_UNREG(); } #else make_security_guard = scheme_builtin_value("make-security-guard"); MZ_GC_CHECK(); #endif /* setup sandbox guards */ if (make_security_guard != NULL) { Scheme_Object *args[3] = {NULL, NULL, NULL}; Scheme_Object *guard = NULL; Scheme_Config *config = NULL; MZ_GC_DECL_REG(5); MZ_GC_ARRAY_VAR_IN_REG(0, args, 3); MZ_GC_VAR_IN_REG(3, guard); MZ_GC_VAR_IN_REG(4, config); MZ_GC_REG(); config = scheme_config; MZ_GC_CHECK(); args[0] = scheme_get_param(config, MZCONFIG_SECURITY_GUARD); MZ_GC_CHECK(); args[1] = scheme_make_prim_w_arity(sandbox_file_guard, "sandbox-file-guard", 3, 3); args[2] = scheme_make_prim_w_arity(sandbox_network_guard, "sandbox-network-guard", 4, 4); guard = scheme_apply(make_security_guard, 3, args); MZ_GC_CHECK(); scheme_set_param(config, MZCONFIG_SECURITY_GUARD, guard); MZ_GC_CHECK(); MZ_GC_UNREG(); } MZ_GC_UNREG(); } #endif /* Create buffer and window types for use in Scheme code */ mz_buffer_type = scheme_make_type("<vim-buffer>"); MZ_GC_CHECK(); mz_window_type = scheme_make_type("<vim-window>"); MZ_GC_CHECK(); #ifdef MZ_PRECISE_GC GC_register_traversers(mz_buffer_type, buffer_size_proc, buffer_mark_proc, buffer_fixup_proc, TRUE, TRUE); GC_register_traversers(mz_window_type, window_size_proc, window_mark_proc, window_fixup_proc, TRUE, TRUE); #endif make_modules(); /* * setup callback to receive notifications * whether thread scheduling is (or not) required */ scheme_notify_multithread = notify_multithread; } /* * This routine is called for each new invocation of MzScheme * to make sure things are properly initialized. */ static int mzscheme_init(void) { if (!initialized) { #ifdef DYNAMIC_MZSCHEME if (!mzscheme_enabled(TRUE)) { EMSG(_("E815: Sorry, this command is disabled, the MzScheme libraries could not be loaded.")); return -1; } #endif startup_mzscheme(); initialized = TRUE; } { Scheme_Config *config = NULL; MZ_GC_DECL_REG(1); MZ_GC_VAR_IN_REG(0, config); MZ_GC_REG(); config = scheme_config; MZ_GC_CHECK(); /* recreate ports each call effectively clearing these ones */ curout = scheme_make_string_output_port(); MZ_GC_CHECK(); curerr = scheme_make_string_output_port(); MZ_GC_CHECK(); scheme_set_param(config, MZCONFIG_OUTPUT_PORT, curout); MZ_GC_CHECK(); scheme_set_param(config, MZCONFIG_ERROR_PORT, curerr); MZ_GC_CHECK(); MZ_GC_UNREG(); } return 0; } /* *======================================================================== * 2. External Interface *======================================================================== */ /* * Evaluate command with exception handling */ static int eval_with_exn_handling(void *data, Scheme_Closed_Prim *what, Scheme_Object **ret) { Scheme_Object *value = NULL; Scheme_Object *exn = NULL; Scheme_Object *prim = NULL; MZ_GC_DECL_REG(3); MZ_GC_VAR_IN_REG(0, value); MZ_GC_VAR_IN_REG(1, exn); MZ_GC_VAR_IN_REG(2, prim); MZ_GC_REG(); prim = scheme_make_closed_prim_w_arity(what, data, "mzvim", 0, 0); MZ_GC_CHECK(); value = _apply_thunk_catch_exceptions(prim, &exn); MZ_GC_CHECK(); if (!value) { value = extract_exn_message(exn); /* Got an exn? */ if (value) { scheme_display(value, curerr); /* Send to stderr-vim */ MZ_GC_CHECK(); do_flush(); } MZ_GC_UNREG(); /* `raise' was called on some arbitrary value */ return FAIL; } if (ret != NULL) /* if pointer to retval supported give it up */ *ret = value; /* Print any result, as long as it's not a void */ else if (!SCHEME_VOIDP(value)) { scheme_display(value, curout); /* Send to stdout-vim */ MZ_GC_CHECK(); } do_flush(); MZ_GC_UNREG(); return OK; } /* :mzscheme */ static int do_mzscheme_command(exarg_T *eap, void *data, Scheme_Closed_Prim *what) { if (mzscheme_init()) return FAIL; range_start = eap->line1; range_end = eap->line2; return eval_with_exn_handling(data, what, NULL); } /* * Routine called by VIM when deleting a buffer */ void mzscheme_buffer_free(buf_T *buf) { if (buf->b_mzscheme_ref) { vim_mz_buffer *bp; bp = buf->b_mzscheme_ref; bp->buf = INVALID_BUFFER_VALUE; buf->b_mzscheme_ref = NULL; scheme_gc_ptr_ok(bp); MZ_GC_CHECK(); } } /* * Routine called by VIM when deleting a Window */ void mzscheme_window_free(win_T *win) { if (win->w_mzscheme_ref) { vim_mz_window *wp; wp = win->w_mzscheme_ref; wp->win = INVALID_WINDOW_VALUE; win->w_mzscheme_ref = NULL; scheme_gc_ptr_ok(wp); MZ_GC_CHECK(); } } /* * ":mzscheme" (or ":mz") */ void ex_mzscheme(exarg_T *eap) { char_u *script; script = script_get(eap, eap->arg); if (!eap->skip) { if (script == NULL) do_mzscheme_command(eap, eap->arg, do_eval); else { do_mzscheme_command(eap, script, do_eval); vim_free(script); } } } static Scheme_Object * do_load(void *data, int noargc UNUSED, Scheme_Object **noargv UNUSED) { Scheme_Object *expr = NULL; Scheme_Object *result = NULL; char *file = NULL; Port_Info *pinfo = (Port_Info *)data; MZ_GC_DECL_REG(3); MZ_GC_VAR_IN_REG(0, expr); MZ_GC_VAR_IN_REG(1, result); MZ_GC_VAR_IN_REG(2, file); MZ_GC_REG(); file = (char *)scheme_malloc_fail_ok(scheme_malloc_atomic, MAXPATHL + 1); MZ_GC_CHECK(); /* make Vim expansion */ expand_env((char_u *)pinfo->name, (char_u *)file, MAXPATHL); pinfo->port = scheme_open_input_file(file, "mzfile"); MZ_GC_CHECK(); scheme_count_lines(pinfo->port); /* to get accurate read error location*/ MZ_GC_CHECK(); /* Like REPL but print only last result */ while (!SCHEME_EOFP(expr = scheme_read(pinfo->port))) { result = scheme_eval(expr, environment); MZ_GC_CHECK(); } /* errors will be caught in do_mzscheme_command and ex_mzfile */ scheme_close_input_port(pinfo->port); MZ_GC_CHECK(); pinfo->port = NULL; MZ_GC_UNREG(); return result; } /* :mzfile */ void ex_mzfile(exarg_T *eap) { Port_Info pinfo = {NULL, NULL}; MZ_GC_DECL_REG(1); MZ_GC_VAR_IN_REG(0, pinfo.port); MZ_GC_REG(); pinfo.name = (char *)eap->arg; if (do_mzscheme_command(eap, &pinfo, do_load) != OK && pinfo.port != NULL) /* looks like port was not closed */ { scheme_close_input_port(pinfo.port); MZ_GC_CHECK(); } MZ_GC_UNREG(); } /* *======================================================================== * Exception handling code -- cribbed form the MzScheme sources and * Matthew Flatt's "Inside PLT MzScheme" document. *======================================================================== */ static void init_exn_catching_apply(void) { if (!exn_catching_apply) { char *e = "(lambda (thunk) " "(with-handlers ([void (lambda (exn) (cons #f exn))]) " "(cons #t (thunk))))"; exn_catching_apply = scheme_eval_string(e, environment); MZ_GC_CHECK(); exn_p = scheme_builtin_value("exn?"); MZ_GC_CHECK(); exn_message = scheme_builtin_value("exn-message"); MZ_GC_CHECK(); } } /* * This function applies a thunk, returning the Scheme value if there's * no exception, otherwise returning NULL and setting *exn to the raised * value (usually an exn structure). */ static Scheme_Object * _apply_thunk_catch_exceptions(Scheme_Object *f, Scheme_Object **exn) { Scheme_Object *v; v = _scheme_apply(exn_catching_apply, 1, &f); /* v is a pair: (cons #t value) or (cons #f exn) */ if (SCHEME_TRUEP(SCHEME_CAR(v))) return SCHEME_CDR(v); else { *exn = SCHEME_CDR(v); return NULL; } } static Scheme_Object * extract_exn_message(Scheme_Object *v) { if (SCHEME_TRUEP(_scheme_apply(exn_p, 1, &v))) return _scheme_apply(exn_message, 1, &v); else return NULL; /* Not an exn structure */ } static Scheme_Object * do_eval(void *s, int noargc UNUSED, Scheme_Object **noargv UNUSED) { return scheme_eval_string_all((char *)s, environment, TRUE); } /* *======================================================================== * 3. MzScheme I/O Handlers *======================================================================== */ static void do_intrnl_output(char *mesg, int error) { char *p, *prev; prev = mesg; p = strchr(prev, '\n'); while (p) { *p = '\0'; if (error) EMSG(prev); else MSG(prev); prev = p + 1; p = strchr(prev, '\n'); } if (error) EMSG(prev); else MSG(prev); } static void do_output(char *mesg, long len UNUSED) { do_intrnl_output(mesg, 0); } static void do_err_output(char *mesg) { do_intrnl_output(mesg, 1); } static void do_printf(char *format, ...) { do_intrnl_output(format, 1); } static void do_flush(void) { char *buff; long length; buff = scheme_get_sized_string_output(curerr, &length); MZ_GC_CHECK(); if (length) { do_err_output(buff); return; } buff = scheme_get_sized_string_output(curout, &length); MZ_GC_CHECK(); if (length) do_output(buff, length); } /* *======================================================================== * 4. Implementation of the Vim Features for MzScheme *======================================================================== */ /* (command {command-string}) */ static Scheme_Object * vim_command(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; char *cmd = SCHEME_STR_VAL(GUARANTEE_STRING(prim->name, 0)); /* may be use do_cmdline_cmd? */ do_cmdline((char_u *)cmd, NULL, NULL, DOCMD_NOWAIT|DOCMD_VERBOSE); update_screen(VALID); raise_if_error(); return scheme_void; } /* (eval {expr-string}) */ static Scheme_Object * vim_eval(void *data, int argc, Scheme_Object **argv) { #ifdef FEAT_EVAL Vim_Prim *prim = (Vim_Prim *)data; char *expr; Scheme_Object *result; /* hash table to store visited values to avoid infinite loops */ Scheme_Hash_Table *visited = NULL; typval_T *vim_result; MZ_GC_DECL_REG(1); MZ_GC_VAR_IN_REG(0, visited); MZ_GC_REG(); visited = scheme_make_hash_table(SCHEME_hash_ptr); MZ_GC_CHECK(); expr = SCHEME_STR_VAL(GUARANTEE_STRING(prim->name, 0)); vim_result = eval_expr((char_u *)expr, NULL); if (vim_result == NULL) raise_vim_exn(_("invalid expression")); result = vim_to_mzscheme(vim_result, 1, visited); free_tv(vim_result); MZ_GC_UNREG(); return result; #else raise_vim_exn(_("expressions disabled at compile time")); /* unreachable */ return scheme_false; #endif } /* (range-start) */ static Scheme_Object * get_range_start(void *data UNUSED, int argc UNUSED, Scheme_Object **argv UNUSED) { return scheme_make_integer(range_start); } /* (range-end) */ static Scheme_Object * get_range_end(void *data UNUSED, int argc UNUSED, Scheme_Object **argv UNUSED) { return scheme_make_integer(range_end); } /* (beep) */ static Scheme_Object * mzscheme_beep(void *data UNUSED, int argc UNUSED, Scheme_Object **argv UNUSED) { vim_beep(); return scheme_void; } static Scheme_Object *M_global = NULL; /* (get-option {option-name}) [buffer/window] */ static Scheme_Object * get_option(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; char_u *name; long value; char *strval; int rc; Scheme_Object *rval; int opt_flags = 0; buf_T *save_curb = curbuf; win_T *save_curw = curwin; name = (char_u *)SCHEME_STR_VAL(GUARANTEE_STRING(prim->name, 0)); if (argc > 1) { if (M_global == NULL) { MZ_REGISTER_STATIC(M_global); M_global = scheme_intern_symbol("global"); MZ_GC_CHECK(); } if (argv[1] == M_global) opt_flags = OPT_GLOBAL; else if (SCHEME_VIMBUFFERP(argv[1])) { curbuf = get_valid_buffer(argv[1]); opt_flags = OPT_LOCAL; } else if (SCHEME_VIMWINDOWP(argv[1])) { win_T *win = get_valid_window(argv[1]); curwin = win; curbuf = win->w_buffer; opt_flags = OPT_LOCAL; } else scheme_wrong_type(prim->name, "vim-buffer/window", 1, argc, argv); } rc = get_option_value(name, &value, (char_u **)&strval, opt_flags); curbuf = save_curb; curwin = save_curw; switch (rc) { case 1: return scheme_make_integer_value(value); case 0: rval = scheme_make_string(strval); MZ_GC_CHECK(); vim_free(strval); return rval; case -1: case -2: raise_vim_exn(_("hidden option")); case -3: raise_vim_exn(_("unknown option")); } /* unreachable */ return scheme_void; } /* (set-option {option-changing-string} [buffer/window]) */ static Scheme_Object * set_option(void *data, int argc, Scheme_Object **argv) { char_u *cmd; int opt_flags = 0; buf_T *save_curb = curbuf; win_T *save_curw = curwin; Vim_Prim *prim = (Vim_Prim *)data; GUARANTEE_STRING(prim->name, 0); if (argc > 1) { if (M_global == NULL) { MZ_REGISTER_STATIC(M_global); M_global = scheme_intern_symbol("global"); MZ_GC_CHECK(); } if (argv[1] == M_global) opt_flags = OPT_GLOBAL; else if (SCHEME_VIMBUFFERP(argv[1])) { curbuf = get_valid_buffer(argv[1]); opt_flags = OPT_LOCAL; } else if (SCHEME_VIMWINDOWP(argv[1])) { win_T *win = get_valid_window(argv[1]); curwin = win; curbuf = win->w_buffer; opt_flags = OPT_LOCAL; } else scheme_wrong_type(prim->name, "vim-buffer/window", 1, argc, argv); } /* do_set can modify cmd, make copy */ cmd = vim_strsave((char_u *)SCHEME_STR_VAL(argv[0])); do_set(cmd, opt_flags); vim_free(cmd); update_screen(NOT_VALID); curbuf = save_curb; curwin = save_curw; raise_if_error(); return scheme_void; } /* *=========================================================================== * 5. Vim Window-related Manipulation Functions *=========================================================================== */ /* (curr-win) */ static Scheme_Object * get_curr_win(void *data UNUSED, int argc UNUSED, Scheme_Object **argv UNUSED) { return (Scheme_Object *)get_vim_curr_window(); } /* (win-count) */ static Scheme_Object * get_window_count(void *data UNUSED, int argc UNUSED, Scheme_Object **argv UNUSED) { win_T *w; int n = 0; for (w = firstwin; w != NULL; w = w->w_next) ++n; return scheme_make_integer(n); } /* (get-win-list [buffer]) */ static Scheme_Object * get_window_list(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; vim_mz_buffer *buf; Scheme_Object *list; win_T *w; buf = get_buffer_arg(prim->name, 0, argc, argv); list = scheme_null; for (w = firstwin; w != NULL; w = w->w_next) if (w->w_buffer == buf->buf) { list = scheme_make_pair(window_new(w), list); MZ_GC_CHECK(); } return list; } static Scheme_Object * window_new(win_T *win) { vim_mz_window *self = NULL; MZ_GC_DECL_REG(1); MZ_GC_VAR_IN_REG(0, self); MZ_GC_REG(); /* We need to handle deletion of windows underneath us. * If we add a "w_mzscheme_ref" field to the win_T structure, * then we can get at it in win_free() in vim. * * On a win_free() we set the Scheme object's win_T *field * to an invalid value. We trap all uses of a window * object, and reject them if the win_T *field is invalid. */ if (win->w_mzscheme_ref != NULL) return win->w_mzscheme_ref; self = scheme_malloc_fail_ok(scheme_malloc, sizeof(vim_mz_window)); vim_memset(self, 0, sizeof(vim_mz_window)); scheme_dont_gc_ptr(self); /* because win isn't visible to GC */ MZ_GC_CHECK(); win->w_mzscheme_ref = self; self->win = win; self->so.type = mz_window_type; MZ_GC_UNREG(); return (Scheme_Object *)(self); } /* (get-win-num [window]) */ static Scheme_Object * get_window_num(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; win_T *win = get_window_arg(prim->name, 0, argc, argv)->win; int nr = 1; win_T *wp; for (wp = firstwin; wp != win; wp = wp->w_next) ++nr; return scheme_make_integer(nr); } /* (get-win-by-num {windownum}) */ static Scheme_Object * get_window_by_num(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; win_T *win; int fnum; fnum = SCHEME_INT_VAL(GUARANTEE_INTEGER(prim->name, 0)); if (fnum < 1) scheme_signal_error(_("window index is out of range")); for (win = firstwin; win != NULL; win = win->w_next, --fnum) if (fnum == 1) /* to be 1-based */ return window_new(win); return scheme_false; } /* (get-win-buffer [window]) */ static Scheme_Object * get_window_buffer(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; vim_mz_window *win = get_window_arg(prim->name, 0, argc, argv); return buffer_new(win->win->w_buffer); } /* (get-win-height [window]) */ static Scheme_Object * get_window_height(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; vim_mz_window *win = get_window_arg(prim->name, 0, argc, argv); return scheme_make_integer(win->win->w_height); } /* (set-win-height {height} [window]) */ static Scheme_Object * set_window_height(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; vim_mz_window *win; win_T *savewin; int height; win = get_window_arg(prim->name, 1, argc, argv); height = SCHEME_INT_VAL(GUARANTEE_INTEGER(prim->name, 0)); #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif savewin = curwin; curwin = win->win; win_setheight(height); curwin = savewin; raise_if_error(); return scheme_void; } #ifdef FEAT_VERTSPLIT /* (get-win-width [window]) */ static Scheme_Object * get_window_width(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; vim_mz_window *win = get_window_arg(prim->name, 0, argc, argv); return scheme_make_integer(W_WIDTH(win->win)); } /* (set-win-width {width} [window]) */ static Scheme_Object * set_window_width(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; vim_mz_window *win; win_T *savewin; int width = 0; win = get_window_arg(prim->name, 1, argc, argv); width = SCHEME_INT_VAL(GUARANTEE_INTEGER(prim->name, 0)); # ifdef FEAT_GUI need_mouse_correct = TRUE; # endif savewin = curwin; curwin = win->win; win_setwidth(width); curwin = savewin; raise_if_error(); return scheme_void; } #endif /* (get-cursor [window]) -> (line . col) */ static Scheme_Object * get_cursor(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; vim_mz_window *win; pos_T pos; win = get_window_arg(prim->name, 0, argc, argv); pos = win->win->w_cursor; return scheme_make_pair(scheme_make_integer_value((long)pos.lnum), scheme_make_integer_value((long)pos.col + 1)); } /* (set-cursor (line . col) [window]) */ static Scheme_Object * set_cursor(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; vim_mz_window *win; long lnum = 0; long col = 0; #ifdef HAVE_SANDBOX sandbox_check(); #endif win = get_window_arg(prim->name, 1, argc, argv); GUARANTEE_PAIR(prim->name, 0); if (!SCHEME_INTP(SCHEME_CAR(argv[0])) || !SCHEME_INTP(SCHEME_CDR(argv[0]))) scheme_wrong_type(prim->name, "integer pair", 0, argc, argv); lnum = SCHEME_INT_VAL(SCHEME_CAR(argv[0])); col = SCHEME_INT_VAL(SCHEME_CDR(argv[0])) - 1; check_line_range(lnum, win->win->w_buffer); /* don't know how to catch invalid column value */ win->win->w_cursor.lnum = lnum; win->win->w_cursor.col = col; update_screen(VALID); raise_if_error(); return scheme_void; } /* *=========================================================================== * 6. Vim Buffer-related Manipulation Functions *=========================================================================== */ /* (open-buff {filename}) */ static Scheme_Object * mzscheme_open_buffer(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; char_u *fname; int num = 0; Scheme_Object *onum; #ifdef HAVE_SANDBOX sandbox_check(); #endif fname = (char_u *)SCHEME_STR_VAL(GUARANTEE_STRING(prim->name, 0)); /* TODO make open existing file */ num = buflist_add(fname, BLN_LISTED | BLN_CURBUF); if (num == 0) raise_vim_exn(_("couldn't open buffer")); onum = scheme_make_integer(num); return get_buffer_by_num(data, 1, &onum); } /* (get-buff-by-num {buffernum}) */ static Scheme_Object * get_buffer_by_num(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; buf_T *buf; int fnum; fnum = SCHEME_INT_VAL(GUARANTEE_INTEGER(prim->name, 0)); for (buf = firstbuf; buf; buf = buf->b_next) if (buf->b_fnum == fnum) return buffer_new(buf); return scheme_false; } /* (get-buff-by-name {buffername}) */ static Scheme_Object * get_buffer_by_name(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; buf_T *buf; char_u *fname; fname = (char_u *)SCHEME_STR_VAL(GUARANTEE_STRING(prim->name, 0)); for (buf = firstbuf; buf; buf = buf->b_next) if (buf->b_ffname == NULL || buf->b_sfname == NULL) /* empty string */ { if (fname[0] == NUL) return buffer_new(buf); } else if (!fnamecmp(buf->b_ffname, fname) || !fnamecmp(buf->b_sfname, fname)) /* either short or long filename matches */ return buffer_new(buf); return scheme_false; } /* (get-next-buff [buffer]) */ static Scheme_Object * get_next_buffer(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; buf_T *buf = get_buffer_arg(prim->name, 0, argc, argv)->buf; if (buf->b_next == NULL) return scheme_false; else return buffer_new(buf->b_next); } /* (get-prev-buff [buffer]) */ static Scheme_Object * get_prev_buffer(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; buf_T *buf = get_buffer_arg(prim->name, 0, argc, argv)->buf; if (buf->b_prev == NULL) return scheme_false; else return buffer_new(buf->b_prev); } /* (get-buff-num [buffer]) */ static Scheme_Object * get_buffer_num(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; vim_mz_buffer *buf = get_buffer_arg(prim->name, 0, argc, argv); return scheme_make_integer(buf->buf->b_fnum); } /* (buff-count) */ static Scheme_Object * get_buffer_count(void *data UNUSED, int argc UNUSED, Scheme_Object **argv UNUSED) { buf_T *b; int n = 0; for (b = firstbuf; b; b = b->b_next) ++n; return scheme_make_integer(n); } /* (get-buff-name [buffer]) */ static Scheme_Object * get_buffer_name(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; vim_mz_buffer *buf = get_buffer_arg(prim->name, 0, argc, argv); return scheme_make_string((char *)buf->buf->b_ffname); } /* (curr-buff) */ static Scheme_Object * get_curr_buffer(void *data UNUSED, int argc UNUSED, Scheme_Object **argv UNUSED) { return (Scheme_Object *)get_vim_curr_buffer(); } static Scheme_Object * buffer_new(buf_T *buf) { vim_mz_buffer *self = NULL; MZ_GC_DECL_REG(1); MZ_GC_VAR_IN_REG(0, self); MZ_GC_REG(); /* We need to handle deletion of buffers underneath us. * If we add a "b_mzscheme_ref" field to the buf_T structure, * then we can get at it in buf_freeall() in vim. */ if (buf->b_mzscheme_ref) return buf->b_mzscheme_ref; self = scheme_malloc_fail_ok(scheme_malloc, sizeof(vim_mz_buffer)); vim_memset(self, 0, sizeof(vim_mz_buffer)); scheme_dont_gc_ptr(self); /* because buf isn't visible to GC */ MZ_GC_CHECK(); buf->b_mzscheme_ref = self; self->buf = buf; self->so.type = mz_buffer_type; MZ_GC_UNREG(); return (Scheme_Object *)(self); } /* * (get-buff-size [buffer]) * * Get the size (number of lines) in the current buffer. */ static Scheme_Object * get_buffer_size(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; vim_mz_buffer *buf = get_buffer_arg(prim->name, 0, argc, argv); return scheme_make_integer(buf->buf->b_ml.ml_line_count); } /* * (get-buff-line {linenr} [buffer]) * * Get a line from the specified buffer. The line number is * in Vim format (1-based). The line is returned as a MzScheme * string object. */ static Scheme_Object * get_buffer_line(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; vim_mz_buffer *buf; int linenr; char_u *line; buf = get_buffer_arg(prim->name, 1, argc, argv); linenr = SCHEME_INT_VAL(GUARANTEE_INTEGER(prim->name, 0)); line = ml_get_buf(buf->buf, (linenr_T)linenr, FALSE); raise_if_error(); return scheme_make_string((char *)line); } /* * (get-buff-line-list {start} {end} [buffer]) * * Get a list of lines from the specified buffer. The line numbers * are in Vim format (1-based). The range is from lo up to, but not * including, hi. The list is returned as a list of string objects. */ static Scheme_Object * get_buffer_line_list(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; vim_mz_buffer *buf; int i, hi, lo, n; Scheme_Object *list = NULL; MZ_GC_DECL_REG(1); MZ_GC_VAR_IN_REG(0, list); MZ_GC_REG(); buf = get_buffer_arg(prim->name, 2, argc, argv); list = scheme_null; hi = SCHEME_INT_VAL(GUARANTEE_INTEGER(prim->name, 1)); lo = SCHEME_INT_VAL(GUARANTEE_INTEGER(prim->name, 0)); /* * Handle some error conditions */ if (lo < 0) lo = 0; if (hi < 0) hi = 0; if (hi < lo) hi = lo; n = hi - lo; for (i = n; i >= 0; --i) { Scheme_Object *str = scheme_make_string( (char *)ml_get_buf(buf->buf, (linenr_T)(lo+i), FALSE)); raise_if_error(); /* Set the list item */ list = scheme_make_pair(str, list); MZ_GC_CHECK(); } MZ_GC_UNREG(); return list; } /* * (set-buff-line {linenr} {string/#f} [buffer]) * * Replace a line in the specified buffer. The line number is * in Vim format (1-based). The replacement line is given as * an MzScheme string object. The object is checked for validity * and correct format. An exception is thrown if the values are not * the correct format. * * It returns a Scheme Object that indicates the length of the * string changed. */ static Scheme_Object * set_buffer_line(void *data, int argc, Scheme_Object **argv) { /* First of all, we check the value of the supplied MzScheme object. * There are three cases: * 1. #f - this is a deletion. * 2. A string - this is a replacement. * 3. Anything else - this is an error. */ Vim_Prim *prim = (Vim_Prim *)data; vim_mz_buffer *buf; Scheme_Object *line = NULL; char *save; int n; MZ_GC_DECL_REG(1); MZ_GC_VAR_IN_REG(0, line); MZ_GC_REG(); #ifdef HAVE_SANDBOX sandbox_check(); #endif n = SCHEME_INT_VAL(GUARANTEE_INTEGER(prim->name, 0)); if (!SCHEME_STRINGP(argv[1]) && !SCHEME_FALSEP(argv[1])) scheme_wrong_type(prim->name, "string or #f", 1, argc, argv); line = argv[1]; buf = get_buffer_arg(prim->name, 2, argc, argv); check_line_range(n, buf->buf); if (SCHEME_FALSEP(line)) { buf_T *savebuf = curbuf; curbuf = buf->buf; if (u_savedel((linenr_T)n, 1L) == FAIL) { curbuf = savebuf; raise_vim_exn(_("cannot save undo information")); } else if (ml_delete((linenr_T)n, FALSE) == FAIL) { curbuf = savebuf; raise_vim_exn(_("cannot delete line")); } if (buf->buf == curwin->w_buffer) mz_fix_cursor(n, n + 1, -1); deleted_lines_mark((linenr_T)n, 1L); curbuf = savebuf; MZ_GC_UNREG(); raise_if_error(); return scheme_void; } else { /* Otherwise it's a line */ buf_T *savebuf = curbuf; save = string_to_line(line); curbuf = buf->buf; if (u_savesub((linenr_T)n) == FAIL) { curbuf = savebuf; vim_free(save); raise_vim_exn(_("cannot save undo information")); } else if (ml_replace((linenr_T)n, (char_u *)save, TRUE) == FAIL) { curbuf = savebuf; vim_free(save); raise_vim_exn(_("cannot replace line")); } else { vim_free(save); changed_bytes((linenr_T)n, 0); } curbuf = savebuf; /* Check that the cursor is not beyond the end of the line now. */ if (buf->buf == curwin->w_buffer) check_cursor_col(); MZ_GC_UNREG(); raise_if_error(); return scheme_void; } } static void free_array(char **array) { char **curr = array; while (*curr != NULL) vim_free(*curr++); vim_free(array); } /* * (set-buff-line-list {start} {end} {string-list/#f/null} [buffer]) * * Replace a range of lines in the specified buffer. The line numbers are in * Vim format (1-based). The range is from lo up to, but not including, hi. * The replacement lines are given as a Scheme list of string objects. The * list is checked for validity and correct format. * * Errors are returned as a value of FAIL. The return value is OK on success. * If OK is returned and len_change is not NULL, *len_change is set to the * change in the buffer length. */ static Scheme_Object * set_buffer_line_list(void *data, int argc, Scheme_Object **argv) { /* First of all, we check the type of the supplied MzScheme object. * There are three cases: * 1. #f - this is a deletion. * 2. A list - this is a replacement. * 3. Anything else - this is an error. */ Vim_Prim *prim = (Vim_Prim *)data; vim_mz_buffer *buf = NULL; Scheme_Object *line_list = NULL; int i, old_len, new_len, hi, lo; long extra; MZ_GC_DECL_REG(1); MZ_GC_VAR_IN_REG(0, line_list); MZ_GC_REG(); #ifdef HAVE_SANDBOX sandbox_check(); #endif lo = SCHEME_INT_VAL(GUARANTEE_INTEGER(prim->name, 0)); hi = SCHEME_INT_VAL(GUARANTEE_INTEGER(prim->name, 1)); if (!SCHEME_PAIRP(argv[2]) && !SCHEME_FALSEP(argv[2]) && !SCHEME_NULLP(argv[2])) scheme_wrong_type(prim->name, "list or #f", 2, argc, argv); line_list = argv[2]; buf = get_buffer_arg(prim->name, 3, argc, argv); old_len = hi - lo; if (old_len < 0) /* process inverse values wisely */ { i = lo; lo = hi; hi = i; old_len = -old_len; } extra = 0; check_line_range(lo, buf->buf); /* inclusive */ check_line_range(hi - 1, buf->buf); /* exclusive */ if (SCHEME_FALSEP(line_list) || SCHEME_NULLP(line_list)) { buf_T *savebuf = curbuf; curbuf = buf->buf; if (u_savedel((linenr_T)lo, (long)old_len) == FAIL) { curbuf = savebuf; raise_vim_exn(_("cannot save undo information")); } else { for (i = 0; i < old_len; i++) if (ml_delete((linenr_T)lo, FALSE) == FAIL) { curbuf = savebuf; raise_vim_exn(_("cannot delete line")); } if (buf->buf == curwin->w_buffer) mz_fix_cursor(lo, hi, -old_len); deleted_lines_mark((linenr_T)lo, (long)old_len); } curbuf = savebuf; MZ_GC_UNREG(); raise_if_error(); return scheme_void; } else { buf_T *savebuf = curbuf; /* List */ new_len = scheme_proper_list_length(line_list); MZ_GC_CHECK(); if (new_len < 0) /* improper or cyclic list */ scheme_wrong_type(prim->name, "proper list", 2, argc, argv); else { char **array = NULL; Scheme_Object *line = NULL; Scheme_Object *rest = NULL; MZ_GC_DECL_REG(2); MZ_GC_VAR_IN_REG(0, line); MZ_GC_VAR_IN_REG(1, rest); MZ_GC_REG(); array = (char **)alloc(new_len * sizeof(char *)); vim_memset(array, 0, new_len * sizeof(char *)); rest = line_list; for (i = 0; i < new_len; ++i) { line = SCHEME_CAR(rest); rest = SCHEME_CDR(rest); if (!SCHEME_STRINGP(line)) { free_array(array); scheme_wrong_type(prim->name, "string-list", 2, argc, argv); } array[i] = string_to_line(line); } curbuf = buf->buf; if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL) { curbuf = savebuf; free_array(array); raise_vim_exn(_("cannot save undo information")); } /* * If the size of the range is reducing (ie, new_len < old_len) we * need to delete some old_len. We do this at the start, by * repeatedly deleting line "lo". */ for (i = 0; i < old_len - new_len; ++i) { if (ml_delete((linenr_T)lo, FALSE) == FAIL) { curbuf = savebuf; free_array(array); raise_vim_exn(_("cannot delete line")); } extra--; } /* * For as long as possible, replace the existing old_len with the * new old_len. This is a more efficient operation, as it requires * less memory allocation and freeing. */ for (i = 0; i < old_len && i < new_len; i++) if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], TRUE) == FAIL) { curbuf = savebuf; free_array(array); raise_vim_exn(_("cannot replace line")); } /* * Now we may need to insert the remaining new_len. We don't need to * free the string passed back because MzScheme has control of that * memory. */ while (i < new_len) { if (ml_append((linenr_T)(lo + i - 1), (char_u *)array[i], 0, FALSE) == FAIL) { curbuf = savebuf; free_array(array); raise_vim_exn(_("cannot insert line")); } ++i; ++extra; } MZ_GC_UNREG(); free_array(array); } /* * Adjust marks. Invalidate any which lie in the * changed range, and move any in the remainder of the buffer. */ mark_adjust((linenr_T)lo, (linenr_T)(hi - 1), (long)MAXLNUM, (long)extra); changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra); if (buf->buf == curwin->w_buffer) mz_fix_cursor(lo, hi, extra); curbuf = savebuf; MZ_GC_UNREG(); raise_if_error(); return scheme_void; } } /* * (insert-buff-line-list {linenr} {string/string-list} [buffer]) * * Insert a number of lines into the specified buffer after the specified line. * The line number is in Vim format (1-based). The lines to be inserted are * given as an MzScheme list of string objects or as a single string. The lines * to be added are checked for validity and correct format. Errors are * returned as a value of FAIL. The return value is OK on success. * If OK is returned and len_change is not NULL, *len_change * is set to the change in the buffer length. */ static Scheme_Object * insert_buffer_line_list(void *data, int argc, Scheme_Object **argv) { Vim_Prim *prim = (Vim_Prim *)data; vim_mz_buffer *buf = NULL; Scheme_Object *list = NULL; char *str = NULL; int i, n, size; MZ_GC_DECL_REG(1); MZ_GC_VAR_IN_REG(0, list); MZ_GC_REG(); #ifdef HAVE_SANDBOX sandbox_check(); #endif /* * First of all, we check the type of the supplied MzScheme object. * It must be a string or a list, or the call is in error. */ n = SCHEME_INT_VAL(GUARANTEE_INTEGER(prim->name, 0)); list = argv[1]; if (!SCHEME_STRINGP(list) && !SCHEME_PAIRP(list)) scheme_wrong_type(prim->name, "string or list", 1, argc, argv); buf = get_buffer_arg(prim->name, 2, argc, argv); if (n != 0) /* 0 can be used in insert */ check_line_range(n, buf->buf); if (SCHEME_STRINGP(list)) { buf_T *savebuf = curbuf; str = string_to_line(list); curbuf = buf->buf; if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL) { curbuf = savebuf; vim_free(str); raise_vim_exn(_("cannot save undo information")); } else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL) { curbuf = savebuf; vim_free(str); raise_vim_exn(_("cannot insert line")); } else { vim_free(str); appended_lines_mark((linenr_T)n, 1L); } curbuf = savebuf; update_screen(VALID); MZ_GC_UNREG(); raise_if_error(); return scheme_void; } /* List */ size = scheme_proper_list_length(list); MZ_GC_CHECK(); if (size < 0) /* improper or cyclic list */ scheme_wrong_type(prim->name, "proper list", 2, argc, argv); else { Scheme_Object *line = NULL; Scheme_Object *rest = NULL; char **array; buf_T *savebuf = curbuf; MZ_GC_DECL_REG(2); MZ_GC_VAR_IN_REG(0, line); MZ_GC_VAR_IN_REG(1, rest); MZ_GC_REG(); array = (char **)alloc(size * sizeof(char *)); vim_memset(array, 0, size * sizeof(char *)); rest = list; for (i = 0; i < size; ++i) { line = SCHEME_CAR(rest); rest = SCHEME_CDR(rest); array[i] = string_to_line(line); } curbuf = buf->buf; if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL) { curbuf = savebuf; free_array(array); raise_vim_exn(_("cannot save undo information")); } else { for (i = 0; i < size; ++i) if (ml_append((linenr_T)(n + i), (char_u *)array[i], 0, FALSE) == FAIL) { curbuf = savebuf; free_array(array); raise_vim_exn(_("cannot insert line")); } if (i > 0) appended_lines_mark((linenr_T)n, (long)i); } free_array(array); MZ_GC_UNREG(); curbuf = savebuf; update_screen(VALID); } MZ_GC_UNREG(); raise_if_error(); return scheme_void; } /* * Predicates */ /* (buff? obj) */ static Scheme_Object * vim_bufferp(void *data UNUSED, int argc UNUSED, Scheme_Object **argv) { if (SCHEME_VIMBUFFERP(argv[0])) return scheme_true; else return scheme_false; } /* (win? obj) */ static Scheme_Object * vim_windowp(void *data UNUSED, int argc UNUSED, Scheme_Object **argv) { if (SCHEME_VIMWINDOWP(argv[0])) return scheme_true; else return scheme_false; } /* (buff-valid? obj) */ static Scheme_Object * vim_buffer_validp(void *data UNUSED, int argc UNUSED, Scheme_Object **argv) { if (SCHEME_VIMBUFFERP(argv[0]) && ((vim_mz_buffer *)argv[0])->buf != INVALID_BUFFER_VALUE) return scheme_true; else return scheme_false; } /* (win-valid? obj) */ static Scheme_Object * vim_window_validp(void *data UNUSED, int argc UNUSED, Scheme_Object **argv) { if (SCHEME_VIMWINDOWP(argv[0]) && ((vim_mz_window *)argv[0])->win != INVALID_WINDOW_VALUE) return scheme_true; else return scheme_false; } /* *=========================================================================== * Utilities *=========================================================================== */ /* * Convert an MzScheme string into a Vim line. * * All internal nulls are replaced by newline characters. * It is an error for the string to contain newline characters. * * Returns pointer to Vim allocated memory */ static char * string_to_line(Scheme_Object *obj) { char *scheme_str = NULL; char *vim_str = NULL; long len; int i; scheme_str = scheme_display_to_string(obj, &len); /* Error checking: String must not contain newlines, as we * are replacing a single line, and we must replace it with * a single line. */ if (memchr(scheme_str, '\n', len)) scheme_signal_error(_("string cannot contain newlines")); vim_str = (char *)alloc(len + 1); /* Create a copy of the string, with internal nulls replaced by * newline characters, as is the vim convention. */ for (i = 0; i < len; ++i) { if (scheme_str[i] == '\0') vim_str[i] = '\n'; else vim_str[i] = scheme_str[i]; } vim_str[i] = '\0'; MZ_GC_CHECK(); return vim_str; } #ifdef FEAT_EVAL /* * Convert Vim value into MzScheme, adopted from if_python.c */ static Scheme_Object * vim_to_mzscheme(typval_T *vim_value, int depth, Scheme_Hash_Table *visited) { Scheme_Object *result = NULL; int new_value = TRUE; MZ_GC_DECL_REG(1); MZ_GC_VAR_IN_REG(0, result); MZ_GC_REG(); /* Avoid infinite recursion */ if (depth > 100) { MZ_GC_UNREG(); return scheme_void; } /* Check if we run into a recursive loop. The item must be in visited * then and we can use it again. */ result = scheme_hash_get(visited, (Scheme_Object *)vim_value); MZ_GC_CHECK(); if (result != NULL) /* found, do nothing */ new_value = FALSE; else if (vim_value->v_type == VAR_STRING) { result = scheme_make_string((char *)vim_value->vval.v_string); MZ_GC_CHECK(); } else if (vim_value->v_type == VAR_NUMBER) { result = scheme_make_integer((long)vim_value->vval.v_number); MZ_GC_CHECK(); } # ifdef FEAT_FLOAT else if (vim_value->v_type == VAR_FLOAT) { result = scheme_make_double((double)vim_value->vval.v_float); MZ_GC_CHECK(); } # endif else if (vim_value->v_type == VAR_LIST) { list_T *list = vim_value->vval.v_list; listitem_T *curr; if (list == NULL || list->lv_first == NULL) result = scheme_null; else { Scheme_Object *obj = NULL; MZ_GC_DECL_REG(1); MZ_GC_VAR_IN_REG(0, obj); MZ_GC_REG(); curr = list->lv_last; obj = vim_to_mzscheme(&curr->li_tv, depth + 1, visited); result = scheme_make_pair(obj, scheme_null); MZ_GC_CHECK(); while (curr != list->lv_first) { curr = curr->li_prev; obj = vim_to_mzscheme(&curr->li_tv, depth + 1, visited); result = scheme_make_pair(obj, result); MZ_GC_CHECK(); } } MZ_GC_UNREG(); } else if (vim_value->v_type == VAR_DICT) { Scheme_Object *key = NULL; Scheme_Object *obj = NULL; MZ_GC_DECL_REG(2); MZ_GC_VAR_IN_REG(0, key); MZ_GC_VAR_IN_REG(1, obj); MZ_GC_REG(); result = (Scheme_Object *)scheme_make_hash_table(SCHEME_hash_ptr); MZ_GC_CHECK(); if (vim_value->vval.v_dict != NULL) { hashtab_T *ht = &vim_value->vval.v_dict->dv_hashtab; long_u todo = ht->ht_used; hashitem_T *hi; dictitem_T *di; for (hi = ht->ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; di = dict_lookup(hi); obj = vim_to_mzscheme(&di->di_tv, depth + 1, visited); key = scheme_make_string((char *)hi->hi_key); MZ_GC_CHECK(); scheme_hash_set((Scheme_Hash_Table *)result, key, obj); MZ_GC_CHECK(); } } } MZ_GC_UNREG(); } else { result = scheme_void; new_value = FALSE; } if (new_value) { scheme_hash_set(visited, (Scheme_Object *)vim_value, result); MZ_GC_CHECK(); } MZ_GC_UNREG(); return result; } static int mzscheme_to_vim(Scheme_Object *obj, typval_T *tv, int depth, Scheme_Hash_Table *visited) { int status = OK; typval_T *found; MZ_GC_CHECK(); if (depth > 100) /* limit the deepest recursion level */ { tv->v_type = VAR_NUMBER; tv->vval.v_number = 0; return FAIL; } found = (typval_T *)scheme_hash_get(visited, obj); if (found != NULL) copy_tv(found, tv); else if (SCHEME_VOIDP(obj)) { tv->v_type = VAR_NUMBER; tv->vval.v_number = 0; } else if (SCHEME_INTP(obj)) { tv->v_type = VAR_NUMBER; tv->vval.v_number = SCHEME_INT_VAL(obj); } else if (SCHEME_BOOLP(obj)) { tv->v_type = VAR_NUMBER; tv->vval.v_number = SCHEME_TRUEP(obj); } # ifdef FEAT_FLOAT else if (SCHEME_DBLP(obj)) { tv->v_type = VAR_FLOAT; tv->vval.v_float = SCHEME_DBL_VAL(obj); } # endif else if (SCHEME_STRINGP(obj)) { tv->v_type = VAR_STRING; tv->vval.v_string = vim_strsave((char_u *)SCHEME_STR_VAL(obj)); } else if (SCHEME_VECTORP(obj) || SCHEME_NULLP(obj) || SCHEME_PAIRP(obj) || SCHEME_MUTABLE_PAIRP(obj)) { list_T *list = list_alloc(); if (list == NULL) status = FAIL; else { int i; Scheme_Object *curr = NULL; Scheme_Object *cval = NULL; /* temporary var to hold current element of vectors and pairs */ typval_T *v; MZ_GC_DECL_REG(2); MZ_GC_VAR_IN_REG(0, curr); MZ_GC_VAR_IN_REG(1, cval); MZ_GC_REG(); tv->v_type = VAR_LIST; tv->vval.v_list = list; ++list->lv_refcount; v = (typval_T *)alloc(sizeof(typval_T)); if (v == NULL) status = FAIL; else { /* add the value in advance to allow handling of self-referencial * data structures */ typval_T *visited_tv = (typval_T *)alloc(sizeof(typval_T)); copy_tv(tv, visited_tv); scheme_hash_set(visited, obj, (Scheme_Object *)visited_tv); if (SCHEME_VECTORP(obj)) { for (i = 0; i < SCHEME_VEC_SIZE(obj); ++i) { cval = SCHEME_VEC_ELS(obj)[i]; status = mzscheme_to_vim(cval, v, depth + 1, visited); if (status == FAIL) break; status = list_append_tv(list, v); clear_tv(v); if (status == FAIL) break; } } else if (SCHEME_PAIRP(obj) || SCHEME_MUTABLE_PAIRP(obj)) { for (curr = obj; SCHEME_PAIRP(curr) || SCHEME_MUTABLE_PAIRP(curr); curr = SCHEME_CDR(curr)) { cval = SCHEME_CAR(curr); status = mzscheme_to_vim(cval, v, depth + 1, visited); if (status == FAIL) break; status = list_append_tv(list, v); clear_tv(v); if (status == FAIL) break; } /* impoper list not terminated with null * need to handle the last element */ if (status == OK && !SCHEME_NULLP(curr)) { status = mzscheme_to_vim(cval, v, depth + 1, visited); if (status == OK) { status = list_append_tv(list, v); clear_tv(v); } } } /* nothing to do for scheme_null */ vim_free(v); } MZ_GC_UNREG(); } } else if (SCHEME_HASHTP(obj)) { int i; dict_T *dict; Scheme_Object *key = NULL; Scheme_Object *val = NULL; MZ_GC_DECL_REG(2); MZ_GC_VAR_IN_REG(0, key); MZ_GC_VAR_IN_REG(1, val); MZ_GC_REG(); dict = dict_alloc(); if (dict == NULL) status = FAIL; else { typval_T *visited_tv = (typval_T *)alloc(sizeof(typval_T)); tv->v_type = VAR_DICT; tv->vval.v_dict = dict; ++dict->dv_refcount; copy_tv(tv, visited_tv); scheme_hash_set(visited, obj, (Scheme_Object *)visited_tv); for (i = 0; i < ((Scheme_Hash_Table *)obj)->size; ++i) { if (((Scheme_Hash_Table *) obj)->vals[i] != NULL) { /* generate item for `diplay'ed Scheme key */ dictitem_T *item = dictitem_alloc((char_u *)string_to_line( ((Scheme_Hash_Table *) obj)->keys[i])); /* convert Scheme val to Vim and add it to the dict */ if (mzscheme_to_vim(((Scheme_Hash_Table *) obj)->vals[i], &item->di_tv, depth + 1, visited) == FAIL || dict_add(dict, item) == FAIL) { dictitem_free(item); status = FAIL; break; } } } } MZ_GC_UNREG(); } else { /* `display' any other value to string */ tv->v_type = VAR_STRING; tv->vval.v_string = (char_u *)string_to_line(obj); } return status; } void do_mzeval(char_u *str, typval_T *rettv) { int i; Scheme_Object *ret = NULL; Scheme_Hash_Table *visited = NULL; MZ_GC_DECL_REG(2); MZ_GC_VAR_IN_REG(0, ret); MZ_GC_VAR_IN_REG(0, visited); MZ_GC_REG(); if (mzscheme_init()) { MZ_GC_UNREG(); return; } MZ_GC_CHECK(); visited = scheme_make_hash_table(SCHEME_hash_ptr); MZ_GC_CHECK(); if (eval_with_exn_handling(str, do_eval, &ret) == OK) mzscheme_to_vim(ret, rettv, 1, visited); for (i = 0; i < visited->size; ++i) { /* free up remembered objects */ if (visited->vals[i] != NULL) { free_tv((typval_T *)visited->vals[i]); } } MZ_GC_UNREG(); } #endif /* * Check to see whether a Vim error has been reported, or a keyboard * interrupt (from vim --> got_int) has been detected. */ static int vim_error_check(void) { return (got_int || did_emsg); } /* * register Scheme exn:vim */ static void register_vim_exn(void) { int nc = 0; int i; Scheme_Object *struct_exn = NULL; Scheme_Object *exn_name = NULL; MZ_GC_DECL_REG(2); MZ_GC_VAR_IN_REG(0, struct_exn); MZ_GC_VAR_IN_REG(1, exn_name); MZ_GC_REG(); exn_name = scheme_intern_symbol("exn:vim"); MZ_GC_CHECK(); struct_exn = scheme_builtin_value("struct:exn"); MZ_GC_CHECK(); if (vim_exn == NULL) vim_exn = scheme_make_struct_type(exn_name, struct_exn, NULL, 0, 0, NULL, NULL #if MZSCHEME_VERSION_MAJOR >= 299 , NULL #endif ); { Scheme_Object **tmp = NULL; Scheme_Object *exn_names[5] = {NULL, NULL, NULL, NULL, NULL}; Scheme_Object *exn_values[5] = {NULL, NULL, NULL, NULL, NULL}; MZ_GC_DECL_REG(6); MZ_GC_ARRAY_VAR_IN_REG(0, exn_names, 5); MZ_GC_ARRAY_VAR_IN_REG(3, exn_values, 5); MZ_GC_REG(); tmp = scheme_make_struct_names(exn_name, scheme_null, 0, &nc); mch_memmove(exn_names, tmp, nc * sizeof(Scheme_Object *)); MZ_GC_CHECK(); tmp = scheme_make_struct_values(vim_exn, exn_names, nc, 0); mch_memmove(exn_values, tmp, nc * sizeof(Scheme_Object *)); MZ_GC_CHECK(); for (i = 0; i < nc; i++) { scheme_add_global_symbol(exn_names[i], exn_values[i], environment); MZ_GC_CHECK(); } MZ_GC_UNREG(); } MZ_GC_UNREG(); } /* * raise exn:vim, may be with additional info string */ void raise_vim_exn(const char *add_info) { char *fmt = _("Vim error: ~a"); Scheme_Object *argv[2] = {NULL, NULL}; Scheme_Object *exn = NULL; MZ_GC_DECL_REG(4); MZ_GC_ARRAY_VAR_IN_REG(0, argv, 2); MZ_GC_VAR_IN_REG(3, exn); MZ_GC_REG(); if (add_info != NULL) { char *c_string = NULL; Scheme_Object *byte_string = NULL; Scheme_Object *info = NULL; MZ_GC_DECL_REG(3); MZ_GC_VAR_IN_REG(0, c_string); MZ_GC_VAR_IN_REG(1, byte_string); MZ_GC_VAR_IN_REG(2, info); MZ_GC_REG(); info = scheme_make_string(add_info); MZ_GC_CHECK(); c_string = scheme_format(fmt, STRLEN(fmt), 1, &info, NULL); MZ_GC_CHECK(); byte_string = scheme_make_string(c_string); MZ_GC_CHECK(); argv[0] = scheme_byte_string_to_char_string(byte_string); MZ_GC_CHECK(); SCHEME_SET_IMMUTABLE(argv[0]); MZ_GC_UNREG(); } else argv[0] = scheme_make_string(_("Vim error")); MZ_GC_CHECK(); #if MZSCHEME_VERSION_MAJOR < 360 argv[1] = scheme_current_continuation_marks(); MZ_GC_CHECK(); #else argv[1] = scheme_current_continuation_marks(NULL); MZ_GC_CHECK(); #endif exn = scheme_make_struct_instance(vim_exn, 2, argv); MZ_GC_CHECK(); scheme_raise(exn); MZ_GC_UNREG(); } void raise_if_error(void) { if (vim_error_check()) raise_vim_exn(NULL); } /* get buffer: * either current * or passed as argv[argnum] with checks */ static vim_mz_buffer * get_buffer_arg(const char *fname, int argnum, int argc, Scheme_Object **argv) { vim_mz_buffer *b; if (argc < argnum + 1) return get_vim_curr_buffer(); if (!SCHEME_VIMBUFFERP(argv[argnum])) scheme_wrong_type(fname, "vim-buffer", argnum, argc, argv); b = (vim_mz_buffer *)argv[argnum]; (void)get_valid_buffer(argv[argnum]); return b; } /* get window: * either current * or passed as argv[argnum] with checks */ static vim_mz_window * get_window_arg(const char *fname, int argnum, int argc, Scheme_Object **argv) { vim_mz_window *w; if (argc < argnum + 1) return get_vim_curr_window(); w = (vim_mz_window *)argv[argnum]; if (!SCHEME_VIMWINDOWP(argv[argnum])) scheme_wrong_type(fname, "vim-window", argnum, argc, argv); (void)get_valid_window(argv[argnum]); return w; } /* get valid Vim buffer from Scheme_Object* */ buf_T *get_valid_buffer(void *obj) { buf_T *buf = ((vim_mz_buffer *)obj)->buf; if (buf == INVALID_BUFFER_VALUE) scheme_signal_error(_("buffer is invalid")); return buf; } /* get valid Vim window from Scheme_Object* */ win_T *get_valid_window(void *obj) { win_T *win = ((vim_mz_window *)obj)->win; if (win == INVALID_WINDOW_VALUE) scheme_signal_error(_("window is invalid")); return win; } int mzthreads_allowed(void) { return mz_threads_allow; } static int line_in_range(linenr_T lnum, buf_T *buf) { return (lnum > 0 && lnum <= buf->b_ml.ml_line_count); } static void check_line_range(linenr_T lnum, buf_T *buf) { if (!line_in_range(lnum, buf)) scheme_signal_error(_("linenr out of range")); } /* * Check if deleting lines made the cursor position invalid * (or you'll get msg from Vim about invalid linenr). * Changed the lines from "lo" to "hi" and added "extra" lines (negative if * deleted). Got from if_python.c */ static void mz_fix_cursor(int lo, int hi, int extra) { if (curwin->w_cursor.lnum >= lo) { /* Adjust the cursor position if it's in/after the changed * lines. */ if (curwin->w_cursor.lnum >= hi) { curwin->w_cursor.lnum += extra; check_cursor_col(); } else if (extra < 0) { curwin->w_cursor.lnum = lo; check_cursor(); } else check_cursor_col(); changed_cline_bef_curs(); } invalidate_botline(); } static Vim_Prim prims[]= { /* * Buffer-related commands */ {get_buffer_line, "get-buff-line", 1, 2}, {set_buffer_line, "set-buff-line", 2, 3}, {get_buffer_line_list, "get-buff-line-list", 2, 3}, {get_buffer_name, "get-buff-name", 0, 1}, {get_buffer_num, "get-buff-num", 0, 1}, {get_buffer_size, "get-buff-size", 0, 1}, {set_buffer_line_list, "set-buff-line-list", 3, 4}, {insert_buffer_line_list, "insert-buff-line-list", 2, 3}, {get_curr_buffer, "curr-buff", 0, 0}, {get_buffer_count, "buff-count", 0, 0}, {get_next_buffer, "get-next-buff", 0, 1}, {get_prev_buffer, "get-prev-buff", 0, 1}, {mzscheme_open_buffer, "open-buff", 1, 1}, {get_buffer_by_name, "get-buff-by-name", 1, 1}, {get_buffer_by_num, "get-buff-by-num", 1, 1}, /* * Window-related commands */ {get_curr_win, "curr-win", 0, 0}, {get_window_count, "win-count", 0, 0}, {get_window_by_num, "get-win-by-num", 1, 1}, {get_window_num, "get-win-num", 0, 1}, {get_window_buffer, "get-win-buffer", 0, 1}, {get_window_height, "get-win-height", 0, 1}, {set_window_height, "set-win-height", 1, 2}, #ifdef FEAT_VERTSPLIT {get_window_width, "get-win-width", 0, 1}, {set_window_width, "set-win-width", 1, 2}, #endif {get_cursor, "get-cursor", 0, 1}, {set_cursor, "set-cursor", 1, 2}, {get_window_list, "get-win-list", 0, 1}, /* * Vim-related commands */ {vim_command, "command", 1, 1}, {vim_eval, "eval", 1, 1}, {get_range_start, "range-start", 0, 0}, {get_range_end, "range-end", 0, 0}, {mzscheme_beep, "beep", 0, 0}, {get_option, "get-option", 1, 2}, {set_option, "set-option", 1, 2}, /* * small utilities */ {vim_bufferp, "buff?", 1, 1}, {vim_windowp, "win?", 1, 1}, {vim_buffer_validp, "buff-valid?", 1, 1}, {vim_window_validp, "win-valid?", 1, 1} }; /* return MzScheme wrapper for curbuf */ static vim_mz_buffer * get_vim_curr_buffer(void) { if (curbuf->b_mzscheme_ref == NULL) return (vim_mz_buffer *)buffer_new(curbuf); else return (vim_mz_buffer *)curbuf->b_mzscheme_ref; } /* return MzScheme wrapper for curwin */ static vim_mz_window * get_vim_curr_window(void) { if (curwin->w_mzscheme_ref == NULL) return (vim_mz_window *)window_new(curwin); else return (vim_mz_window *)curwin->w_mzscheme_ref; } static void make_modules() { int i; Scheme_Env *mod = NULL; Scheme_Object *vimext_symbol = NULL; Scheme_Object *closed_prim = NULL; MZ_GC_DECL_REG(3); MZ_GC_VAR_IN_REG(0, mod); MZ_GC_VAR_IN_REG(1, vimext_symbol); MZ_GC_VAR_IN_REG(2, closed_prim); MZ_GC_REG(); vimext_symbol = scheme_intern_symbol("vimext"); MZ_GC_CHECK(); mod = scheme_primitive_module(vimext_symbol, environment); MZ_GC_CHECK(); /* all prims made closed so they can access their own names */ for (i = 0; i < (int)(sizeof(prims)/sizeof(prims[0])); i++) { Vim_Prim *prim = prims + i; closed_prim = scheme_make_closed_prim_w_arity(prim->prim, prim, prim->name, prim->mina, prim->maxa); scheme_add_global(prim->name, closed_prim, mod); MZ_GC_CHECK(); } scheme_finish_primitive_module(mod); MZ_GC_CHECK(); MZ_GC_UNREG(); } #ifdef HAVE_SANDBOX static Scheme_Object *M_write = NULL; static Scheme_Object *M_read = NULL; static Scheme_Object *M_execute = NULL; static Scheme_Object *M_delete = NULL; static void sandbox_check(void) { if (sandbox) raise_vim_exn(_("not allowed in the Vim sandbox")); } /* security guards to force Vim's sandbox restrictions on MzScheme level */ static Scheme_Object * sandbox_file_guard(int argc UNUSED, Scheme_Object **argv) { if (sandbox) { Scheme_Object *requested_access = argv[2]; if (M_write == NULL) { MZ_REGISTER_STATIC(M_write); M_write = scheme_intern_symbol("write"); MZ_GC_CHECK(); } if (M_read == NULL) { MZ_REGISTER_STATIC(M_read); M_read = scheme_intern_symbol("read"); MZ_GC_CHECK(); } if (M_execute == NULL) { MZ_REGISTER_STATIC(M_execute); M_execute = scheme_intern_symbol("execute"); MZ_GC_CHECK(); } if (M_delete == NULL) { MZ_REGISTER_STATIC(M_delete); M_delete = scheme_intern_symbol("delete"); MZ_GC_CHECK(); } while (!SCHEME_NULLP(requested_access)) { Scheme_Object *item = SCHEME_CAR(requested_access); if (scheme_eq(item, M_write) || scheme_eq(item, M_read) || scheme_eq(item, M_execute) || scheme_eq(item, M_delete)) { raise_vim_exn(_("not allowed in the Vim sandbox")); } requested_access = SCHEME_CDR(requested_access); } } return scheme_void; } static Scheme_Object * sandbox_network_guard(int argc UNUSED, Scheme_Object **argv UNUSED) { return scheme_void; } #endif #endif
zyz2011-vim
src/if_mzsch.c
C
gpl2
92,966
#! /bin/sh # # osdef.sh -- copy osdef.h.in to osdef.h while removing declarations # found in the system header files. Caution: weird sed magic going on here. # Warnings are printed if sed did not survive. # # (C) Michael Schroeder, Juergen Weigert # # osdef.h.in has been split into osdef1.h.in and osdef2.h.in, because some # sed's could not handle the amount of commands (is 50 commands the limit?). # # 31.10.95 jw. if test -z "$CC"; then CC=cc fi if test -z "$srcdir"; then srcdir=. fi rm -f core* *.core cat << EOF > osdef0.c #ifndef __APPLE__ # define select select_declared_wrong #endif #define tgetstr tgetstr_declared_wrong #include "auto/config.h" #include "os_unix.h" /* bring in most header files, more follow below */ #include "os_unixx.h" /* bring in header files for os_unix.c */ #ifdef HAVE_TERMCAP_H # include <termcap.h> /* only for term.c */ #endif #ifdef HAVE_FCNTL_H # include <fcntl.h> /* only used in a few files */ #endif #ifdef HAVE_SYS_STATFS_H # include <sys/types.h> # include <sys/statfs.h> /* only for memfile.c */ #endif #ifdef HAVE_X11 # include <X11/Intrinsic.h> #endif EOF # Mac uses precompiled headers, but we need real headers here. case `uname` in Darwin) $CC -I. -I$srcdir -E -no-cpp-precomp osdef0.c >osdef0.cc;; *) $CC -I. -I$srcdir -E osdef0.c >osdef0.cc;; esac # insert a space in front of each line, so that a function name at the # start of the line is matched with "[)*, ]\1[ (]" sed < osdef0.cc -e '/\(..*\)/s// \1/' > osdef0.ccc sed < $srcdir/osdef1.h.in -n -e '/^extern/s@.*[)* ][)* ]*\([a-zA-Z_][a-zA-Z0-9_]*\) __ARGS.*@/[)*, ][(]*\1[)]*[ (]/i\\\ \\/\\[^a-zA-Z_\\]\1 __ARGS\\/d@p' > osdef11.sed sed < $srcdir/osdef2.h.in -n -e '/^extern/s@.*[)* ][)* ]*\([a-zA-Z_][a-zA-Z0-9_]*\) __ARGS.*@/[)*, ][(]*\1[)]*[ (]/i\\\ \\/\\[^a-zA-Z_\\]\1 __ARGS\\/d@p' > osdef21.sed cat << EOF > osdef2.sed 1i\\ /* 1i\\ * osdef.h is automagically created from osdef?.h.in by osdef.sh -- DO NOT EDIT 1i\\ */ EOF cat osdef0.ccc | sed -n -f osdef11.sed >> osdef2.sed sed -f osdef2.sed < $srcdir/osdef1.h.in > auto/osdef.h cat osdef0.ccc | sed -n -f osdef21.sed > osdef2.sed sed -f osdef2.sed < $srcdir/osdef2.h.in >> auto/osdef.h rm osdef0.c osdef0.cc osdef0.ccc osdef11.sed osdef21.sed osdef2.sed if test -f core*; then file core* echo " Sorry, your sed is broken. Call the system administrator." echo " Meanwhile, you may try to compile Vim with an empty osdef.h file." echo " If you compiler complains about missing prototypes, move the needed" echo " ones from osdef1.h.in and osdef2.h.in to osdef.h." exit 1 fi cat $srcdir/osdef1.h.in $srcdir/osdef2.h.in >osdefX.h.in if eval test "`diff auto/osdef.h osdefX.h.in | wc -l`" -eq 4; then echo " Hmm, sed is very pessimistic about your system header files." echo " But it did not dump core -- strange! Let's continue carefully..." echo " If this fails, you may want to remove offending lines from osdef.h" echo " or try with an empty osdef.h file, if your compiler can do without" echo " function declarations." fi rm osdefX.h.in
zyz2011-vim
src/osdef.sh
Shell
gpl2
3,081
#define IDR_VIM 150 #define IDR_VIM_ERROR 151 #define IDR_VIM_ALERT 152 #define IDR_VIM_INFO 153 #define IDR_VIM_QUESTION 154 #define IDR_ICOBUDDYBASE 200 #define IDR_ICOBUDDY_DEF1 (IDR_ICOBUDDYBASE + 3) #define IDR_ICOBUDDY_DEF2 (IDR_ICOBUDDYBASE + 0) #define IDR_ICOBUDDY_DEF3 (IDR_ICOBUDDYBASE + 1) #define IDR_ICOBUDDY_DEF4 (IDR_ICOBUDDYBASE + 2) #define IDR_ICOBUDDY_GRIN (IDR_ICOBUDDYBASE + 4) #define IDR_ICOBUDDY_ALARM (IDR_ICOBUDDYBASE + 5)
zyz2011-vim
src/guiw16rc.h
C
gpl2
469
# # Makefile for VIM on OS/2 using EMX vim:ts=8:sw=8:tw=78 # # Created by: Paul Slootman # ### This Makefile has been successfully tested on these systems. ### Check the (*) column for remarks, listed below. ### Later code changes may cause small problems, otherwise Vim is supposed to ### compile and run without problems. ### Just to show that this is just like the Unix version! #system: configurations: version (*) tested by: #------------- ------------------------ ------- - ---------- #OS/2 Warp HPFS gcc-2.7.2+emx-0.9b -GUI 4.5 Paul Slootman #OS/2 FAT gcc-2.6.3+emx -GUI 4.5 Karsten Sievert #>>>>> choose options: ### See feature.h for a list of optionals. ### Any other defines can be included here. DEFINES = -DUSE_SYSTEM=1 #>>>>> name of the compiler and linker, name of lib directory CC = gcc #>>>>> end of choices ### Name of target(s) TARGET = vim.exe ### Names of the tools that are also made TOOLS = xxd/xxd.exe tee/tee.exe ########################################################################### INCL = vim.h globals.h option.h keymap.h macros.h ascii.h term.h os_unix.h structs.h os_os2_cfg.h CFLAGS = -O2 -fno-strength-reduce -DOS2 -Wall -Iproto $(DEFINES) OBJ = \ blowfish.o \ buffer.o \ charset.o \ diff.o \ digraph.o \ edit.o \ eval.o \ ex_cmds.o \ ex_cmds2.o \ ex_docmd.o \ ex_eval.o \ ex_getln.o \ fileio.o \ fold.o \ getchar.o \ hardcopy.o \ hashtab.o \ main.o \ mark.o \ memfile.o \ memline.o \ menu.o \ message.o \ misc1.o \ misc2.o \ move.o \ mbyte.o \ normal.o \ ops.o \ option.o \ popupmnu.o \ quickfix.o \ regexp.o \ screen.o \ search.o \ sha256.o \ spell.o \ syntax.o \ tag.o \ term.o \ ui.o \ undo.o \ window.o \ os_unix.o LIBS = -ltermcap # Default target is making the executable all: $(TARGET) $(TOOLS) # Link the target for normal use LFLAGS = -Zcrtdll -s -o $(TARGET) $(LIBS) $(TARGET): $(OBJ) version.c version.h $(CC) $(CFLAGS) version.c $(OBJ) $(LFLAGS) xxd/xxd.exe: xxd/xxd.c cd xxd & $(MAKE) -f Make_os2.mak tee/tee.exe: tee/tee.c cd tee & $(MAKE) -f Makefile test: cd testdir & $(MAKE) -f Make_os2.mak clean: -del *.o -del *.exe -del *.~ *~ *.bak cd xxd & $(MAKE) -f Make_os2.mak clean cd tee & $(MAKE) -f Makefile clean ########################################################################### os_unix.o: os_unix.c $(INCL) blowfish.o: blowfish.c $(INCL) buffer.o: buffer.c $(INCL) charset.o: charset.c $(INCL) diff.o: diff.c $(INCL) digraph.o: digraph.c $(INCL) edit.o: edit.c $(INCL) eval.o: eval.c $(INCL) ex_cmds.o: ex_cmds.c $(INCL) ex_cmds2.o: ex_cmds2.c $(INCL) ex_docmd.o: ex_docmd.c $(INCL) ex_cmds.h ex_eval.o: ex_eval.c $(INCL) ex_cmds.h ex_getln.o: ex_getln.c $(INCL) fileio.o: fileio.c $(INCL) fold.o: fold.c $(INCL) getchar.o: getchar.c $(INCL) hardcopy.o: hardcopy.c $(INCL) hashtab.o: hashtab.c $(INCL) main.o: main.c $(INCL) mark.o: mark.c $(INCL) memfile.o: memfile.c $(INCL) memline.o: memline.c $(INCL) menu.o: menu.c $(INCL) message.o: message.c $(INCL) misc1.o: misc1.c $(INCL) misc2.o: misc2.c $(INCL) move.o: move.c $(INCL) mbyte.o: mbyte.c $(INCL) normal.o: normal.c $(INCL) ops.o: ops.c $(INCL) option.o: option.c $(INCL) popupmnu.o: popupmnu.c $(INCL) quickfix.o: quickfix.c $(INCL) regexp.o: regexp.c $(INCL) screen.o: screen.c $(INCL) search.o: search.c $(INCL) sha256.o: sha256.c $(INCL) spell.o: spell.c $(INCL) syntax.o: syntax.c $(INCL) tag.o: tag.c $(INCL) term.o: term.c $(INCL) ui.o: ui.c $(INCL) undo.o: undo.c $(INCL) window.o: window.c $(INCL)
zyz2011-vim
src/Make_os2.mak
Makefile
gpl2
3,609
/* vi:set ts=8 sts=4 sw=4: * * if_sniff.c Interface between Vim and SNiFF+ * * See README.txt for an overview of the Vim source code. */ #include "vim.h" #ifdef WIN32 # include <stdio.h> # include <process.h> # include <string.h> # include <assert.h> #else # ifdef FEAT_GUI_X11 # include "gui_x11.pro" # endif # include "os_unixx.h" #endif static int sniffemacs_pid; int fd_from_sniff; int sniff_connected = 0; int sniff_request_waiting = 0; int want_sniff_request = 0; #define MAX_REQUEST_LEN 512 #define NEED_SYMBOL 2 #define EMPTY_SYMBOL 4 #define NEED_FILE 8 #define SILENT 16 #define DISCONNECT 32 #define CONNECT 64 #define RQ_NONE 0 #define RQ_SIMPLE 1 #define RQ_CONTEXT NEED_FILE + NEED_SYMBOL #define RQ_SCONTEXT NEED_FILE + NEED_SYMBOL + EMPTY_SYMBOL #define RQ_NOSYMBOL NEED_FILE #define RQ_SILENT RQ_NOSYMBOL + SILENT #define RQ_CONNECT RQ_NONE + CONNECT #define RQ_DISCONNECT RQ_SIMPLE + DISCONNECT struct sn_cmd { char *cmd_name; char cmd_code; char *cmd_msg; int cmd_type; }; struct sn_cmd_list { struct sn_cmd* sniff_cmd; struct sn_cmd_list* next_cmd; }; static struct sn_cmd sniff_cmds[] = { { "toggle", 'e', N_("Toggle implementation/definition"),RQ_SCONTEXT }, { "superclass", 's', N_("Show base class of"), RQ_CONTEXT }, { "overridden", 'm', N_("Show overridden member function"),RQ_SCONTEXT }, { "retrieve-file", 'r', N_("Retrieve from file"), RQ_CONTEXT }, { "retrieve-project",'p', N_("Retrieve from project"), RQ_CONTEXT }, { "retrieve-all-projects", 'P', N_("Retrieve from all projects"), RQ_CONTEXT }, { "retrieve-next", 'R', N_("Retrieve"), RQ_CONTEXT }, { "goto-symbol", 'g', N_("Show source of"), RQ_CONTEXT }, { "find-symbol", 'f', N_("Find symbol"), RQ_CONTEXT }, { "browse-class", 'w', N_("Browse class"), RQ_CONTEXT }, { "hierarchy", 't', N_("Show class in hierarchy"), RQ_CONTEXT }, { "restr-hier", 'T', N_("Show class in restricted hierarchy"),RQ_CONTEXT }, { "xref-to", 'x', N_("Xref refers to"), RQ_CONTEXT }, { "xref-by", 'X', N_("Xref referred by"), RQ_CONTEXT }, { "xref-has", 'c', N_("Xref has a"), RQ_CONTEXT }, { "xref-used-by", 'C', N_("Xref used by"), RQ_CONTEXT }, { "show-docu", 'd', N_("Show docu of"), RQ_CONTEXT }, { "gen-docu", 'D', N_("Generate docu for"), RQ_CONTEXT }, { "connect", 'y', NULL, RQ_CONNECT }, { "disconnect", 'q', NULL, RQ_DISCONNECT }, { "font-info", 'z', NULL, RQ_SILENT }, { "update", 'u', NULL, RQ_SILENT }, { NULL, '\0', NULL, 0} }; static char *SniffEmacs[2] = {"sniffemacs", (char *)NULL}; /* Yes, Emacs! */ static int fd_to_sniff; static int sniff_will_disconnect = 0; static char msg_sniff_disconnect[] = N_("Cannot connect to SNiFF+. Check environment (sniffemacs must be found in $PATH).\n"); static char sniff_rq_sep[] = " "; static struct sn_cmd_list *sniff_cmd_ext = NULL; /* Initializing vim commands * executed each time vim connects to Sniff */ static char *init_cmds[]= { "augroup sniff", "autocmd BufWritePost * sniff update", "autocmd BufReadPost * sniff font-info", "autocmd VimLeave * sniff disconnect", "augroup END", "let g:sniff_connected = 1", "if ! exists('g:sniff_mappings_sourced')|" "if ! exists('g:sniff_mappings')|" "if exists('$SNIFF_DIR4')|" "let g:sniff_mappings='$SNIFF_DIR4/config/integrations/vim/sniff.vim'|" "else|" "let g:sniff_mappings='$SNIFF_DIR/config/sniff.vim'|" "endif|" "endif|" "let g:sniff_mappings=expand(g:sniff_mappings)|" "if filereadable(g:sniff_mappings)|" "execute 'source' g:sniff_mappings|" "let g:sniff_mappings_sourced=1|" "endif|" "endif", NULL }; /*-------- Function Prototypes ----------------------------------*/ static int ConnectToSniffEmacs __ARGS((void)); static void sniff_connect __ARGS((void)); static void HandleSniffRequest __ARGS((char* buffer)); static int get_request __ARGS((int fd, char *buf, int maxlen)); static void WriteToSniff __ARGS((char *str)); static void SendRequest __ARGS((struct sn_cmd *command, char* symbol)); static void vi_msg __ARGS((char *)); static void vi_error_msg __ARGS((char *)); static char *vi_symbol_under_cursor __ARGS((void)); static void vi_open_file __ARGS((char *)); static char *vi_buffer_name __ARGS((void)); static buf_T *vi_find_buffer __ARGS((char *)); static void vi_exec_cmd __ARGS((char *)); static void vi_set_cursor_pos __ARGS((long char_nr)); static long vi_cursor_pos __ARGS((void)); /* debug trace */ #if 0 static FILE* _tracefile = NULL; #define SNIFF_TRACE_OPEN(file) if (!_tracefile) _tracefile = fopen(file, "w") #define SNIFF_TRACE(msg) fprintf(_tracefile, msg); fflush(_tracefile); #define SNIFF_TRACE1(msg, arg) fprintf(_tracefile, msg,arg); fflush(_tracefile); #define SNIFF_TRACE_CLOSE fclose(_tracefile); _tracefile=NULL; #else #define SNIFF_TRACE_OPEN(file) #define SNIFF_TRACE(msg) #define SNIFF_TRACE1(msg, arg) #define SNIFF_TRACE_CLOSE #endif /*-------- Windows Only Declarations -----------------------------*/ #ifdef WIN32 static int sniff_request_processed=1; static HANDLE sniffemacs_handle=NULL; static HANDLE readthread_handle=NULL; static HANDLE handle_to_sniff=NULL; static HANDLE handle_from_sniff=NULL; struct sniffBufNode { struct sniffBufNode *next; int bufLen; char buf[MAX_REQUEST_LEN]; }; static struct sniffBufNode *sniffBufStart=NULL; static struct sniffBufNode *sniffBufEnd=NULL; static HANDLE hBufferMutex=NULL; # ifdef FEAT_GUI_W32 extern HWND s_hwnd; /* gvim's Window handle */ # endif /* * some helper functions for Windows port only */ static HANDLE ExecuteDetachedProgram(char *szBinary, char *szCmdLine, HANDLE hStdInput, HANDLE hStdOutput) { BOOL bResult; DWORD nError; PROCESS_INFORMATION aProcessInformation; PROCESS_INFORMATION *pProcessInformation= &aProcessInformation; STARTUPINFO aStartupInfo; STARTUPINFO *pStartupInfo= &aStartupInfo; DWORD dwCreationFlags= 0; char szPath[512]; HINSTANCE hResult; hResult = FindExecutable(szBinary, ".", szPath); if ((int)hResult <= 32) { /* can't find the exe file */ return NULL; } ZeroMemory(pStartupInfo, sizeof(*pStartupInfo)); pStartupInfo->dwFlags= STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES; pStartupInfo->hStdInput = hStdInput; pStartupInfo->hStdOutput = hStdOutput; pStartupInfo->wShowWindow= SW_HIDE; pStartupInfo->cb = sizeof(STARTUPINFO); bResult= CreateProcess( szPath, szCmdLine, NULL, /* security attr for process */ NULL, /* security attr for primary thread */ TRUE, /* DO inherit stdin and stdout */ dwCreationFlags, /* creation flags */ NULL, /* environment */ ".", /* current directory */ pStartupInfo, /* startup info: NULL crashes */ pProcessInformation /* process information: NULL crashes */ ); nError= GetLastError(); if (bResult) { CloseHandle(pProcessInformation->hThread); CloseHandle(hStdInput); CloseHandle(hStdOutput); return(pProcessInformation->hProcess); } else return(NULL); } /* * write to the internal Thread / Thread communications buffer. * Return TRUE if successful, FALSE else. */ static BOOL writeToBuffer(char *msg, int len) { DWORD dwWaitResult; /* Request ownership of mutex. */ struct sniffBufNode *bn; int bnSize; SNIFF_TRACE1("writeToBuffer %d\n", len); bnSize = sizeof(struct sniffBufNode) - MAX_REQUEST_LEN + len + 1; if (bnSize < 128) bnSize = 128; /* minimum length to avoid fragmentation */ bn = (struct sniffBufNode *)malloc(bnSize); if (!bn) return FALSE; memcpy(bn->buf, msg, len); bn->buf[len]='\0'; /* terminate CString for added safety */ bn->next = NULL; bn->bufLen = len; /* now, acquire a Mutex for adding the string to our linked list */ dwWaitResult = WaitForSingleObject( hBufferMutex, /* handle of mutex */ 1000L); /* one-second time-out interval */ if (dwWaitResult == WAIT_OBJECT_0) { /* The thread got mutex ownership. */ if (sniffBufEnd) { sniffBufEnd->next = bn; sniffBufEnd = bn; } else sniffBufStart = sniffBufEnd = bn; /* Release ownership of the mutex object. */ if (! ReleaseMutex(hBufferMutex)) { /* Deal with error. */ } return TRUE; } /* Cannot get mutex ownership due to time-out or mutex object abandoned. */ free(bn); return FALSE; } /* * read from the internal Thread / Thread communications buffer. * Return TRUE if successful, FALSE else. */ static int ReadFromBuffer(char *buf, int maxlen) { DWORD dwWaitResult; /* Request ownership of mutex. */ int theLen; struct sniffBufNode *bn; dwWaitResult = WaitForSingleObject( hBufferMutex, /* handle of mutex */ 1000L); /* one-second time-out interval */ if (dwWaitResult == WAIT_OBJECT_0) { if (!sniffBufStart) { /* all pending Requests Processed */ theLen = 0; } else { bn = sniffBufStart; theLen = bn->bufLen; SNIFF_TRACE1("ReadFromBuffer %d\n", theLen); if (theLen >= maxlen) { /* notify the user of buffer overflow? */ theLen = maxlen-1; } memcpy(buf, bn->buf, theLen); buf[theLen] = '\0'; if (! (sniffBufStart = bn->next)) { sniffBufEnd = NULL; sniff_request_processed = 1; } free(bn); } if (! ReleaseMutex(hBufferMutex)) { /* Deal with error. */ } return theLen; } /* Cannot get mutex ownership due to time-out or mutex object abandoned. */ return -1; } /* on Win32, a separate Thread reads the input pipe. get_request is not needed here. */ static void __cdecl SniffEmacsReadThread(void *dummy) { static char ReadThreadBuffer[MAX_REQUEST_LEN]; int ReadThreadLen=0; int result=0; int msgLen=0; char *msgStart, *msgCur; SNIFF_TRACE("begin thread\n"); /* Read from the pipe to SniffEmacs */ while (sniff_connected) { if (!ReadFile(handle_from_sniff, ReadThreadBuffer + ReadThreadLen, /* acknowledge rest in buffer */ MAX_REQUEST_LEN - ReadThreadLen, &result, NULL)) { DWORD err = GetLastError(); result = -1; } if (result < 0) { /* probably sniffemacs died... log the Error? */ sniff_disconnect(1); } else if (result > 0) { ReadThreadLen += result-1; /* total length of valid chars */ for(msgCur=msgStart=ReadThreadBuffer; ReadThreadLen > 0; msgCur++, ReadThreadLen--) { if (*msgCur == '\0' || *msgCur == '\r' || *msgCur == '\n') { msgLen = msgCur-msgStart; /* don't add the CR/LF chars */ if (msgLen > 0) writeToBuffer(msgStart, msgLen); msgStart = msgCur + 1; /* over-read single CR/LF chars */ } } /* move incomplete message to beginning of buffer */ ReadThreadLen = msgCur - msgStart; if (ReadThreadLen > 0) mch_memmove(ReadThreadBuffer, msgStart, ReadThreadLen); if (sniff_request_processed) { /* notify others that new data has arrived */ sniff_request_processed = 0; sniff_request_waiting = 1; #ifdef FEAT_GUI_W32 PostMessage(s_hwnd, WM_USER, (WPARAM)0, (LPARAM)0); #endif } } } SNIFF_TRACE("end thread\n"); } #endif /* WIN32 */ /*-------- End of Windows Only Declarations ------------------------*/ /* ProcessSniffRequests * Function that should be called from outside * to process the waiting sniff requests */ void ProcessSniffRequests() { static char buf[MAX_REQUEST_LEN]; int len; while (sniff_connected) { #ifdef WIN32 len = ReadFromBuffer(buf, sizeof(buf)); #else len = get_request(fd_from_sniff, buf, sizeof(buf)); #endif if (len < 0) { vi_error_msg(_("E274: Sniff: Error during read. Disconnected")); sniff_disconnect(1); break; } else if (len > 0) HandleSniffRequest( buf ); else break; } if (sniff_will_disconnect) /* Now the last msg has been processed */ sniff_disconnect(1); } static struct sn_cmd * find_sniff_cmd(cmd) char *cmd; { struct sn_cmd *sniff_cmd = NULL; int i; for(i=0; sniff_cmds[i].cmd_name; i++) { if (!strcmp(cmd, sniff_cmds[i].cmd_name)) { sniff_cmd = &sniff_cmds[i]; break; } } if (!sniff_cmd) { struct sn_cmd_list *list = sniff_cmd_ext; while(list) { if (!strcmp(cmd, list->sniff_cmd->cmd_name)) { sniff_cmd = list->sniff_cmd; break; } list = list->next_cmd; } } return sniff_cmd; } static int add_sniff_cmd(cmd, def, msg) char *cmd; char *def; char *msg; { int rc = 0; if (def != NULL && def[0] != NUL && find_sniff_cmd(cmd) == NULL) { struct sn_cmd_list *list = sniff_cmd_ext; struct sn_cmd *sniff_cmd = (struct sn_cmd*)malloc(sizeof(struct sn_cmd)); struct sn_cmd_list *cmd_node = (struct sn_cmd_list*)malloc(sizeof(struct sn_cmd_list)); int rq_type = 0; /* unescape message text */ char *p = msg; char *end = p+strlen(msg); while(*p) { if (*p == '\\') mch_memmove(p,p+1,end-p); p++; } SNIFF_TRACE1("request name = %s\n",cmd); SNIFF_TRACE1("request def = %s\n",def); SNIFF_TRACE1("request msg = %s\n",msg); while(list && list->next_cmd) list = list->next_cmd; if (!list) sniff_cmd_ext = cmd_node; else list->next_cmd = cmd_node; sniff_cmd->cmd_name = cmd; sniff_cmd->cmd_code = def[0]; sniff_cmd->cmd_msg = msg; switch(def[1]) { case 'f': rq_type = RQ_NOSYMBOL; break; case 's': rq_type = RQ_CONTEXT; break; case 'S': rq_type = RQ_SCONTEXT; break; default: rq_type = RQ_SIMPLE; break; } sniff_cmd->cmd_type = rq_type; cmd_node->sniff_cmd = sniff_cmd; cmd_node->next_cmd = NULL; rc = 1; } return rc; } /* ex_sniff * Handle ":sniff" command */ void ex_sniff(eap) exarg_T *eap; { char_u *arg = eap->arg; char_u *symbol = NULL; char_u *cmd = NULL; SNIFF_TRACE_OPEN("if_sniff.log"); if (ends_excmd(*arg)) /* no request: print available commands */ { int i; msg_start(); msg_outtrans_attr((char_u *)"-- SNiFF+ commands --", hl_attr(HLF_T)); for(i=0; sniff_cmds[i].cmd_name; i++) { msg_putchar('\n'); msg_outtrans((char_u *)":sniff "); msg_outtrans((char_u *)sniff_cmds[i].cmd_name); } msg_putchar('\n'); msg_outtrans((char_u *)_("SNiFF+ is currently ")); if (!sniff_connected) msg_outtrans((char_u *)_("not ")); msg_outtrans((char_u *)_("connected")); msg_end(); } else /* extract command name and symbol if present */ { symbol = skiptowhite(arg); cmd = vim_strnsave(arg, (int)(symbol-arg)); symbol = skipwhite(symbol); if (ends_excmd(*symbol)) symbol = NULL; if (!strcmp((char *)cmd, "addcmd")) { char_u *def = skiptowhite(symbol); char_u *name = vim_strnsave(symbol, (int)(def-symbol)); char_u *msg; def = skipwhite(def); msg = skiptowhite(def); def = vim_strnsave(def, (int)(msg-def)); msg = skipwhite(msg); if (ends_excmd(*msg)) msg = vim_strsave(name); else msg = vim_strnsave(msg, (int)(skiptowhite_esc(msg)-msg)); if (!add_sniff_cmd((char*)name, (char*)def, (char*)msg)) { vim_free(msg); vim_free(def); vim_free(name); } } else { struct sn_cmd* sniff_cmd = find_sniff_cmd((char*)cmd); if (sniff_cmd) SendRequest(sniff_cmd, (char *)symbol); else EMSG2(_("E275: Unknown SNiFF+ request: %s"), cmd); } vim_free(cmd); } } static void sniff_connect() { if (sniff_connected) return; if (ConnectToSniffEmacs()) vi_error_msg(_("E276: Error connecting to SNiFF+")); else { int i; for (i = 0; init_cmds[i]; i++) vi_exec_cmd(init_cmds[i]); } } void sniff_disconnect(immediately) int immediately; { if (!sniff_connected) return; if (immediately) { vi_exec_cmd("augroup sniff"); vi_exec_cmd("au!"); vi_exec_cmd("augroup END"); vi_exec_cmd("unlet g:sniff_connected"); sniff_connected = 0; want_sniff_request = 0; sniff_will_disconnect = 0; #ifdef FEAT_GUI if (gui.in_use) gui_mch_wait_for_chars(0L); #endif #ifdef WIN32 while(sniffBufStart != NULL) { struct sniffBufNode *node = sniffBufStart; sniffBufStart = sniffBufStart->next; free(node); } sniffBufStart = sniffBufEnd = NULL; sniff_request_processed = 1; CloseHandle(handle_to_sniff); CloseHandle(handle_from_sniff); WaitForSingleObject(sniffemacs_handle, 1000L); CloseHandle(sniffemacs_handle); sniffemacs_handle = NULL; WaitForSingleObject(readthread_handle, 1000L); readthread_handle = NULL; CloseHandle(hBufferMutex); hBufferMutex = NULL; SNIFF_TRACE_CLOSE; #else close(fd_to_sniff); close(fd_from_sniff); wait(NULL); #endif } else { #ifdef WIN32 _sleep(2); if (!sniff_request_processed) ProcessSniffRequests(); #else sleep(2); /* Incoming msg could disturb edit */ #endif sniff_will_disconnect = 1; /* We expect disconnect msg in 2 secs */ } } /* ConnectToSniffEmacs * Connect to Sniff: returns 1 on error */ static int ConnectToSniffEmacs() { #ifdef WIN32 /* Windows Version of the Code */ HANDLE ToSniffEmacs[2], FromSniffEmacs[2]; SECURITY_ATTRIBUTES sa; sa.nLength = sizeof(sa); sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = TRUE; if (! CreatePipe(&ToSniffEmacs[0], &ToSniffEmacs[1], &sa, 0)) return 1; if (! CreatePipe(&FromSniffEmacs[0], &FromSniffEmacs[1], &sa, 0)) return 1; sniffemacs_handle = ExecuteDetachedProgram(SniffEmacs[0], SniffEmacs[0], ToSniffEmacs[0], FromSniffEmacs[1]); if (sniffemacs_handle) { handle_to_sniff = ToSniffEmacs[1]; handle_from_sniff = FromSniffEmacs[0]; sniff_connected = 1; hBufferMutex = CreateMutex( NULL, /* no security attributes */ FALSE, /* initially not owned */ "SniffReadBufferMutex"); /* name of mutex */ if (hBufferMutex == NULL) { /* Check for error. */ } readthread_handle = (HANDLE)_beginthread(SniffEmacsReadThread, 0, NULL); return 0; } else { /* error in spawn() */ return 1; } #else /* UNIX Version of the Code */ int ToSniffEmacs[2], FromSniffEmacs[2]; if (pipe(ToSniffEmacs) != 0) return 1; if (pipe(FromSniffEmacs) != 0) return 1; /* fork */ if ((sniffemacs_pid=fork()) == 0) { /* child */ /* prepare communication pipes */ close(ToSniffEmacs[1]); close(FromSniffEmacs[0]); dup2(ToSniffEmacs[0],fileno(stdin)); /* write to ToSniffEmacs[1] */ dup2(FromSniffEmacs[1],fileno(stdout));/* read from FromSniffEmacs[0] */ close(ToSniffEmacs[0]); close(FromSniffEmacs[1]); /* start sniffemacs */ execvp (SniffEmacs[0], SniffEmacs); { /* FILE *out = fdopen(FromSniffEmacs[1], "w"); */ sleep(1); fputs(_(msg_sniff_disconnect), stdout); fflush(stdout); sleep(3); #ifdef FEAT_GUI if (gui.in_use) gui_exit(1); #endif exit(1); } return 1; } else if (sniffemacs_pid > 0) { /* parent process */ close(ToSniffEmacs[0]); fd_to_sniff = ToSniffEmacs[1]; close(FromSniffEmacs[1]); fd_from_sniff = FromSniffEmacs[0]; sniff_connected = 1; return 0; } else /* error in fork() */ return 1; #endif /* UNIX Version of the Code */ } /* HandleSniffRequest * Handle one request from SNiFF+ */ static void HandleSniffRequest(buffer) char *buffer; { char VICommand[MAX_REQUEST_LEN]; char command; char *arguments; char *token; char *argv[3]; int argc = 0; buf_T *buf; const char *SetTab = "set tabstop=%d"; const char *SelectBuf = "buf %s"; const char *DeleteBuf = "bd %s"; const char *UnloadBuf = "bun %s"; const char *GotoLine = "%d"; command = buffer[0]; arguments = &buffer[1]; token = strtok(arguments, sniff_rq_sep); while(argc <3) { if (token) { argv[argc] = (char*)vim_strsave((char_u *)token); token = strtok(0, sniff_rq_sep); } else argv[argc] = strdup(""); argc++; } switch (command) { case 'o' : /* visit file at char pos */ case 'O' : /* visit file at line number */ { char *file = argv[0]; int position = atoi(argv[1]); buf = vi_find_buffer(file); setpcmark(); /* insert current pos in jump list [mark.c]*/ if (!buf) vi_open_file(file); else if (buf!=curbuf) { vim_snprintf(VICommand, sizeof(VICommand), (char *)SelectBuf, file); vi_exec_cmd(VICommand); } if (command == 'o') vi_set_cursor_pos((long)position); else { vim_snprintf(VICommand, sizeof(VICommand), (char *)GotoLine, (int)position); vi_exec_cmd(VICommand); } checkpcmark(); /* [mark.c] */ #if defined(FEAT_GUI_X11) || defined(FEAT_GUI_W32) if (gui.in_use && !gui.in_focus) /* Raise Vim Window */ { # ifdef FEAT_GUI_W32 SetForegroundWindow(s_hwnd); # else extern Widget vimShell; XSetInputFocus(gui.dpy, XtWindow(vimShell), RevertToNone, CurrentTime); XRaiseWindow(gui.dpy, XtWindow(vimShell)); # endif } #endif break; } case 'p' : /* path of file has changed */ /* when changing from shared to private WS (checkout) */ { char *file = argv[0]; char *new_path = argv[1]; buf = vi_find_buffer(file); if (buf && !buf->b_changed) /* delete buffer only if not modified */ { vim_snprintf(VICommand, sizeof(VICommand), (char *)DeleteBuf, file); vi_exec_cmd(VICommand); } vi_open_file(new_path); break; } case 'w' : /* writability has changed */ /* Sniff sends request twice, * but only the last one is the right one */ { char *file = argv[0]; int writable = atoi(argv[1]); buf = vi_find_buffer(file); if (buf) { buf->b_p_ro = !writable; if (buf != curbuf) { buf->b_flags |= BF_CHECK_RO + BF_NEVERLOADED; if (writable && !buf->b_changed) { vim_snprintf(VICommand, sizeof(VICommand), (char *)UnloadBuf, file); vi_exec_cmd(VICommand); } } else if (writable && !buf->b_changed) { vi_exec_cmd("e"); } } break; } case 'h' : /* highlight info */ break; /* not implemented */ case 't' : /* Set tab width */ { int tab_width = atoi(argv[1]); if (tab_width > 0 && tab_width <= 16) { vim_snprintf(VICommand, sizeof(VICommand), (char *)SetTab, tab_width); vi_exec_cmd(VICommand); } break; } case '|': { /* change the request separator */ sniff_rq_sep[0] = arguments[0]; /* echo the request */ WriteToSniff(buffer); break; } case 'A' : /* Warning/Info msg */ vi_msg(arguments); if (!strncmp(arguments, "Disconnected", 12)) sniff_disconnect(1); /* unexpected disconnection */ break; case 'a' : /* Error msg */ vi_error_msg(arguments); if (!strncmp(arguments, "Cannot connect", 14)) sniff_disconnect(1); break; default : break; } while(argc) vim_free(argv[--argc]); } #ifndef WIN32 /* get_request * read string from fd up to next newline (excluding the nl), * returns length of string * 0 if no data available or no complete line * <0 on error */ static int get_request(fd, buf, maxlen) int fd; char *buf; int maxlen; { static char inbuf[1024]; static int pos = 0, bytes = 0; int len; #ifdef HAVE_SELECT struct timeval tval; fd_set rfds; FD_ZERO(&rfds); FD_SET(fd, &rfds); tval.tv_sec = 0; tval.tv_usec = 0; #else struct pollfd fds; fds.fd = fd; fds.events = POLLIN; #endif for (len = 0; len < maxlen; len++) { if (pos >= bytes) /* end of buffer reached? */ { #ifdef HAVE_SELECT if (select(fd + 1, &rfds, NULL, NULL, &tval) > 0) #else if (poll(&fds, 1, 0) > 0) #endif { pos = 0; bytes = read(fd, inbuf, sizeof(inbuf)); if (bytes <= 0) return bytes; } else { pos = pos-len; buf[0] = '\0'; return 0; } } if ((buf[len] = inbuf[pos++]) =='\n') break; } buf[len] = '\0'; return len; } #endif /* WIN32 */ static void SendRequest(command, symbol) struct sn_cmd *command; char *symbol; { int cmd_type = command->cmd_type; static char cmdstr[MAX_REQUEST_LEN]; static char msgtxt[MAX_REQUEST_LEN]; char *buffer_name = NULL; if (cmd_type == RQ_CONNECT) { sniff_connect(); return; } if (!sniff_connected && !(cmd_type & SILENT)) { vi_error_msg(_("E278: SNiFF+ not connected")); return; } if (cmd_type & NEED_FILE) { if (!curbuf->b_sniff) { if (!(cmd_type & SILENT)) vi_error_msg(_("E279: Not a SNiFF+ buffer")); return; } buffer_name = vi_buffer_name(); if (buffer_name == NULL) return; if (cmd_type & NEED_SYMBOL) { if (cmd_type & EMPTY_SYMBOL) symbol = " "; else if (!symbol && !(symbol = vi_symbol_under_cursor())) return; /* error msg already displayed */ } if (symbol) vim_snprintf(cmdstr, sizeof(cmdstr), "%c%s%s%ld%s%s\n", command->cmd_code, buffer_name, sniff_rq_sep, vi_cursor_pos(), sniff_rq_sep, symbol ); else vim_snprintf(cmdstr, sizeof(cmdstr), "%c%s\n", command->cmd_code, buffer_name); } else /* simple request */ { cmdstr[0] = command->cmd_code; cmdstr[1] = '\n'; cmdstr[2] = '\0'; } if (command->cmd_msg && !(cmd_type & SILENT)) { if ((cmd_type & NEED_SYMBOL) && !(cmd_type & EMPTY_SYMBOL)) { vim_snprintf(msgtxt, sizeof(msgtxt), "%s: %s", _(command->cmd_msg), symbol); vi_msg(msgtxt); } else vi_msg(_(command->cmd_msg)); } WriteToSniff(cmdstr); if (cmd_type & DISCONNECT) sniff_disconnect(0); } static void WriteToSniff(str) char *str; { int bytes; #ifdef WIN32 if (! WriteFile(handle_to_sniff, str, strlen(str), &bytes, NULL)) { DWORD err=GetLastError(); bytes = -1; } #else bytes = write(fd_to_sniff, str, strlen(str)); #endif if (bytes<0) { vi_msg(_("Sniff: Error during write. Disconnected")); sniff_disconnect(1); } } /*-------- vim helping functions --------------------------------*/ static void vi_msg(str) char *str; { if (str != NULL && *str != NUL) MSG((char_u *)str); } static void vi_error_msg(str) char *str; { if (str != NULL && *str != NUL) EMSG((char_u *)str); } static void vi_open_file(fname) char *fname; { ++no_wait_return; do_ecmd(0, (char_u *)fname, NULL, NULL, ECMD_ONE, ECMD_HIDE+ECMD_OLDBUF, curwin); curbuf->b_sniff = TRUE; --no_wait_return; /* [ex_docmd.c] */ } static buf_T * vi_find_buffer(fname) char *fname; { /* derived from buflist_findname() [buffer.c] */ buf_T *buf; for (buf = firstbuf; buf != NULL; buf = buf->b_next) if (buf->b_sfname != NULL && fnamecmp(fname, buf->b_sfname) == 0) return (buf); return NULL; } static char * vi_symbol_under_cursor() { int len; char *symbolp; char *p; static char sniff_symbol[256]; len = find_ident_under_cursor((char_u **)&symbolp, FIND_IDENT); /* [normal.c] */ if (len <= 0) return NULL; for (p=sniff_symbol; len; len--) *p++ = *symbolp++; *p = '\0'; return sniff_symbol; } static char * vi_buffer_name() { return (char *)curbuf->b_sfname; } static void vi_exec_cmd(vicmd) char *vicmd; { do_cmdline_cmd((char_u *)vicmd); /* [ex_docmd.c] */ } /* * Set cursor on character position * derived from cursor_pos_info() [buffer.c] */ static void vi_set_cursor_pos(char_pos) long char_pos; { linenr_T lnum; long char_count = 1; /* first position = 1 */ int line_size; int eol_size; if (char_pos == 0) { char_pos = 1; } if (get_fileformat(curbuf) == EOL_DOS) eol_size = 2; else eol_size = 1; for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum) { line_size = STRLEN(ml_get(lnum)) + eol_size; if (char_count+line_size > char_pos) break; char_count += line_size; } curwin->w_cursor.lnum = lnum; curwin->w_cursor.col = char_pos - char_count; } static long vi_cursor_pos() { linenr_T lnum; long char_count=1; /* sniff starts with pos 1 */ int line_size; int eol_size; if (curbuf->b_p_tx) eol_size = 2; else eol_size = 1; for (lnum = 1; lnum < curwin->w_cursor.lnum; ++lnum) { line_size = STRLEN(ml_get(lnum)) + eol_size; char_count += line_size; } return char_count + curwin->w_cursor.col; }
zyz2011-vim
src/if_sniff.c
C
gpl2
28,512
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * buffer.c: functions for dealing with the buffer structure */ /* * The buffer list is a double linked list of all buffers. * Each buffer can be in one of these states: * never loaded: BF_NEVERLOADED is set, only the file name is valid * not loaded: b_ml.ml_mfp == NULL, no memfile allocated * hidden: b_nwindows == 0, loaded but not displayed in a window * normal: loaded and displayed in a window * * Instead of storing file names all over the place, each file name is * stored in the buffer list. It can be referenced by a number. * * The current implementation remembers all file names ever used. */ #include "vim.h" #if defined(FEAT_CMDL_COMPL) || defined(FEAT_LISTCMDS) || defined(FEAT_EVAL) || defined(FEAT_PERL) static char_u *buflist_match __ARGS((regprog_T *prog, buf_T *buf)); # define HAVE_BUFLIST_MATCH static char_u *fname_match __ARGS((regprog_T *prog, char_u *name)); #endif static void buflist_setfpos __ARGS((buf_T *buf, win_T *win, linenr_T lnum, colnr_T col, int copy_options)); static wininfo_T *find_wininfo __ARGS((buf_T *buf, int skip_diff_buffer)); #ifdef UNIX static buf_T *buflist_findname_stat __ARGS((char_u *ffname, struct stat *st)); static int otherfile_buf __ARGS((buf_T *buf, char_u *ffname, struct stat *stp)); static int buf_same_ino __ARGS((buf_T *buf, struct stat *stp)); #else static int otherfile_buf __ARGS((buf_T *buf, char_u *ffname)); #endif #ifdef FEAT_TITLE static int ti_change __ARGS((char_u *str, char_u **last)); #endif static int append_arg_number __ARGS((win_T *wp, char_u *buf, int buflen, int add_file)); static void free_buffer __ARGS((buf_T *)); static void free_buffer_stuff __ARGS((buf_T *buf, int free_options)); static void clear_wininfo __ARGS((buf_T *buf)); #ifdef UNIX # define dev_T dev_t #else # define dev_T unsigned #endif #if defined(FEAT_SIGNS) static void insert_sign __ARGS((buf_T *buf, signlist_T *prev, signlist_T *next, int id, linenr_T lnum, int typenr)); static void buf_delete_signs __ARGS((buf_T *buf)); #endif #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX) static char *msg_loclist = N_("[Location List]"); static char *msg_qflist = N_("[Quickfix List]"); #endif #ifdef FEAT_AUTOCMD static char *e_auabort = N_("E855: Autocommands caused command to abort"); #endif /* * Open current buffer, that is: open the memfile and read the file into * memory. * Return FAIL for failure, OK otherwise. */ int open_buffer(read_stdin, eap, flags) int read_stdin; /* read file from stdin */ exarg_T *eap; /* for forced 'ff' and 'fenc' or NULL */ int flags; /* extra flags for readfile() */ { int retval = OK; #ifdef FEAT_AUTOCMD buf_T *old_curbuf; #endif /* * The 'readonly' flag is only set when BF_NEVERLOADED is being reset. * When re-entering the same buffer, it should not change, because the * user may have reset the flag by hand. */ if (readonlymode && curbuf->b_ffname != NULL && (curbuf->b_flags & BF_NEVERLOADED)) curbuf->b_p_ro = TRUE; if (ml_open(curbuf) == FAIL) { /* * There MUST be a memfile, otherwise we can't do anything * If we can't create one for the current buffer, take another buffer */ close_buffer(NULL, curbuf, 0, FALSE); for (curbuf = firstbuf; curbuf != NULL; curbuf = curbuf->b_next) if (curbuf->b_ml.ml_mfp != NULL) break; /* * if there is no memfile at all, exit * This is OK, since there are no changes to lose. */ if (curbuf == NULL) { EMSG(_("E82: Cannot allocate any buffer, exiting...")); getout(2); } EMSG(_("E83: Cannot allocate buffer, using other one...")); enter_buffer(curbuf); return FAIL; } #ifdef FEAT_AUTOCMD /* The autocommands in readfile() may change the buffer, but only AFTER * reading the file. */ old_curbuf = curbuf; modified_was_set = FALSE; #endif /* mark cursor position as being invalid */ curwin->w_valid = 0; if (curbuf->b_ffname != NULL #ifdef FEAT_NETBEANS_INTG && netbeansReadFile #endif ) { #ifdef FEAT_NETBEANS_INTG int oldFire = netbeansFireChanges; netbeansFireChanges = 0; #endif retval = readfile(curbuf->b_ffname, curbuf->b_fname, (linenr_T)0, (linenr_T)0, (linenr_T)MAXLNUM, eap, flags | READ_NEW); #ifdef FEAT_NETBEANS_INTG netbeansFireChanges = oldFire; #endif /* Help buffer is filtered. */ if (curbuf->b_help) fix_help_buffer(); } else if (read_stdin) { int save_bin = curbuf->b_p_bin; linenr_T line_count; /* * First read the text in binary mode into the buffer. * Then read from that same buffer and append at the end. This makes * it possible to retry when 'fileformat' or 'fileencoding' was * guessed wrong. */ curbuf->b_p_bin = TRUE; retval = readfile(NULL, NULL, (linenr_T)0, (linenr_T)0, (linenr_T)MAXLNUM, NULL, flags | (READ_NEW + READ_STDIN)); curbuf->b_p_bin = save_bin; if (retval == OK) { line_count = curbuf->b_ml.ml_line_count; retval = readfile(NULL, NULL, (linenr_T)line_count, (linenr_T)0, (linenr_T)MAXLNUM, eap, flags | READ_BUFFER); if (retval == OK) { /* Delete the binary lines. */ while (--line_count >= 0) ml_delete((linenr_T)1, FALSE); } else { /* Delete the converted lines. */ while (curbuf->b_ml.ml_line_count > line_count) ml_delete(line_count, FALSE); } /* Put the cursor on the first line. */ curwin->w_cursor.lnum = 1; curwin->w_cursor.col = 0; /* Set or reset 'modified' before executing autocommands, so that * it can be changed there. */ if (!readonlymode && !bufempty()) changed(); else if (retval != FAIL) unchanged(curbuf, FALSE); #ifdef FEAT_AUTOCMD # ifdef FEAT_EVAL apply_autocmds_retval(EVENT_STDINREADPOST, NULL, NULL, FALSE, curbuf, &retval); # else apply_autocmds(EVENT_STDINREADPOST, NULL, NULL, FALSE, curbuf); # endif #endif } } /* if first time loading this buffer, init b_chartab[] */ if (curbuf->b_flags & BF_NEVERLOADED) (void)buf_init_chartab(curbuf, FALSE); /* * Set/reset the Changed flag first, autocmds may change the buffer. * Apply the automatic commands, before processing the modelines. * So the modelines have priority over auto commands. */ /* When reading stdin, the buffer contents always needs writing, so set * the changed flag. Unless in readonly mode: "ls | gview -". * When interrupted and 'cpoptions' contains 'i' set changed flag. */ if ((got_int && vim_strchr(p_cpo, CPO_INTMOD) != NULL) #ifdef FEAT_AUTOCMD || modified_was_set /* ":set modified" used in autocmd */ # ifdef FEAT_EVAL || (aborting() && vim_strchr(p_cpo, CPO_INTMOD) != NULL) # endif #endif ) changed(); else if (retval != FAIL && !read_stdin) unchanged(curbuf, FALSE); save_file_ff(curbuf); /* keep this fileformat */ /* require "!" to overwrite the file, because it wasn't read completely */ #ifdef FEAT_EVAL if (aborting()) #else if (got_int) #endif curbuf->b_flags |= BF_READERR; #ifdef FEAT_FOLDING /* Need to update automatic folding. Do this before the autocommands, * they may use the fold info. */ foldUpdateAll(curwin); #endif #ifdef FEAT_AUTOCMD /* need to set w_topline, unless some autocommand already did that. */ if (!(curwin->w_valid & VALID_TOPLINE)) { curwin->w_topline = 1; # ifdef FEAT_DIFF curwin->w_topfill = 0; # endif } # ifdef FEAT_EVAL apply_autocmds_retval(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf, &retval); # else apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf); # endif #endif if (retval != FAIL) { #ifdef FEAT_AUTOCMD /* * The autocommands may have changed the current buffer. Apply the * modelines to the correct buffer, if it still exists and is loaded. */ if (buf_valid(old_curbuf) && old_curbuf->b_ml.ml_mfp != NULL) { aco_save_T aco; /* Go to the buffer that was opened. */ aucmd_prepbuf(&aco, old_curbuf); #endif do_modelines(0); curbuf->b_flags &= ~(BF_CHECK_RO | BF_NEVERLOADED); #ifdef FEAT_AUTOCMD # ifdef FEAT_EVAL apply_autocmds_retval(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf, &retval); # else apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf); # endif /* restore curwin/curbuf and a few other things */ aucmd_restbuf(&aco); } #endif } return retval; } /* * Return TRUE if "buf" points to a valid buffer (in the buffer list). */ int buf_valid(buf) buf_T *buf; { buf_T *bp; for (bp = firstbuf; bp != NULL; bp = bp->b_next) if (bp == buf) return TRUE; return FALSE; } /* * Close the link to a buffer. * "action" is used when there is no longer a window for the buffer. * It can be: * 0 buffer becomes hidden * DOBUF_UNLOAD buffer is unloaded * DOBUF_DELETE buffer is unloaded and removed from buffer list * DOBUF_WIPE buffer is unloaded and really deleted * When doing all but the first one on the current buffer, the caller should * get a new buffer very soon! * * The 'bufhidden' option can force freeing and deleting. * * When "abort_if_last" is TRUE then do not close the buffer if autocommands * cause there to be only one window with this buffer. e.g. when ":quit" is * supposed to close the window but autocommands close all other windows. */ void close_buffer(win, buf, action, abort_if_last) win_T *win; /* if not NULL, set b_last_cursor */ buf_T *buf; int action; int abort_if_last UNUSED; { #ifdef FEAT_AUTOCMD int is_curbuf; int nwindows; #endif int unload_buf = (action != 0); int del_buf = (action == DOBUF_DEL || action == DOBUF_WIPE); int wipe_buf = (action == DOBUF_WIPE); #ifdef FEAT_QUICKFIX /* * Force unloading or deleting when 'bufhidden' says so. * The caller must take care of NOT deleting/freeing when 'bufhidden' is * "hide" (otherwise we could never free or delete a buffer). */ if (buf->b_p_bh[0] == 'd') /* 'bufhidden' == "delete" */ { del_buf = TRUE; unload_buf = TRUE; } else if (buf->b_p_bh[0] == 'w') /* 'bufhidden' == "wipe" */ { del_buf = TRUE; unload_buf = TRUE; wipe_buf = TRUE; } else if (buf->b_p_bh[0] == 'u') /* 'bufhidden' == "unload" */ unload_buf = TRUE; #endif if (win != NULL) { /* Set b_last_cursor when closing the last window for the buffer. * Remember the last cursor position and window options of the buffer. * This used to be only for the current window, but then options like * 'foldmethod' may be lost with a ":only" command. */ if (buf->b_nwindows == 1) set_last_cursor(win); buflist_setfpos(buf, win, win->w_cursor.lnum == 1 ? 0 : win->w_cursor.lnum, win->w_cursor.col, TRUE); } #ifdef FEAT_AUTOCMD /* When the buffer is no longer in a window, trigger BufWinLeave */ if (buf->b_nwindows == 1) { buf->b_closing = TRUE; apply_autocmds(EVENT_BUFWINLEAVE, buf->b_fname, buf->b_fname, FALSE, buf); if (!buf_valid(buf)) { /* Autocommands deleted the buffer. */ aucmd_abort: EMSG(_(e_auabort)); return; } buf->b_closing = FALSE; if (abort_if_last && one_window()) /* Autocommands made this the only window. */ goto aucmd_abort; /* When the buffer becomes hidden, but is not unloaded, trigger * BufHidden */ if (!unload_buf) { buf->b_closing = TRUE; apply_autocmds(EVENT_BUFHIDDEN, buf->b_fname, buf->b_fname, FALSE, buf); if (!buf_valid(buf)) /* Autocommands deleted the buffer. */ goto aucmd_abort; buf->b_closing = FALSE; if (abort_if_last && one_window()) /* Autocommands made this the only window. */ goto aucmd_abort; } # ifdef FEAT_EVAL if (aborting()) /* autocmds may abort script processing */ return; # endif } nwindows = buf->b_nwindows; #endif /* decrease the link count from windows (unless not in any window) */ if (buf->b_nwindows > 0) --buf->b_nwindows; /* Return when a window is displaying the buffer or when it's not * unloaded. */ if (buf->b_nwindows > 0 || !unload_buf) return; /* Always remove the buffer when there is no file name. */ if (buf->b_ffname == NULL) del_buf = TRUE; /* * Free all things allocated for this buffer. * Also calls the "BufDelete" autocommands when del_buf is TRUE. */ #ifdef FEAT_AUTOCMD /* Remember if we are closing the current buffer. Restore the number of * windows, so that autocommands in buf_freeall() don't get confused. */ is_curbuf = (buf == curbuf); buf->b_nwindows = nwindows; #endif buf_freeall(buf, (del_buf ? BFA_DEL : 0) + (wipe_buf ? BFA_WIPE : 0)); if ( #ifdef FEAT_WINDOWS win_valid(win) && #else win != NULL && #endif win->w_buffer == buf) win->w_buffer = NULL; /* make sure we don't use the buffer now */ #ifdef FEAT_AUTOCMD /* Autocommands may have deleted the buffer. */ if (!buf_valid(buf)) return; # ifdef FEAT_EVAL if (aborting()) /* autocmds may abort script processing */ return; # endif /* Autocommands may have opened or closed windows for this buffer. * Decrement the count for the close we do here. */ if (buf->b_nwindows > 0) --buf->b_nwindows; /* * It's possible that autocommands change curbuf to the one being deleted. * This might cause the previous curbuf to be deleted unexpectedly. But * in some cases it's OK to delete the curbuf, because a new one is * obtained anyway. Therefore only return if curbuf changed to the * deleted buffer. */ if (buf == curbuf && !is_curbuf) return; #endif /* Change directories when the 'acd' option is set. */ DO_AUTOCHDIR /* * Remove the buffer from the list. */ if (wipe_buf) { #ifdef FEAT_SUN_WORKSHOP if (usingSunWorkShop) workshop_file_closed_lineno((char *)buf->b_ffname, (int)buf->b_last_cursor.lnum); #endif vim_free(buf->b_ffname); vim_free(buf->b_sfname); if (buf->b_prev == NULL) firstbuf = buf->b_next; else buf->b_prev->b_next = buf->b_next; if (buf->b_next == NULL) lastbuf = buf->b_prev; else buf->b_next->b_prev = buf->b_prev; free_buffer(buf); } else { if (del_buf) { /* Free all internal variables and reset option values, to make * ":bdel" compatible with Vim 5.7. */ free_buffer_stuff(buf, TRUE); /* Make it look like a new buffer. */ buf->b_flags = BF_CHECK_RO | BF_NEVERLOADED; /* Init the options when loaded again. */ buf->b_p_initialized = FALSE; } buf_clear_file(buf); if (del_buf) buf->b_p_bl = FALSE; } } /* * Make buffer not contain a file. */ void buf_clear_file(buf) buf_T *buf; { buf->b_ml.ml_line_count = 1; unchanged(buf, TRUE); #ifndef SHORT_FNAME buf->b_shortname = FALSE; #endif buf->b_p_eol = TRUE; buf->b_start_eol = TRUE; #ifdef FEAT_MBYTE buf->b_p_bomb = FALSE; buf->b_start_bomb = FALSE; #endif buf->b_ml.ml_mfp = NULL; buf->b_ml.ml_flags = ML_EMPTY; /* empty buffer */ #ifdef FEAT_NETBEANS_INTG netbeans_deleted_all_lines(buf); #endif } /* * buf_freeall() - free all things allocated for a buffer that are related to * the file. flags: * BFA_DEL buffer is going to be deleted * BFA_WIPE buffer is going to be wiped out * BFA_KEEP_UNDO do not free undo information */ void buf_freeall(buf, flags) buf_T *buf; int flags; { #ifdef FEAT_AUTOCMD int is_curbuf = (buf == curbuf); buf->b_closing = TRUE; apply_autocmds(EVENT_BUFUNLOAD, buf->b_fname, buf->b_fname, FALSE, buf); if (!buf_valid(buf)) /* autocommands may delete the buffer */ return; if ((flags & BFA_DEL) && buf->b_p_bl) { apply_autocmds(EVENT_BUFDELETE, buf->b_fname, buf->b_fname, FALSE, buf); if (!buf_valid(buf)) /* autocommands may delete the buffer */ return; } if (flags & BFA_WIPE) { apply_autocmds(EVENT_BUFWIPEOUT, buf->b_fname, buf->b_fname, FALSE, buf); if (!buf_valid(buf)) /* autocommands may delete the buffer */ return; } buf->b_closing = FALSE; # ifdef FEAT_EVAL if (aborting()) /* autocmds may abort script processing */ return; # endif /* * It's possible that autocommands change curbuf to the one being deleted. * This might cause curbuf to be deleted unexpectedly. But in some cases * it's OK to delete the curbuf, because a new one is obtained anyway. * Therefore only return if curbuf changed to the deleted buffer. */ if (buf == curbuf && !is_curbuf) return; #endif #ifdef FEAT_DIFF diff_buf_delete(buf); /* Can't use 'diff' for unloaded buffer. */ #endif #ifdef FEAT_SYN_HL /* Remove any ownsyntax, unless exiting. */ if (firstwin != NULL && curwin->w_buffer == buf) reset_synblock(curwin); #endif #ifdef FEAT_FOLDING /* No folds in an empty buffer. */ # ifdef FEAT_WINDOWS { win_T *win; tabpage_T *tp; FOR_ALL_TAB_WINDOWS(tp, win) if (win->w_buffer == buf) clearFolding(win); } # else if (curwin->w_buffer == buf) clearFolding(curwin); # endif #endif #ifdef FEAT_TCL tcl_buffer_free(buf); #endif ml_close(buf, TRUE); /* close and delete the memline/memfile */ buf->b_ml.ml_line_count = 0; /* no lines in buffer */ if ((flags & BFA_KEEP_UNDO) == 0) { u_blockfree(buf); /* free the memory allocated for undo */ u_clearall(buf); /* reset all undo information */ } #ifdef FEAT_SYN_HL syntax_clear(&buf->b_s); /* reset syntax info */ #endif buf->b_flags &= ~BF_READERR; /* a read error is no longer relevant */ } /* * Free a buffer structure and the things it contains related to the buffer * itself (not the file, that must have been done already). */ static void free_buffer(buf) buf_T *buf; { free_buffer_stuff(buf, TRUE); #ifdef FEAT_LUA lua_buffer_free(buf); #endif #ifdef FEAT_MZSCHEME mzscheme_buffer_free(buf); #endif #ifdef FEAT_PERL perl_buf_free(buf); #endif #ifdef FEAT_PYTHON python_buffer_free(buf); #endif #ifdef FEAT_PYTHON3 python3_buffer_free(buf); #endif #ifdef FEAT_RUBY ruby_buffer_free(buf); #endif #ifdef FEAT_AUTOCMD aubuflocal_remove(buf); #endif vim_free(buf); } /* * Free stuff in the buffer for ":bdel" and when wiping out the buffer. */ static void free_buffer_stuff(buf, free_options) buf_T *buf; int free_options; /* free options as well */ { if (free_options) { clear_wininfo(buf); /* including window-local options */ free_buf_options(buf, TRUE); #ifdef FEAT_SPELL ga_clear(&buf->b_s.b_langp); #endif } #ifdef FEAT_EVAL vars_clear(&buf->b_vars.dv_hashtab); /* free all internal variables */ hash_init(&buf->b_vars.dv_hashtab); #endif #ifdef FEAT_USR_CMDS uc_clear(&buf->b_ucmds); /* clear local user commands */ #endif #ifdef FEAT_SIGNS buf_delete_signs(buf); /* delete any signs */ #endif #ifdef FEAT_NETBEANS_INTG netbeans_file_killed(buf); #endif #ifdef FEAT_LOCALMAP map_clear_int(buf, MAP_ALL_MODES, TRUE, FALSE); /* clear local mappings */ map_clear_int(buf, MAP_ALL_MODES, TRUE, TRUE); /* clear local abbrevs */ #endif #ifdef FEAT_MBYTE vim_free(buf->b_start_fenc); buf->b_start_fenc = NULL; #endif } /* * Free the b_wininfo list for buffer "buf". */ static void clear_wininfo(buf) buf_T *buf; { wininfo_T *wip; while (buf->b_wininfo != NULL) { wip = buf->b_wininfo; buf->b_wininfo = wip->wi_next; if (wip->wi_optset) { clear_winopt(&wip->wi_opt); #ifdef FEAT_FOLDING deleteFoldRecurse(&wip->wi_folds); #endif } vim_free(wip); } } #if defined(FEAT_LISTCMDS) || defined(PROTO) /* * Go to another buffer. Handles the result of the ATTENTION dialog. */ void goto_buffer(eap, start, dir, count) exarg_T *eap; int start; int dir; int count; { # if defined(FEAT_WINDOWS) && defined(HAS_SWAP_EXISTS_ACTION) buf_T *old_curbuf = curbuf; swap_exists_action = SEA_DIALOG; # endif (void)do_buffer(*eap->cmd == 's' ? DOBUF_SPLIT : DOBUF_GOTO, start, dir, count, eap->forceit); # if defined(FEAT_WINDOWS) && defined(HAS_SWAP_EXISTS_ACTION) if (swap_exists_action == SEA_QUIT && *eap->cmd == 's') { # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL) cleanup_T cs; /* Reset the error/interrupt/exception state here so that * aborting() returns FALSE when closing a window. */ enter_cleanup(&cs); # endif /* Quitting means closing the split window, nothing else. */ win_close(curwin, TRUE); swap_exists_action = SEA_NONE; swap_exists_did_quit = TRUE; # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL) /* Restore the error/interrupt/exception state if not discarded by a * new aborting error, interrupt, or uncaught exception. */ leave_cleanup(&cs); # endif } else handle_swap_exists(old_curbuf); # endif } #endif #if defined(HAS_SWAP_EXISTS_ACTION) || defined(PROTO) /* * Handle the situation of swap_exists_action being set. * It is allowed for "old_curbuf" to be NULL or invalid. */ void handle_swap_exists(old_curbuf) buf_T *old_curbuf; { # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL) cleanup_T cs; # endif if (swap_exists_action == SEA_QUIT) { # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL) /* Reset the error/interrupt/exception state here so that * aborting() returns FALSE when closing a buffer. */ enter_cleanup(&cs); # endif /* User selected Quit at ATTENTION prompt. Go back to previous * buffer. If that buffer is gone or the same as the current one, * open a new, empty buffer. */ swap_exists_action = SEA_NONE; /* don't want it again */ swap_exists_did_quit = TRUE; close_buffer(curwin, curbuf, DOBUF_UNLOAD, FALSE); if (!buf_valid(old_curbuf) || old_curbuf == curbuf) old_curbuf = buflist_new(NULL, NULL, 1L, BLN_CURBUF | BLN_LISTED); if (old_curbuf != NULL) enter_buffer(old_curbuf); /* If "old_curbuf" is NULL we are in big trouble here... */ # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL) /* Restore the error/interrupt/exception state if not discarded by a * new aborting error, interrupt, or uncaught exception. */ leave_cleanup(&cs); # endif } else if (swap_exists_action == SEA_RECOVER) { # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL) /* Reset the error/interrupt/exception state here so that * aborting() returns FALSE when closing a buffer. */ enter_cleanup(&cs); # endif /* User selected Recover at ATTENTION prompt. */ msg_scroll = TRUE; ml_recover(); MSG_PUTS("\n"); /* don't overwrite the last message */ cmdline_row = msg_row; do_modelines(0); # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL) /* Restore the error/interrupt/exception state if not discarded by a * new aborting error, interrupt, or uncaught exception. */ leave_cleanup(&cs); # endif } swap_exists_action = SEA_NONE; } #endif #if defined(FEAT_LISTCMDS) || defined(PROTO) /* * do_bufdel() - delete or unload buffer(s) * * addr_count == 0: ":bdel" - delete current buffer * addr_count == 1: ":N bdel" or ":bdel N [N ..]" - first delete * buffer "end_bnr", then any other arguments. * addr_count == 2: ":N,N bdel" - delete buffers in range * * command can be DOBUF_UNLOAD (":bunload"), DOBUF_WIPE (":bwipeout") or * DOBUF_DEL (":bdel") * * Returns error message or NULL */ char_u * do_bufdel(command, arg, addr_count, start_bnr, end_bnr, forceit) int command; char_u *arg; /* pointer to extra arguments */ int addr_count; int start_bnr; /* first buffer number in a range */ int end_bnr; /* buffer nr or last buffer nr in a range */ int forceit; { int do_current = 0; /* delete current buffer? */ int deleted = 0; /* number of buffers deleted */ char_u *errormsg = NULL; /* return value */ int bnr; /* buffer number */ char_u *p; if (addr_count == 0) { (void)do_buffer(command, DOBUF_CURRENT, FORWARD, 0, forceit); } else { if (addr_count == 2) { if (*arg) /* both range and argument is not allowed */ return (char_u *)_(e_trailing); bnr = start_bnr; } else /* addr_count == 1 */ bnr = end_bnr; for ( ;!got_int; ui_breakcheck()) { /* * delete the current buffer last, otherwise when the * current buffer is deleted, the next buffer becomes * the current one and will be loaded, which may then * also be deleted, etc. */ if (bnr == curbuf->b_fnum) do_current = bnr; else if (do_buffer(command, DOBUF_FIRST, FORWARD, (int)bnr, forceit) == OK) ++deleted; /* * find next buffer number to delete/unload */ if (addr_count == 2) { if (++bnr > end_bnr) break; } else /* addr_count == 1 */ { arg = skipwhite(arg); if (*arg == NUL) break; if (!VIM_ISDIGIT(*arg)) { p = skiptowhite_esc(arg); bnr = buflist_findpat(arg, p, command == DOBUF_WIPE, FALSE); if (bnr < 0) /* failed */ break; arg = p; } else bnr = getdigits(&arg); } } if (!got_int && do_current && do_buffer(command, DOBUF_FIRST, FORWARD, do_current, forceit) == OK) ++deleted; if (deleted == 0) { if (command == DOBUF_UNLOAD) STRCPY(IObuff, _("E515: No buffers were unloaded")); else if (command == DOBUF_DEL) STRCPY(IObuff, _("E516: No buffers were deleted")); else STRCPY(IObuff, _("E517: No buffers were wiped out")); errormsg = IObuff; } else if (deleted >= p_report) { if (command == DOBUF_UNLOAD) { if (deleted == 1) MSG(_("1 buffer unloaded")); else smsg((char_u *)_("%d buffers unloaded"), deleted); } else if (command == DOBUF_DEL) { if (deleted == 1) MSG(_("1 buffer deleted")); else smsg((char_u *)_("%d buffers deleted"), deleted); } else { if (deleted == 1) MSG(_("1 buffer wiped out")); else smsg((char_u *)_("%d buffers wiped out"), deleted); } } } return errormsg; } /* * Implementation of the commands for the buffer list. * * action == DOBUF_GOTO go to specified buffer * action == DOBUF_SPLIT split window and go to specified buffer * action == DOBUF_UNLOAD unload specified buffer(s) * action == DOBUF_DEL delete specified buffer(s) from buffer list * action == DOBUF_WIPE delete specified buffer(s) really * * start == DOBUF_CURRENT go to "count" buffer from current buffer * start == DOBUF_FIRST go to "count" buffer from first buffer * start == DOBUF_LAST go to "count" buffer from last buffer * start == DOBUF_MOD go to "count" modified buffer from current buffer * * Return FAIL or OK. */ int do_buffer(action, start, dir, count, forceit) int action; int start; int dir; /* FORWARD or BACKWARD */ int count; /* buffer number or number of buffers */ int forceit; /* TRUE for :...! */ { buf_T *buf; buf_T *bp; int unload = (action == DOBUF_UNLOAD || action == DOBUF_DEL || action == DOBUF_WIPE); switch (start) { case DOBUF_FIRST: buf = firstbuf; break; case DOBUF_LAST: buf = lastbuf; break; default: buf = curbuf; break; } if (start == DOBUF_MOD) /* find next modified buffer */ { while (count-- > 0) { do { buf = buf->b_next; if (buf == NULL) buf = firstbuf; } while (buf != curbuf && !bufIsChanged(buf)); } if (!bufIsChanged(buf)) { EMSG(_("E84: No modified buffer found")); return FAIL; } } else if (start == DOBUF_FIRST && count) /* find specified buffer number */ { while (buf != NULL && buf->b_fnum != count) buf = buf->b_next; } else { bp = NULL; while (count > 0 || (!unload && !buf->b_p_bl && bp != buf)) { /* remember the buffer where we start, we come back there when all * buffers are unlisted. */ if (bp == NULL) bp = buf; if (dir == FORWARD) { buf = buf->b_next; if (buf == NULL) buf = firstbuf; } else { buf = buf->b_prev; if (buf == NULL) buf = lastbuf; } /* don't count unlisted buffers */ if (unload || buf->b_p_bl) { --count; bp = NULL; /* use this buffer as new starting point */ } if (bp == buf) { /* back where we started, didn't find anything. */ EMSG(_("E85: There is no listed buffer")); return FAIL; } } } if (buf == NULL) /* could not find it */ { if (start == DOBUF_FIRST) { /* don't warn when deleting */ if (!unload) EMSGN(_("E86: Buffer %ld does not exist"), count); } else if (dir == FORWARD) EMSG(_("E87: Cannot go beyond last buffer")); else EMSG(_("E88: Cannot go before first buffer")); return FAIL; } #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif #ifdef FEAT_LISTCMDS /* * delete buffer buf from memory and/or the list */ if (unload) { int forward; int retval; /* When unloading or deleting a buffer that's already unloaded and * unlisted: fail silently. */ if (action != DOBUF_WIPE && buf->b_ml.ml_mfp == NULL && !buf->b_p_bl) return FAIL; if (!forceit && bufIsChanged(buf)) { #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) if ((p_confirm || cmdmod.confirm) && p_write) { dialog_changed(buf, FALSE); # ifdef FEAT_AUTOCMD if (!buf_valid(buf)) /* Autocommand deleted buffer, oops! It's not changed * now. */ return FAIL; # endif /* If it's still changed fail silently, the dialog already * mentioned why it fails. */ if (bufIsChanged(buf)) return FAIL; } else #endif { EMSGN(_("E89: No write since last change for buffer %ld (add ! to override)"), buf->b_fnum); return FAIL; } } /* * If deleting the last (listed) buffer, make it empty. * The last (listed) buffer cannot be unloaded. */ for (bp = firstbuf; bp != NULL; bp = bp->b_next) if (bp->b_p_bl && bp != buf) break; if (bp == NULL && buf == curbuf) { if (action == DOBUF_UNLOAD) { EMSG(_("E90: Cannot unload last buffer")); return FAIL; } /* Close any other windows on this buffer, then make it empty. */ #ifdef FEAT_WINDOWS close_windows(buf, TRUE); #endif setpcmark(); retval = do_ecmd(0, NULL, NULL, NULL, ECMD_ONE, forceit ? ECMD_FORCEIT : 0, curwin); /* * do_ecmd() may create a new buffer, then we have to delete * the old one. But do_ecmd() may have done that already, check * if the buffer still exists. */ if (buf != curbuf && buf_valid(buf) && buf->b_nwindows == 0) close_buffer(NULL, buf, action, FALSE); return retval; } #ifdef FEAT_WINDOWS /* * If the deleted buffer is the current one, close the current window * (unless it's the only window). Repeat this so long as we end up in * a window with this buffer. */ while (buf == curbuf # ifdef FEAT_AUTOCMD && !(curwin->w_closing || curwin->w_buffer->b_closing) # endif && (firstwin != lastwin || first_tabpage->tp_next != NULL)) win_close(curwin, FALSE); #endif /* * If the buffer to be deleted is not the current one, delete it here. */ if (buf != curbuf) { #ifdef FEAT_WINDOWS close_windows(buf, FALSE); #endif if (buf != curbuf && buf_valid(buf) && buf->b_nwindows <= 0) close_buffer(NULL, buf, action, FALSE); return OK; } /* * Deleting the current buffer: Need to find another buffer to go to. * There must be another, otherwise it would have been handled above. * First use au_new_curbuf, if it is valid. * Then prefer the buffer we most recently visited. * Else try to find one that is loaded, after the current buffer, * then before the current buffer. * Finally use any buffer. */ buf = NULL; /* selected buffer */ bp = NULL; /* used when no loaded buffer found */ #ifdef FEAT_AUTOCMD if (au_new_curbuf != NULL && buf_valid(au_new_curbuf)) buf = au_new_curbuf; # ifdef FEAT_JUMPLIST else # endif #endif #ifdef FEAT_JUMPLIST if (curwin->w_jumplistlen > 0) { int jumpidx; jumpidx = curwin->w_jumplistidx - 1; if (jumpidx < 0) jumpidx = curwin->w_jumplistlen - 1; forward = jumpidx; while (jumpidx != curwin->w_jumplistidx) { buf = buflist_findnr(curwin->w_jumplist[jumpidx].fmark.fnum); if (buf != NULL) { if (buf == curbuf || !buf->b_p_bl) buf = NULL; /* skip current and unlisted bufs */ else if (buf->b_ml.ml_mfp == NULL) { /* skip unloaded buf, but may keep it for later */ if (bp == NULL) bp = buf; buf = NULL; } } if (buf != NULL) /* found a valid buffer: stop searching */ break; /* advance to older entry in jump list */ if (!jumpidx && curwin->w_jumplistidx == curwin->w_jumplistlen) break; if (--jumpidx < 0) jumpidx = curwin->w_jumplistlen - 1; if (jumpidx == forward) /* List exhausted for sure */ break; } } #endif if (buf == NULL) /* No previous buffer, Try 2'nd approach */ { forward = TRUE; buf = curbuf->b_next; for (;;) { if (buf == NULL) { if (!forward) /* tried both directions */ break; buf = curbuf->b_prev; forward = FALSE; continue; } /* in non-help buffer, try to skip help buffers, and vv */ if (buf->b_help == curbuf->b_help && buf->b_p_bl) { if (buf->b_ml.ml_mfp != NULL) /* found loaded buffer */ break; if (bp == NULL) /* remember unloaded buf for later */ bp = buf; } if (forward) buf = buf->b_next; else buf = buf->b_prev; } } if (buf == NULL) /* No loaded buffer, use unloaded one */ buf = bp; if (buf == NULL) /* No loaded buffer, find listed one */ { for (buf = firstbuf; buf != NULL; buf = buf->b_next) if (buf->b_p_bl && buf != curbuf) break; } if (buf == NULL) /* Still no buffer, just take one */ { if (curbuf->b_next != NULL) buf = curbuf->b_next; else buf = curbuf->b_prev; } } /* * make buf current buffer */ if (action == DOBUF_SPLIT) /* split window first */ { # ifdef FEAT_WINDOWS /* If 'switchbuf' contains "useopen": jump to first window containing * "buf" if one exists */ if ((swb_flags & SWB_USEOPEN) && buf_jump_open_win(buf)) return OK; /* If 'switchbuf' contains "usetab": jump to first window in any tab * page containing "buf" if one exists */ if ((swb_flags & SWB_USETAB) && buf_jump_open_tab(buf)) return OK; if (win_split(0, 0) == FAIL) # endif return FAIL; } #endif /* go to current buffer - nothing to do */ if (buf == curbuf) return OK; /* * Check if the current buffer may be abandoned. */ if (action == DOBUF_GOTO && !can_abandon(curbuf, forceit)) { #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) if ((p_confirm || cmdmod.confirm) && p_write) { dialog_changed(curbuf, FALSE); # ifdef FEAT_AUTOCMD if (!buf_valid(buf)) /* Autocommand deleted buffer, oops! */ return FAIL; # endif } if (bufIsChanged(curbuf)) #endif { EMSG(_(e_nowrtmsg)); return FAIL; } } /* Go to the other buffer. */ set_curbuf(buf, action); #if defined(FEAT_LISTCMDS) \ && (defined(FEAT_SCROLLBIND) || defined(FEAT_CURSORBIND)) if (action == DOBUF_SPLIT) { RESET_BINDING(curwin); /* reset 'scrollbind' and 'cursorbind' */ } #endif #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL) if (aborting()) /* autocmds may abort script processing */ return FAIL; #endif return OK; } #endif /* FEAT_LISTCMDS */ /* * Set current buffer to "buf". Executes autocommands and closes current * buffer. "action" tells how to close the current buffer: * DOBUF_GOTO free or hide it * DOBUF_SPLIT nothing * DOBUF_UNLOAD unload it * DOBUF_DEL delete it * DOBUF_WIPE wipe it out */ void set_curbuf(buf, action) buf_T *buf; int action; { buf_T *prevbuf; #ifdef FEAT_WINDOWS win_T *prevwin; #endif int unload = (action == DOBUF_UNLOAD || action == DOBUF_DEL || action == DOBUF_WIPE); setpcmark(); if (!cmdmod.keepalt) curwin->w_alt_fnum = curbuf->b_fnum; /* remember alternate file */ buflist_altfpos(curwin); /* remember curpos */ #ifdef FEAT_VISUAL /* Don't restart Select mode after switching to another buffer. */ VIsual_reselect = FALSE; #endif /* close_windows() or apply_autocmds() may change curbuf */ prevbuf = curbuf; #ifdef FEAT_AUTOCMD apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, FALSE, curbuf); # ifdef FEAT_EVAL if (buf_valid(prevbuf) && !aborting()) # else if (buf_valid(prevbuf)) # endif #endif { #ifdef FEAT_SYN_HL if (prevbuf == curwin->w_buffer) reset_synblock(curwin); #endif #ifdef FEAT_WINDOWS if (unload) close_windows(prevbuf, FALSE); #endif #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL) if (buf_valid(prevbuf) && !aborting()) #else if (buf_valid(prevbuf)) #endif { #ifdef FEAT_WINDOWS prevwin = curwin; #endif if (prevbuf == curbuf) u_sync(FALSE); close_buffer(prevbuf == curwin->w_buffer ? curwin : NULL, prevbuf, unload ? action : (action == DOBUF_GOTO && !P_HID(prevbuf) && !bufIsChanged(prevbuf)) ? DOBUF_UNLOAD : 0, FALSE); #ifdef FEAT_WINDOWS if (curwin != prevwin && win_valid(prevwin)) /* autocommands changed curwin, Grr! */ curwin = prevwin; #endif } } #ifdef FEAT_AUTOCMD /* An autocommand may have deleted "buf", already entered it (e.g., when * it did ":bunload") or aborted the script processing! * If curwin->w_buffer is null, enter_buffer() will make it valid again */ if ((buf_valid(buf) && buf != curbuf # ifdef FEAT_EVAL && !aborting() # endif # ifdef FEAT_WINDOWS ) || curwin->w_buffer == NULL # endif ) #endif enter_buffer(buf); } /* * Enter a new current buffer. * Old curbuf must have been abandoned already! */ void enter_buffer(buf) buf_T *buf; { /* Copy buffer and window local option values. Not for a help buffer. */ buf_copy_options(buf, BCO_ENTER | BCO_NOHELP); if (!buf->b_help) get_winopts(buf); #ifdef FEAT_FOLDING else /* Remove all folds in the window. */ clearFolding(curwin); foldUpdateAll(curwin); /* update folds (later). */ #endif /* Get the buffer in the current window. */ curwin->w_buffer = buf; curbuf = buf; ++curbuf->b_nwindows; #ifdef FEAT_DIFF if (curwin->w_p_diff) diff_buf_add(curbuf); #endif #ifdef FEAT_SYN_HL curwin->w_s = &(buf->b_s); #endif /* Cursor on first line by default. */ curwin->w_cursor.lnum = 1; curwin->w_cursor.col = 0; #ifdef FEAT_VIRTUALEDIT curwin->w_cursor.coladd = 0; #endif curwin->w_set_curswant = TRUE; #ifdef FEAT_AUTOCMD curwin->w_topline_was_set = FALSE; #endif /* mark cursor position as being invalid */ curwin->w_valid = 0; /* Make sure the buffer is loaded. */ if (curbuf->b_ml.ml_mfp == NULL) /* need to load the file */ { #ifdef FEAT_AUTOCMD /* If there is no filetype, allow for detecting one. Esp. useful for * ":ball" used in a autocommand. If there already is a filetype we * might prefer to keep it. */ if (*curbuf->b_p_ft == NUL) did_filetype = FALSE; #endif open_buffer(FALSE, NULL, 0); } else { if (!msg_silent) need_fileinfo = TRUE; /* display file info after redraw */ (void)buf_check_timestamp(curbuf, FALSE); /* check if file changed */ #ifdef FEAT_AUTOCMD curwin->w_topline = 1; # ifdef FEAT_DIFF curwin->w_topfill = 0; # endif apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf); apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf); #endif } /* If autocommands did not change the cursor position, restore cursor lnum * and possibly cursor col. */ if (curwin->w_cursor.lnum == 1 && inindent(0)) buflist_getfpos(); check_arg_idx(curwin); /* check for valid arg_idx */ #ifdef FEAT_TITLE maketitle(); #endif #ifdef FEAT_AUTOCMD /* when autocmds didn't change it */ if (curwin->w_topline == 1 && !curwin->w_topline_was_set) #endif scroll_cursor_halfway(FALSE); /* redisplay at correct position */ #ifdef FEAT_NETBEANS_INTG /* Send fileOpened event because we've changed buffers. */ netbeans_file_activated(curbuf); #endif /* Change directories when the 'acd' option is set. */ DO_AUTOCHDIR #ifdef FEAT_KEYMAP if (curbuf->b_kmap_state & KEYMAP_INIT) (void)keymap_init(); #endif #ifdef FEAT_SPELL /* May need to set the spell language. Can only do this after the buffer * has been properly setup. */ if (!curbuf->b_help && curwin->w_p_spell && *curwin->w_s->b_p_spl != NUL) (void)did_set_spelllang(curwin); #endif redraw_later(NOT_VALID); } #if defined(FEAT_AUTOCHDIR) || defined(PROTO) /* * Change to the directory of the current buffer. */ void do_autochdir() { if (curbuf->b_ffname != NULL && vim_chdirfile(curbuf->b_ffname) == OK) shorten_fnames(TRUE); } #endif /* * functions for dealing with the buffer list */ /* * Add a file name to the buffer list. Return a pointer to the buffer. * If the same file name already exists return a pointer to that buffer. * If it does not exist, or if fname == NULL, a new entry is created. * If (flags & BLN_CURBUF) is TRUE, may use current buffer. * If (flags & BLN_LISTED) is TRUE, add new buffer to buffer list. * If (flags & BLN_DUMMY) is TRUE, don't count it as a real buffer. * This is the ONLY way to create a new buffer. */ static int top_file_num = 1; /* highest file number */ buf_T * buflist_new(ffname, sfname, lnum, flags) char_u *ffname; /* full path of fname or relative */ char_u *sfname; /* short fname or NULL */ linenr_T lnum; /* preferred cursor line */ int flags; /* BLN_ defines */ { buf_T *buf; #ifdef UNIX struct stat st; #endif fname_expand(curbuf, &ffname, &sfname); /* will allocate ffname */ /* * If file name already exists in the list, update the entry. */ #ifdef UNIX /* On Unix we can use inode numbers when the file exists. Works better * for hard links. */ if (sfname == NULL || mch_stat((char *)sfname, &st) < 0) st.st_dev = (dev_T)-1; #endif if (ffname != NULL && !(flags & BLN_DUMMY) && (buf = #ifdef UNIX buflist_findname_stat(ffname, &st) #else buflist_findname(ffname) #endif ) != NULL) { vim_free(ffname); if (lnum != 0) buflist_setfpos(buf, curwin, lnum, (colnr_T)0, FALSE); /* copy the options now, if 'cpo' doesn't have 's' and not done * already */ buf_copy_options(buf, 0); if ((flags & BLN_LISTED) && !buf->b_p_bl) { buf->b_p_bl = TRUE; #ifdef FEAT_AUTOCMD if (!(flags & BLN_DUMMY)) apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, buf); #endif } return buf; } /* * If the current buffer has no name and no contents, use the current * buffer. Otherwise: Need to allocate a new buffer structure. * * This is the ONLY place where a new buffer structure is allocated! * (A spell file buffer is allocated in spell.c, but that's not a normal * buffer.) */ buf = NULL; if ((flags & BLN_CURBUF) && curbuf != NULL && curbuf->b_ffname == NULL && curbuf->b_nwindows <= 1 && (curbuf->b_ml.ml_mfp == NULL || bufempty())) { buf = curbuf; #ifdef FEAT_AUTOCMD /* It's like this buffer is deleted. Watch out for autocommands that * change curbuf! If that happens, allocate a new buffer anyway. */ if (curbuf->b_p_bl) apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf); if (buf == curbuf) apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf); # ifdef FEAT_EVAL if (aborting()) /* autocmds may abort script processing */ return NULL; # endif #endif #ifdef FEAT_QUICKFIX # ifdef FEAT_AUTOCMD if (buf == curbuf) # endif { /* Make sure 'bufhidden' and 'buftype' are empty */ clear_string_option(&buf->b_p_bh); clear_string_option(&buf->b_p_bt); } #endif } if (buf != curbuf || curbuf == NULL) { buf = (buf_T *)alloc_clear((unsigned)sizeof(buf_T)); if (buf == NULL) { vim_free(ffname); return NULL; } } if (ffname != NULL) { buf->b_ffname = ffname; buf->b_sfname = vim_strsave(sfname); } clear_wininfo(buf); buf->b_wininfo = (wininfo_T *)alloc_clear((unsigned)sizeof(wininfo_T)); if ((ffname != NULL && (buf->b_ffname == NULL || buf->b_sfname == NULL)) || buf->b_wininfo == NULL) { vim_free(buf->b_ffname); buf->b_ffname = NULL; vim_free(buf->b_sfname); buf->b_sfname = NULL; if (buf != curbuf) free_buffer(buf); return NULL; } if (buf == curbuf) { /* free all things allocated for this buffer */ buf_freeall(buf, 0); if (buf != curbuf) /* autocommands deleted the buffer! */ return NULL; #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL) if (aborting()) /* autocmds may abort script processing */ return NULL; #endif /* buf->b_nwindows = 0; why was this here? */ free_buffer_stuff(buf, FALSE); /* delete local variables et al. */ #ifdef FEAT_KEYMAP /* need to reload lmaps and set b:keymap_name */ curbuf->b_kmap_state |= KEYMAP_INIT; #endif } else { /* * put new buffer at the end of the buffer list */ buf->b_next = NULL; if (firstbuf == NULL) /* buffer list is empty */ { buf->b_prev = NULL; firstbuf = buf; } else /* append new buffer at end of list */ { lastbuf->b_next = buf; buf->b_prev = lastbuf; } lastbuf = buf; buf->b_fnum = top_file_num++; if (top_file_num < 0) /* wrap around (may cause duplicates) */ { EMSG(_("W14: Warning: List of file names overflow")); if (emsg_silent == 0) { out_flush(); ui_delay(3000L, TRUE); /* make sure it is noticed */ } top_file_num = 1; } /* * Always copy the options from the current buffer. */ buf_copy_options(buf, BCO_ALWAYS); } buf->b_wininfo->wi_fpos.lnum = lnum; buf->b_wininfo->wi_win = curwin; #ifdef FEAT_EVAL init_var_dict(&buf->b_vars, &buf->b_bufvar); /* init b: variables */ #endif #ifdef FEAT_SYN_HL hash_init(&buf->b_s.b_keywtab); hash_init(&buf->b_s.b_keywtab_ic); #endif buf->b_fname = buf->b_sfname; #ifdef UNIX if (st.st_dev == (dev_T)-1) buf->b_dev_valid = FALSE; else { buf->b_dev_valid = TRUE; buf->b_dev = st.st_dev; buf->b_ino = st.st_ino; } #endif buf->b_u_synced = TRUE; buf->b_flags = BF_CHECK_RO | BF_NEVERLOADED; if (flags & BLN_DUMMY) buf->b_flags |= BF_DUMMY; buf_clear_file(buf); clrallmarks(buf); /* clear marks */ fmarks_check_names(buf); /* check file marks for this file */ buf->b_p_bl = (flags & BLN_LISTED) ? TRUE : FALSE; /* init 'buflisted' */ #ifdef FEAT_AUTOCMD if (!(flags & BLN_DUMMY)) { apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, buf); if (flags & BLN_LISTED) apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, buf); # ifdef FEAT_EVAL if (aborting()) /* autocmds may abort script processing */ return NULL; # endif } #endif return buf; } /* * Free the memory for the options of a buffer. * If "free_p_ff" is TRUE also free 'fileformat', 'buftype' and * 'fileencoding'. */ void free_buf_options(buf, free_p_ff) buf_T *buf; int free_p_ff; { if (free_p_ff) { #ifdef FEAT_MBYTE clear_string_option(&buf->b_p_fenc); #endif clear_string_option(&buf->b_p_ff); #ifdef FEAT_QUICKFIX clear_string_option(&buf->b_p_bh); clear_string_option(&buf->b_p_bt); #endif } #ifdef FEAT_FIND_ID clear_string_option(&buf->b_p_def); clear_string_option(&buf->b_p_inc); # ifdef FEAT_EVAL clear_string_option(&buf->b_p_inex); # endif #endif #if defined(FEAT_CINDENT) && defined(FEAT_EVAL) clear_string_option(&buf->b_p_inde); clear_string_option(&buf->b_p_indk); #endif #if defined(FEAT_BEVAL) && defined(FEAT_EVAL) clear_string_option(&buf->b_p_bexpr); #endif #if defined(FEAT_CRYPT) clear_string_option(&buf->b_p_cm); #endif #if defined(FEAT_EVAL) clear_string_option(&buf->b_p_fex); #endif #ifdef FEAT_CRYPT clear_string_option(&buf->b_p_key); #endif clear_string_option(&buf->b_p_kp); clear_string_option(&buf->b_p_mps); clear_string_option(&buf->b_p_fo); clear_string_option(&buf->b_p_flp); clear_string_option(&buf->b_p_isk); #ifdef FEAT_KEYMAP clear_string_option(&buf->b_p_keymap); ga_clear(&buf->b_kmap_ga); #endif #ifdef FEAT_COMMENTS clear_string_option(&buf->b_p_com); #endif #ifdef FEAT_FOLDING clear_string_option(&buf->b_p_cms); #endif clear_string_option(&buf->b_p_nf); #ifdef FEAT_SYN_HL clear_string_option(&buf->b_p_syn); #endif #ifdef FEAT_SPELL clear_string_option(&buf->b_s.b_p_spc); clear_string_option(&buf->b_s.b_p_spf); vim_free(buf->b_s.b_cap_prog); buf->b_s.b_cap_prog = NULL; clear_string_option(&buf->b_s.b_p_spl); #endif #ifdef FEAT_SEARCHPATH clear_string_option(&buf->b_p_sua); #endif #ifdef FEAT_AUTOCMD clear_string_option(&buf->b_p_ft); #endif #ifdef FEAT_CINDENT clear_string_option(&buf->b_p_cink); clear_string_option(&buf->b_p_cino); #endif #if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT) clear_string_option(&buf->b_p_cinw); #endif #ifdef FEAT_INS_EXPAND clear_string_option(&buf->b_p_cpt); #endif #ifdef FEAT_COMPL_FUNC clear_string_option(&buf->b_p_cfu); clear_string_option(&buf->b_p_ofu); #endif #ifdef FEAT_QUICKFIX clear_string_option(&buf->b_p_gp); clear_string_option(&buf->b_p_mp); clear_string_option(&buf->b_p_efm); #endif clear_string_option(&buf->b_p_ep); clear_string_option(&buf->b_p_path); clear_string_option(&buf->b_p_tags); #ifdef FEAT_INS_EXPAND clear_string_option(&buf->b_p_dict); clear_string_option(&buf->b_p_tsr); #endif #ifdef FEAT_TEXTOBJ clear_string_option(&buf->b_p_qe); #endif buf->b_p_ar = -1; } /* * get alternate file n * set linenr to lnum or altfpos.lnum if lnum == 0 * also set cursor column to altfpos.col if 'startofline' is not set. * if (options & GETF_SETMARK) call setpcmark() * if (options & GETF_ALT) we are jumping to an alternate file. * if (options & GETF_SWITCH) respect 'switchbuf' settings when jumping * * return FAIL for failure, OK for success */ int buflist_getfile(n, lnum, options, forceit) int n; linenr_T lnum; int options; int forceit; { buf_T *buf; #ifdef FEAT_WINDOWS win_T *wp = NULL; #endif pos_T *fpos; colnr_T col; buf = buflist_findnr(n); if (buf == NULL) { if ((options & GETF_ALT) && n == 0) EMSG(_(e_noalt)); else EMSGN(_("E92: Buffer %ld not found"), n); return FAIL; } /* if alternate file is the current buffer, nothing to do */ if (buf == curbuf) return OK; if (text_locked()) { text_locked_msg(); return FAIL; } #ifdef FEAT_AUTOCMD if (curbuf_locked()) return FAIL; #endif /* altfpos may be changed by getfile(), get it now */ if (lnum == 0) { fpos = buflist_findfpos(buf); lnum = fpos->lnum; col = fpos->col; } else col = 0; #ifdef FEAT_WINDOWS if (options & GETF_SWITCH) { /* If 'switchbuf' contains "useopen": jump to first window containing * "buf" if one exists */ if (swb_flags & SWB_USEOPEN) wp = buf_jump_open_win(buf); /* If 'switchbuf' contians "usetab": jump to first window in any tab * page containing "buf" if one exists */ if (wp == NULL && (swb_flags & SWB_USETAB)) wp = buf_jump_open_tab(buf); /* If 'switchbuf' contains "split" or "newtab" and the current buffer * isn't empty: open new window */ if (wp == NULL && (swb_flags & (SWB_SPLIT | SWB_NEWTAB)) && !bufempty()) { if (swb_flags & SWB_NEWTAB) /* Open in a new tab */ tabpage_new(); else if (win_split(0, 0) == FAIL) /* Open in a new window */ return FAIL; RESET_BINDING(curwin); } } #endif ++RedrawingDisabled; if (getfile(buf->b_fnum, NULL, NULL, (options & GETF_SETMARK), lnum, forceit) <= 0) { --RedrawingDisabled; /* cursor is at to BOL and w_cursor.lnum is checked due to getfile() */ if (!p_sol && col != 0) { curwin->w_cursor.col = col; check_cursor_col(); #ifdef FEAT_VIRTUALEDIT curwin->w_cursor.coladd = 0; #endif curwin->w_set_curswant = TRUE; } return OK; } --RedrawingDisabled; return FAIL; } /* * go to the last know line number for the current buffer */ void buflist_getfpos() { pos_T *fpos; fpos = buflist_findfpos(curbuf); curwin->w_cursor.lnum = fpos->lnum; check_cursor_lnum(); if (p_sol) curwin->w_cursor.col = 0; else { curwin->w_cursor.col = fpos->col; check_cursor_col(); #ifdef FEAT_VIRTUALEDIT curwin->w_cursor.coladd = 0; #endif curwin->w_set_curswant = TRUE; } } #if defined(FEAT_QUICKFIX) || defined(FEAT_EVAL) || defined(PROTO) /* * Find file in buffer list by name (it has to be for the current window). * Returns NULL if not found. */ buf_T * buflist_findname_exp(fname) char_u *fname; { char_u *ffname; buf_T *buf = NULL; /* First make the name into a full path name */ ffname = FullName_save(fname, #ifdef UNIX TRUE /* force expansion, get rid of symbolic links */ #else FALSE #endif ); if (ffname != NULL) { buf = buflist_findname(ffname); vim_free(ffname); } return buf; } #endif /* * Find file in buffer list by name (it has to be for the current window). * "ffname" must have a full path. * Skips dummy buffers. * Returns NULL if not found. */ buf_T * buflist_findname(ffname) char_u *ffname; { #ifdef UNIX struct stat st; if (mch_stat((char *)ffname, &st) < 0) st.st_dev = (dev_T)-1; return buflist_findname_stat(ffname, &st); } /* * Same as buflist_findname(), but pass the stat structure to avoid getting it * twice for the same file. * Returns NULL if not found. */ static buf_T * buflist_findname_stat(ffname, stp) char_u *ffname; struct stat *stp; { #endif buf_T *buf; for (buf = firstbuf; buf != NULL; buf = buf->b_next) if ((buf->b_flags & BF_DUMMY) == 0 && !otherfile_buf(buf, ffname #ifdef UNIX , stp #endif )) return buf; return NULL; } #if defined(FEAT_LISTCMDS) || defined(FEAT_EVAL) || defined(FEAT_PERL) || defined(PROTO) /* * Find file in buffer list by a regexp pattern. * Return fnum of the found buffer. * Return < 0 for error. */ int buflist_findpat(pattern, pattern_end, unlisted, diffmode) char_u *pattern; char_u *pattern_end; /* pointer to first char after pattern */ int unlisted; /* find unlisted buffers */ int diffmode UNUSED; /* find diff-mode buffers only */ { buf_T *buf; regprog_T *prog; int match = -1; int find_listed; char_u *pat; char_u *patend; int attempt; char_u *p; int toggledollar; if (pattern_end == pattern + 1 && (*pattern == '%' || *pattern == '#')) { if (*pattern == '%') match = curbuf->b_fnum; else match = curwin->w_alt_fnum; #ifdef FEAT_DIFF if (diffmode && !diff_mode_buf(buflist_findnr(match))) match = -1; #endif } /* * Try four ways of matching a listed buffer: * attempt == 0: without '^' or '$' (at any position) * attempt == 1: with '^' at start (only at position 0) * attempt == 2: with '$' at end (only match at end) * attempt == 3: with '^' at start and '$' at end (only full match) * Repeat this for finding an unlisted buffer if there was no matching * listed buffer. */ else { pat = file_pat_to_reg_pat(pattern, pattern_end, NULL, FALSE); if (pat == NULL) return -1; patend = pat + STRLEN(pat) - 1; toggledollar = (patend > pat && *patend == '$'); /* First try finding a listed buffer. If not found and "unlisted" * is TRUE, try finding an unlisted buffer. */ find_listed = TRUE; for (;;) { for (attempt = 0; attempt <= 3; ++attempt) { /* may add '^' and '$' */ if (toggledollar) *patend = (attempt < 2) ? NUL : '$'; /* add/remove '$' */ p = pat; if (*p == '^' && !(attempt & 1)) /* add/remove '^' */ ++p; prog = vim_regcomp(p, p_magic ? RE_MAGIC : 0); if (prog == NULL) { vim_free(pat); return -1; } for (buf = firstbuf; buf != NULL; buf = buf->b_next) if (buf->b_p_bl == find_listed #ifdef FEAT_DIFF && (!diffmode || diff_mode_buf(buf)) #endif && buflist_match(prog, buf) != NULL) { if (match >= 0) /* already found a match */ { match = -2; break; } match = buf->b_fnum; /* remember first match */ } vim_free(prog); if (match >= 0) /* found one match */ break; } /* Only search for unlisted buffers if there was no match with * a listed buffer. */ if (!unlisted || !find_listed || match != -1) break; find_listed = FALSE; } vim_free(pat); } if (match == -2) EMSG2(_("E93: More than one match for %s"), pattern); else if (match < 0) EMSG2(_("E94: No matching buffer for %s"), pattern); return match; } #endif #if defined(FEAT_CMDL_COMPL) || defined(PROTO) /* * Find all buffer names that match. * For command line expansion of ":buf" and ":sbuf". * Return OK if matches found, FAIL otherwise. */ int ExpandBufnames(pat, num_file, file, options) char_u *pat; int *num_file; char_u ***file; int options; { int count = 0; buf_T *buf; int round; char_u *p; int attempt; regprog_T *prog; char_u *patc; *num_file = 0; /* return values in case of FAIL */ *file = NULL; /* Make a copy of "pat" and change "^" to "\(^\|[\/]\)". */ if (*pat == '^') { patc = alloc((unsigned)STRLEN(pat) + 11); if (patc == NULL) return FAIL; STRCPY(patc, "\\(^\\|[\\/]\\)"); STRCPY(patc + 11, pat + 1); } else patc = pat; /* * attempt == 0: try match with '\<', match at start of word * attempt == 1: try match without '\<', match anywhere */ for (attempt = 0; attempt <= 1; ++attempt) { if (attempt > 0 && patc == pat) break; /* there was no anchor, no need to try again */ prog = vim_regcomp(patc + attempt * 11, RE_MAGIC); if (prog == NULL) { if (patc != pat) vim_free(patc); return FAIL; } /* * round == 1: Count the matches. * round == 2: Build the array to keep the matches. */ for (round = 1; round <= 2; ++round) { count = 0; for (buf = firstbuf; buf != NULL; buf = buf->b_next) { if (!buf->b_p_bl) /* skip unlisted buffers */ continue; p = buflist_match(prog, buf); if (p != NULL) { if (round == 1) ++count; else { if (options & WILD_HOME_REPLACE) p = home_replace_save(buf, p); else p = vim_strsave(p); (*file)[count++] = p; } } } if (count == 0) /* no match found, break here */ break; if (round == 1) { *file = (char_u **)alloc((unsigned)(count * sizeof(char_u *))); if (*file == NULL) { vim_free(prog); if (patc != pat) vim_free(patc); return FAIL; } } } vim_free(prog); if (count) /* match(es) found, break here */ break; } if (patc != pat) vim_free(patc); *num_file = count; return (count == 0 ? FAIL : OK); } #endif /* FEAT_CMDL_COMPL */ #ifdef HAVE_BUFLIST_MATCH /* * Check for a match on the file name for buffer "buf" with regprog "prog". */ static char_u * buflist_match(prog, buf) regprog_T *prog; buf_T *buf; { char_u *match; /* First try the short file name, then the long file name. */ match = fname_match(prog, buf->b_sfname); if (match == NULL) match = fname_match(prog, buf->b_ffname); return match; } /* * Try matching the regexp in "prog" with file name "name". * Return "name" when there is a match, NULL when not. */ static char_u * fname_match(prog, name) regprog_T *prog; char_u *name; { char_u *match = NULL; char_u *p; regmatch_T regmatch; if (name != NULL) { regmatch.regprog = prog; #ifdef CASE_INSENSITIVE_FILENAME regmatch.rm_ic = TRUE; /* Always ignore case */ #else regmatch.rm_ic = FALSE; /* Never ignore case */ #endif if (vim_regexec(&regmatch, name, (colnr_T)0)) match = name; else { /* Replace $(HOME) with '~' and try matching again. */ p = home_replace_save(NULL, name); if (p != NULL && vim_regexec(&regmatch, p, (colnr_T)0)) match = name; vim_free(p); } } return match; } #endif /* * find file in buffer list by number */ buf_T * buflist_findnr(nr) int nr; { buf_T *buf; if (nr == 0) nr = curwin->w_alt_fnum; for (buf = firstbuf; buf != NULL; buf = buf->b_next) if (buf->b_fnum == nr) return (buf); return NULL; } /* * Get name of file 'n' in the buffer list. * When the file has no name an empty string is returned. * home_replace() is used to shorten the file name (used for marks). * Returns a pointer to allocated memory, of NULL when failed. */ char_u * buflist_nr2name(n, fullname, helptail) int n; int fullname; int helptail; /* for help buffers return tail only */ { buf_T *buf; buf = buflist_findnr(n); if (buf == NULL) return NULL; return home_replace_save(helptail ? buf : NULL, fullname ? buf->b_ffname : buf->b_fname); } /* * Set the "lnum" and "col" for the buffer "buf" and the current window. * When "copy_options" is TRUE save the local window option values. * When "lnum" is 0 only do the options. */ static void buflist_setfpos(buf, win, lnum, col, copy_options) buf_T *buf; win_T *win; linenr_T lnum; colnr_T col; int copy_options; { wininfo_T *wip; for (wip = buf->b_wininfo; wip != NULL; wip = wip->wi_next) if (wip->wi_win == win) break; if (wip == NULL) { /* allocate a new entry */ wip = (wininfo_T *)alloc_clear((unsigned)sizeof(wininfo_T)); if (wip == NULL) return; wip->wi_win = win; if (lnum == 0) /* set lnum even when it's 0 */ lnum = 1; } else { /* remove the entry from the list */ if (wip->wi_prev) wip->wi_prev->wi_next = wip->wi_next; else buf->b_wininfo = wip->wi_next; if (wip->wi_next) wip->wi_next->wi_prev = wip->wi_prev; if (copy_options && wip->wi_optset) { clear_winopt(&wip->wi_opt); #ifdef FEAT_FOLDING deleteFoldRecurse(&wip->wi_folds); #endif } } if (lnum != 0) { wip->wi_fpos.lnum = lnum; wip->wi_fpos.col = col; } if (copy_options) { /* Save the window-specific option values. */ copy_winopt(&win->w_onebuf_opt, &wip->wi_opt); #ifdef FEAT_FOLDING wip->wi_fold_manual = win->w_fold_manual; cloneFoldGrowArray(&win->w_folds, &wip->wi_folds); #endif wip->wi_optset = TRUE; } /* insert the entry in front of the list */ wip->wi_next = buf->b_wininfo; buf->b_wininfo = wip; wip->wi_prev = NULL; if (wip->wi_next) wip->wi_next->wi_prev = wip; return; } #ifdef FEAT_DIFF static int wininfo_other_tab_diff __ARGS((wininfo_T *wip)); /* * Return TRUE when "wip" has 'diff' set and the diff is only for another tab * page. That's because a diff is local to a tab page. */ static int wininfo_other_tab_diff(wip) wininfo_T *wip; { win_T *wp; if (wip->wi_opt.wo_diff) { for (wp = firstwin; wp != NULL; wp = wp->w_next) /* return FALSE when it's a window in the current tab page, thus * the buffer was in diff mode here */ if (wip->wi_win == wp) return FALSE; return TRUE; } return FALSE; } #endif /* * Find info for the current window in buffer "buf". * If not found, return the info for the most recently used window. * When "skip_diff_buffer" is TRUE avoid windows with 'diff' set that is in * another tab page. * Returns NULL when there isn't any info. */ static wininfo_T * find_wininfo(buf, skip_diff_buffer) buf_T *buf; int skip_diff_buffer UNUSED; { wininfo_T *wip; for (wip = buf->b_wininfo; wip != NULL; wip = wip->wi_next) if (wip->wi_win == curwin #ifdef FEAT_DIFF && (!skip_diff_buffer || !wininfo_other_tab_diff(wip)) #endif ) break; /* If no wininfo for curwin, use the first in the list (that doesn't have * 'diff' set and is in another tab page). */ if (wip == NULL) { #ifdef FEAT_DIFF if (skip_diff_buffer) { for (wip = buf->b_wininfo; wip != NULL; wip = wip->wi_next) if (!wininfo_other_tab_diff(wip)) break; } else #endif wip = buf->b_wininfo; } return wip; } /* * Reset the local window options to the values last used in this window. * If the buffer wasn't used in this window before, use the values from * the most recently used window. If the values were never set, use the * global values for the window. */ void get_winopts(buf) buf_T *buf; { wininfo_T *wip; clear_winopt(&curwin->w_onebuf_opt); #ifdef FEAT_FOLDING clearFolding(curwin); #endif wip = find_wininfo(buf, TRUE); if (wip != NULL && wip->wi_optset) { copy_winopt(&wip->wi_opt, &curwin->w_onebuf_opt); #ifdef FEAT_FOLDING curwin->w_fold_manual = wip->wi_fold_manual; curwin->w_foldinvalid = TRUE; cloneFoldGrowArray(&wip->wi_folds, &curwin->w_folds); #endif } else copy_winopt(&curwin->w_allbuf_opt, &curwin->w_onebuf_opt); #ifdef FEAT_FOLDING /* Set 'foldlevel' to 'foldlevelstart' if it's not negative. */ if (p_fdls >= 0) curwin->w_p_fdl = p_fdls; #endif #ifdef FEAT_SYN_HL check_colorcolumn(curwin); #endif } /* * Find the position (lnum and col) for the buffer 'buf' for the current * window. * Returns a pointer to no_position if no position is found. */ pos_T * buflist_findfpos(buf) buf_T *buf; { wininfo_T *wip; static pos_T no_position = INIT_POS_T(1, 0, 0); wip = find_wininfo(buf, FALSE); if (wip != NULL) return &(wip->wi_fpos); else return &no_position; } /* * Find the lnum for the buffer 'buf' for the current window. */ linenr_T buflist_findlnum(buf) buf_T *buf; { return buflist_findfpos(buf)->lnum; } #if defined(FEAT_LISTCMDS) || defined(PROTO) /* * List all know file names (for :files and :buffers command). */ void buflist_list(eap) exarg_T *eap; { buf_T *buf; int len; int i; for (buf = firstbuf; buf != NULL && !got_int; buf = buf->b_next) { /* skip unlisted buffers, unless ! was used */ if (!buf->b_p_bl && !eap->forceit) continue; msg_putchar('\n'); if (buf_spname(buf) != NULL) STRCPY(NameBuff, buf_spname(buf)); else home_replace(buf, buf->b_fname, NameBuff, MAXPATHL, TRUE); len = vim_snprintf((char *)IObuff, IOSIZE - 20, "%3d%c%c%c%c%c \"%s\"", buf->b_fnum, buf->b_p_bl ? ' ' : 'u', buf == curbuf ? '%' : (curwin->w_alt_fnum == buf->b_fnum ? '#' : ' '), buf->b_ml.ml_mfp == NULL ? ' ' : (buf->b_nwindows == 0 ? 'h' : 'a'), !buf->b_p_ma ? '-' : (buf->b_p_ro ? '=' : ' '), (buf->b_flags & BF_READERR) ? 'x' : (bufIsChanged(buf) ? '+' : ' '), NameBuff); /* put "line 999" in column 40 or after the file name */ i = 40 - vim_strsize(IObuff); do { IObuff[len++] = ' '; } while (--i > 0 && len < IOSIZE - 18); vim_snprintf((char *)IObuff + len, (size_t)(IOSIZE - len), _("line %ld"), buf == curbuf ? curwin->w_cursor.lnum : (long)buflist_findlnum(buf)); msg_outtrans(IObuff); out_flush(); /* output one line at a time */ ui_breakcheck(); } } #endif /* * Get file name and line number for file 'fnum'. * Used by DoOneCmd() for translating '%' and '#'. * Used by insert_reg() and cmdline_paste() for '#' register. * Return FAIL if not found, OK for success. */ int buflist_name_nr(fnum, fname, lnum) int fnum; char_u **fname; linenr_T *lnum; { buf_T *buf; buf = buflist_findnr(fnum); if (buf == NULL || buf->b_fname == NULL) return FAIL; *fname = buf->b_fname; *lnum = buflist_findlnum(buf); return OK; } /* * Set the file name for "buf"' to 'ffname', short file name to 'sfname'. * The file name with the full path is also remembered, for when :cd is used. * Returns FAIL for failure (file name already in use by other buffer) * OK otherwise. */ int setfname(buf, ffname, sfname, message) buf_T *buf; char_u *ffname, *sfname; int message; /* give message when buffer already exists */ { buf_T *obuf = NULL; #ifdef UNIX struct stat st; #endif if (ffname == NULL || *ffname == NUL) { /* Removing the name. */ vim_free(buf->b_ffname); vim_free(buf->b_sfname); buf->b_ffname = NULL; buf->b_sfname = NULL; #ifdef UNIX st.st_dev = (dev_T)-1; #endif } else { fname_expand(buf, &ffname, &sfname); /* will allocate ffname */ if (ffname == NULL) /* out of memory */ return FAIL; /* * if the file name is already used in another buffer: * - if the buffer is loaded, fail * - if the buffer is not loaded, delete it from the list */ #ifdef UNIX if (mch_stat((char *)ffname, &st) < 0) st.st_dev = (dev_T)-1; #endif if (!(buf->b_flags & BF_DUMMY)) #ifdef UNIX obuf = buflist_findname_stat(ffname, &st); #else obuf = buflist_findname(ffname); #endif if (obuf != NULL && obuf != buf) { if (obuf->b_ml.ml_mfp != NULL) /* it's loaded, fail */ { if (message) EMSG(_("E95: Buffer with this name already exists")); vim_free(ffname); return FAIL; } /* delete from the list */ close_buffer(NULL, obuf, DOBUF_WIPE, FALSE); } sfname = vim_strsave(sfname); if (ffname == NULL || sfname == NULL) { vim_free(sfname); vim_free(ffname); return FAIL; } #ifdef USE_FNAME_CASE # ifdef USE_LONG_FNAME if (USE_LONG_FNAME) # endif fname_case(sfname, 0); /* set correct case for short file name */ #endif vim_free(buf->b_ffname); vim_free(buf->b_sfname); buf->b_ffname = ffname; buf->b_sfname = sfname; } buf->b_fname = buf->b_sfname; #ifdef UNIX if (st.st_dev == (dev_T)-1) buf->b_dev_valid = FALSE; else { buf->b_dev_valid = TRUE; buf->b_dev = st.st_dev; buf->b_ino = st.st_ino; } #endif #ifndef SHORT_FNAME buf->b_shortname = FALSE; #endif buf_name_changed(buf); return OK; } /* * Crude way of changing the name of a buffer. Use with care! * The name should be relative to the current directory. */ void buf_set_name(fnum, name) int fnum; char_u *name; { buf_T *buf; buf = buflist_findnr(fnum); if (buf != NULL) { vim_free(buf->b_sfname); vim_free(buf->b_ffname); buf->b_ffname = vim_strsave(name); buf->b_sfname = NULL; /* Allocate ffname and expand into full path. Also resolves .lnk * files on Win32. */ fname_expand(buf, &buf->b_ffname, &buf->b_sfname); buf->b_fname = buf->b_sfname; } } /* * Take care of what needs to be done when the name of buffer "buf" has * changed. */ void buf_name_changed(buf) buf_T *buf; { /* * If the file name changed, also change the name of the swapfile */ if (buf->b_ml.ml_mfp != NULL) ml_setname(buf); if (curwin->w_buffer == buf) check_arg_idx(curwin); /* check file name for arg list */ #ifdef FEAT_TITLE maketitle(); /* set window title */ #endif #ifdef FEAT_WINDOWS status_redraw_all(); /* status lines need to be redrawn */ #endif fmarks_check_names(buf); /* check named file marks */ ml_timestamp(buf); /* reset timestamp */ } /* * set alternate file name for current window * * Used by do_one_cmd(), do_write() and do_ecmd(). * Return the buffer. */ buf_T * setaltfname(ffname, sfname, lnum) char_u *ffname; char_u *sfname; linenr_T lnum; { buf_T *buf; /* Create a buffer. 'buflisted' is not set if it's a new buffer */ buf = buflist_new(ffname, sfname, lnum, 0); if (buf != NULL && !cmdmod.keepalt) curwin->w_alt_fnum = buf->b_fnum; return buf; } /* * Get alternate file name for current window. * Return NULL if there isn't any, and give error message if requested. */ char_u * getaltfname(errmsg) int errmsg; /* give error message */ { char_u *fname; linenr_T dummy; if (buflist_name_nr(0, &fname, &dummy) == FAIL) { if (errmsg) EMSG(_(e_noalt)); return NULL; } return fname; } /* * Add a file name to the buflist and return its number. * Uses same flags as buflist_new(), except BLN_DUMMY. * * used by qf_init(), main() and doarglist() */ int buflist_add(fname, flags) char_u *fname; int flags; { buf_T *buf; buf = buflist_new(fname, NULL, (linenr_T)0, flags); if (buf != NULL) return buf->b_fnum; return 0; } #if defined(BACKSLASH_IN_FILENAME) || defined(PROTO) /* * Adjust slashes in file names. Called after 'shellslash' was set. */ void buflist_slash_adjust() { buf_T *bp; for (bp = firstbuf; bp != NULL; bp = bp->b_next) { if (bp->b_ffname != NULL) slash_adjust(bp->b_ffname); if (bp->b_sfname != NULL) slash_adjust(bp->b_sfname); } } #endif /* * Set alternate cursor position for the current buffer and window "win". * Also save the local window option values. */ void buflist_altfpos(win) win_T *win; { buflist_setfpos(curbuf, win, win->w_cursor.lnum, win->w_cursor.col, TRUE); } /* * Return TRUE if 'ffname' is not the same file as current file. * Fname must have a full path (expanded by mch_FullName()). */ int otherfile(ffname) char_u *ffname; { return otherfile_buf(curbuf, ffname #ifdef UNIX , NULL #endif ); } static int otherfile_buf(buf, ffname #ifdef UNIX , stp #endif ) buf_T *buf; char_u *ffname; #ifdef UNIX struct stat *stp; #endif { /* no name is different */ if (ffname == NULL || *ffname == NUL || buf->b_ffname == NULL) return TRUE; if (fnamecmp(ffname, buf->b_ffname) == 0) return FALSE; #ifdef UNIX { struct stat st; /* If no struct stat given, get it now */ if (stp == NULL) { if (!buf->b_dev_valid || mch_stat((char *)ffname, &st) < 0) st.st_dev = (dev_T)-1; stp = &st; } /* Use dev/ino to check if the files are the same, even when the names * are different (possible with links). Still need to compare the * name above, for when the file doesn't exist yet. * Problem: The dev/ino changes when a file is deleted (and created * again) and remains the same when renamed/moved. We don't want to * mch_stat() each buffer each time, that would be too slow. Get the * dev/ino again when they appear to match, but not when they appear * to be different: Could skip a buffer when it's actually the same * file. */ if (buf_same_ino(buf, stp)) { buf_setino(buf); if (buf_same_ino(buf, stp)) return FALSE; } } #endif return TRUE; } #if defined(UNIX) || defined(PROTO) /* * Set inode and device number for a buffer. * Must always be called when b_fname is changed!. */ void buf_setino(buf) buf_T *buf; { struct stat st; if (buf->b_fname != NULL && mch_stat((char *)buf->b_fname, &st) >= 0) { buf->b_dev_valid = TRUE; buf->b_dev = st.st_dev; buf->b_ino = st.st_ino; } else buf->b_dev_valid = FALSE; } /* * Return TRUE if dev/ino in buffer "buf" matches with "stp". */ static int buf_same_ino(buf, stp) buf_T *buf; struct stat *stp; { return (buf->b_dev_valid && stp->st_dev == buf->b_dev && stp->st_ino == buf->b_ino); } #endif /* * Print info about the current buffer. */ void fileinfo(fullname, shorthelp, dont_truncate) int fullname; /* when non-zero print full path */ int shorthelp; int dont_truncate; { char_u *name; int n; char_u *p; char_u *buffer; size_t len; buffer = alloc(IOSIZE); if (buffer == NULL) return; if (fullname > 1) /* 2 CTRL-G: include buffer number */ { vim_snprintf((char *)buffer, IOSIZE, "buf %d: ", curbuf->b_fnum); p = buffer + STRLEN(buffer); } else p = buffer; *p++ = '"'; if (buf_spname(curbuf) != NULL) STRCPY(p, buf_spname(curbuf)); else { if (!fullname && curbuf->b_fname != NULL) name = curbuf->b_fname; else name = curbuf->b_ffname; home_replace(shorthelp ? curbuf : NULL, name, p, (int)(IOSIZE - (p - buffer)), TRUE); } vim_snprintf_add((char *)buffer, IOSIZE, "\"%s%s%s%s%s%s", curbufIsChanged() ? (shortmess(SHM_MOD) ? " [+]" : _(" [Modified]")) : " ", (curbuf->b_flags & BF_NOTEDITED) #ifdef FEAT_QUICKFIX && !bt_dontwrite(curbuf) #endif ? _("[Not edited]") : "", (curbuf->b_flags & BF_NEW) #ifdef FEAT_QUICKFIX && !bt_dontwrite(curbuf) #endif ? _("[New file]") : "", (curbuf->b_flags & BF_READERR) ? _("[Read errors]") : "", curbuf->b_p_ro ? (shortmess(SHM_RO) ? "[RO]" : _("[readonly]")) : "", (curbufIsChanged() || (curbuf->b_flags & BF_WRITE_MASK) || curbuf->b_p_ro) ? " " : ""); /* With 32 bit longs and more than 21,474,836 lines multiplying by 100 * causes an overflow, thus for large numbers divide instead. */ if (curwin->w_cursor.lnum > 1000000L) n = (int)(((long)curwin->w_cursor.lnum) / ((long)curbuf->b_ml.ml_line_count / 100L)); else n = (int)(((long)curwin->w_cursor.lnum * 100L) / (long)curbuf->b_ml.ml_line_count); if (curbuf->b_ml.ml_flags & ML_EMPTY) { vim_snprintf_add((char *)buffer, IOSIZE, "%s", _(no_lines_msg)); } #ifdef FEAT_CMDL_INFO else if (p_ru) { /* Current line and column are already on the screen -- webb */ if (curbuf->b_ml.ml_line_count == 1) vim_snprintf_add((char *)buffer, IOSIZE, _("1 line --%d%%--"), n); else vim_snprintf_add((char *)buffer, IOSIZE, _("%ld lines --%d%%--"), (long)curbuf->b_ml.ml_line_count, n); } #endif else { vim_snprintf_add((char *)buffer, IOSIZE, _("line %ld of %ld --%d%%-- col "), (long)curwin->w_cursor.lnum, (long)curbuf->b_ml.ml_line_count, n); validate_virtcol(); len = STRLEN(buffer); col_print(buffer + len, IOSIZE - len, (int)curwin->w_cursor.col + 1, (int)curwin->w_virtcol + 1); } (void)append_arg_number(curwin, buffer, IOSIZE, !shortmess(SHM_FILE)); if (dont_truncate) { /* Temporarily set msg_scroll to avoid the message being truncated. * First call msg_start() to get the message in the right place. */ msg_start(); n = msg_scroll; msg_scroll = TRUE; msg(buffer); msg_scroll = n; } else { p = msg_trunc_attr(buffer, FALSE, 0); if (restart_edit != 0 || (msg_scrolled && !need_wait_return)) /* Need to repeat the message after redrawing when: * - When restart_edit is set (otherwise there will be a delay * before redrawing). * - When the screen was scrolled but there is no wait-return * prompt. */ set_keep_msg(p, 0); } vim_free(buffer); } void col_print(buf, buflen, col, vcol) char_u *buf; size_t buflen; int col; int vcol; { if (col == vcol) vim_snprintf((char *)buf, buflen, "%d", col); else vim_snprintf((char *)buf, buflen, "%d-%d", col, vcol); } #if defined(FEAT_TITLE) || defined(PROTO) /* * put file name in title bar of window and in icon title */ static char_u *lasttitle = NULL; static char_u *lasticon = NULL; void maketitle() { char_u *p; char_u *t_str = NULL; char_u *i_name; char_u *i_str = NULL; int maxlen = 0; int len; int mustset; char_u buf[IOSIZE]; int off; if (!redrawing()) { /* Postpone updating the title when 'lazyredraw' is set. */ need_maketitle = TRUE; return; } need_maketitle = FALSE; if (!p_title && !p_icon && lasttitle == NULL && lasticon == NULL) return; if (p_title) { if (p_titlelen > 0) { maxlen = p_titlelen * Columns / 100; if (maxlen < 10) maxlen = 10; } t_str = buf; if (*p_titlestring != NUL) { #ifdef FEAT_STL_OPT if (stl_syntax & STL_IN_TITLE) { int use_sandbox = FALSE; int save_called_emsg = called_emsg; # ifdef FEAT_EVAL use_sandbox = was_set_insecurely((char_u *)"titlestring", 0); # endif called_emsg = FALSE; build_stl_str_hl(curwin, t_str, sizeof(buf), p_titlestring, use_sandbox, 0, maxlen, NULL, NULL); if (called_emsg) set_string_option_direct((char_u *)"titlestring", -1, (char_u *)"", OPT_FREE, SID_ERROR); called_emsg |= save_called_emsg; } else #endif t_str = p_titlestring; } else { /* format: "fname + (path) (1 of 2) - VIM" */ if (curbuf->b_fname == NULL) vim_strncpy(buf, (char_u *)_("[No Name]"), IOSIZE - 100); else { p = transstr(gettail(curbuf->b_fname)); vim_strncpy(buf, p, IOSIZE - 100); vim_free(p); } switch (bufIsChanged(curbuf) + (curbuf->b_p_ro * 2) + (!curbuf->b_p_ma * 4)) { case 1: STRCAT(buf, " +"); break; case 2: STRCAT(buf, " ="); break; case 3: STRCAT(buf, " =+"); break; case 4: case 6: STRCAT(buf, " -"); break; case 5: case 7: STRCAT(buf, " -+"); break; } if (curbuf->b_fname != NULL) { /* Get path of file, replace home dir with ~ */ off = (int)STRLEN(buf); buf[off++] = ' '; buf[off++] = '('; home_replace(curbuf, curbuf->b_ffname, buf + off, IOSIZE - off, TRUE); #ifdef BACKSLASH_IN_FILENAME /* avoid "c:/name" to be reduced to "c" */ if (isalpha(buf[off]) && buf[off + 1] == ':') off += 2; #endif /* remove the file name */ p = gettail_sep(buf + off); if (p == buf + off) /* must be a help buffer */ vim_strncpy(buf + off, (char_u *)_("help"), (size_t)(IOSIZE - off - 1)); else *p = NUL; /* translate unprintable chars */ p = transstr(buf + off); vim_strncpy(buf + off, p, (size_t)(IOSIZE - off - 1)); vim_free(p); STRCAT(buf, ")"); } append_arg_number(curwin, buf, IOSIZE, FALSE); #if defined(FEAT_CLIENTSERVER) if (serverName != NULL) { STRCAT(buf, " - "); vim_strcat(buf, serverName, IOSIZE); } else #endif STRCAT(buf, " - VIM"); if (maxlen > 0) { /* make it shorter by removing a bit in the middle */ if (vim_strsize(buf) > maxlen) trunc_string(buf, buf, maxlen, IOSIZE); } } } mustset = ti_change(t_str, &lasttitle); if (p_icon) { i_str = buf; if (*p_iconstring != NUL) { #ifdef FEAT_STL_OPT if (stl_syntax & STL_IN_ICON) { int use_sandbox = FALSE; int save_called_emsg = called_emsg; # ifdef FEAT_EVAL use_sandbox = was_set_insecurely((char_u *)"iconstring", 0); # endif called_emsg = FALSE; build_stl_str_hl(curwin, i_str, sizeof(buf), p_iconstring, use_sandbox, 0, 0, NULL, NULL); if (called_emsg) set_string_option_direct((char_u *)"iconstring", -1, (char_u *)"", OPT_FREE, SID_ERROR); called_emsg |= save_called_emsg; } else #endif i_str = p_iconstring; } else { if (buf_spname(curbuf) != NULL) i_name = (char_u *)buf_spname(curbuf); else /* use file name only in icon */ i_name = gettail(curbuf->b_ffname); *i_str = NUL; /* Truncate name at 100 bytes. */ len = (int)STRLEN(i_name); if (len > 100) { len -= 100; #ifdef FEAT_MBYTE if (has_mbyte) len += (*mb_tail_off)(i_name, i_name + len) + 1; #endif i_name += len; } STRCPY(i_str, i_name); trans_characters(i_str, IOSIZE); } } mustset |= ti_change(i_str, &lasticon); if (mustset) resettitle(); } /* * Used for title and icon: Check if "str" differs from "*last". Set "*last" * from "str" if it does. * Return TRUE when "*last" changed. */ static int ti_change(str, last) char_u *str; char_u **last; { if ((str == NULL) != (*last == NULL) || (str != NULL && *last != NULL && STRCMP(str, *last) != 0)) { vim_free(*last); if (str == NULL) *last = NULL; else *last = vim_strsave(str); return TRUE; } return FALSE; } /* * Put current window title back (used after calling a shell) */ void resettitle() { mch_settitle(lasttitle, lasticon); } # if defined(EXITFREE) || defined(PROTO) void free_titles() { vim_free(lasttitle); vim_free(lasticon); } # endif #endif /* FEAT_TITLE */ #if defined(FEAT_STL_OPT) || defined(FEAT_GUI_TABLINE) || defined(PROTO) /* * Build a string from the status line items in "fmt". * Return length of string in screen cells. * * Normally works for window "wp", except when working for 'tabline' then it * is "curwin". * * Items are drawn interspersed with the text that surrounds it * Specials: %-<wid>(xxx%) => group, %= => middle marker, %< => truncation * Item: %-<minwid>.<maxwid><itemch> All but <itemch> are optional * * If maxwidth is not zero, the string will be filled at any middle marker * or truncated if too long, fillchar is used for all whitespace. */ int build_stl_str_hl(wp, out, outlen, fmt, use_sandbox, fillchar, maxwidth, hltab, tabtab) win_T *wp; char_u *out; /* buffer to write into != NameBuff */ size_t outlen; /* length of out[] */ char_u *fmt; int use_sandbox UNUSED; /* "fmt" was set insecurely, use sandbox */ int fillchar; int maxwidth; struct stl_hlrec *hltab; /* return: HL attributes (can be NULL) */ struct stl_hlrec *tabtab; /* return: tab page nrs (can be NULL) */ { char_u *p; char_u *s; char_u *t; char_u *linecont; #ifdef FEAT_EVAL win_T *o_curwin; buf_T *o_curbuf; #endif int empty_line; colnr_T virtcol; long l; long n; int prevchar_isflag; int prevchar_isitem; int itemisflag; int fillable; char_u *str; long num; int width; int itemcnt; int curitem; int groupitem[STL_MAX_ITEM]; int groupdepth; struct stl_item { char_u *start; int minwid; int maxwid; enum { Normal, Empty, Group, Middle, Highlight, TabPage, Trunc } type; } item[STL_MAX_ITEM]; int minwid; int maxwid; int zeropad; char_u base; char_u opt; #define TMPLEN 70 char_u tmp[TMPLEN]; char_u *usefmt = fmt; struct stl_hlrec *sp; #ifdef FEAT_EVAL /* * When the format starts with "%!" then evaluate it as an expression and * use the result as the actual format string. */ if (fmt[0] == '%' && fmt[1] == '!') { usefmt = eval_to_string_safe(fmt + 2, NULL, use_sandbox); if (usefmt == NULL) usefmt = fmt; } #endif if (fillchar == 0) fillchar = ' '; #ifdef FEAT_MBYTE /* Can't handle a multi-byte fill character yet. */ else if (mb_char2len(fillchar) > 1) fillchar = '-'; #endif /* * Get line & check if empty (cursorpos will show "0-1"). * If inversion is possible we use it. Else '=' characters are used. */ linecont = ml_get_buf(wp->w_buffer, wp->w_cursor.lnum, FALSE); empty_line = (*linecont == NUL); groupdepth = 0; p = out; curitem = 0; prevchar_isflag = TRUE; prevchar_isitem = FALSE; for (s = usefmt; *s; ) { if (curitem == STL_MAX_ITEM) { /* There are too many items. Add the error code to the statusline * to give the user a hint about what went wrong. */ if (p + 6 < out + outlen) { mch_memmove(p, " E541", (size_t)5); p += 5; } break; } if (*s != NUL && *s != '%') prevchar_isflag = prevchar_isitem = FALSE; /* * Handle up to the next '%' or the end. */ while (*s != NUL && *s != '%' && p + 1 < out + outlen) *p++ = *s++; if (*s == NUL || p + 1 >= out + outlen) break; /* * Handle one '%' item. */ s++; if (*s == NUL) /* ignore trailing % */ break; if (*s == '%') { if (p + 1 >= out + outlen) break; *p++ = *s++; prevchar_isflag = prevchar_isitem = FALSE; continue; } if (*s == STL_MIDDLEMARK) { s++; if (groupdepth > 0) continue; item[curitem].type = Middle; item[curitem++].start = p; continue; } if (*s == STL_TRUNCMARK) { s++; item[curitem].type = Trunc; item[curitem++].start = p; continue; } if (*s == ')') { s++; if (groupdepth < 1) continue; groupdepth--; t = item[groupitem[groupdepth]].start; *p = NUL; l = vim_strsize(t); if (curitem > groupitem[groupdepth] + 1 && item[groupitem[groupdepth]].minwid == 0) { /* remove group if all items are empty */ for (n = groupitem[groupdepth] + 1; n < curitem; n++) if (item[n].type == Normal) break; if (n == curitem) { p = t; l = 0; } } if (l > item[groupitem[groupdepth]].maxwid) { /* truncate, remove n bytes of text at the start */ #ifdef FEAT_MBYTE if (has_mbyte) { /* Find the first character that should be included. */ n = 0; while (l >= item[groupitem[groupdepth]].maxwid) { l -= ptr2cells(t + n); n += (*mb_ptr2len)(t + n); } } else #endif n = (long)(p - t) - item[groupitem[groupdepth]].maxwid + 1; *t = '<'; mch_memmove(t + 1, t + n, (size_t)(p - (t + n))); p = p - n + 1; #ifdef FEAT_MBYTE /* Fill up space left over by half a double-wide char. */ while (++l < item[groupitem[groupdepth]].minwid) *p++ = fillchar; #endif /* correct the start of the items for the truncation */ for (l = groupitem[groupdepth] + 1; l < curitem; l++) { item[l].start -= n; if (item[l].start < t) item[l].start = t; } } else if (abs(item[groupitem[groupdepth]].minwid) > l) { /* fill */ n = item[groupitem[groupdepth]].minwid; if (n < 0) { /* fill by appending characters */ n = 0 - n; while (l++ < n && p + 1 < out + outlen) *p++ = fillchar; } else { /* fill by inserting characters */ mch_memmove(t + n - l, t, (size_t)(p - t)); l = n - l; if (p + l >= out + outlen) l = (long)((out + outlen) - p - 1); p += l; for (n = groupitem[groupdepth] + 1; n < curitem; n++) item[n].start += l; for ( ; l > 0; l--) *t++ = fillchar; } } continue; } minwid = 0; maxwid = 9999; zeropad = FALSE; l = 1; if (*s == '0') { s++; zeropad = TRUE; } if (*s == '-') { s++; l = -1; } if (VIM_ISDIGIT(*s)) { minwid = (int)getdigits(&s); if (minwid < 0) /* overflow */ minwid = 0; } if (*s == STL_USER_HL) { item[curitem].type = Highlight; item[curitem].start = p; item[curitem].minwid = minwid > 9 ? 1 : minwid; s++; curitem++; continue; } if (*s == STL_TABPAGENR || *s == STL_TABCLOSENR) { if (*s == STL_TABCLOSENR) { if (minwid == 0) { /* %X ends the close label, go back to the previously * define tab label nr. */ for (n = curitem - 1; n >= 0; --n) if (item[n].type == TabPage && item[n].minwid >= 0) { minwid = item[n].minwid; break; } } else /* close nrs are stored as negative values */ minwid = - minwid; } item[curitem].type = TabPage; item[curitem].start = p; item[curitem].minwid = minwid; s++; curitem++; continue; } if (*s == '.') { s++; if (VIM_ISDIGIT(*s)) { maxwid = (int)getdigits(&s); if (maxwid <= 0) /* overflow */ maxwid = 50; } } minwid = (minwid > 50 ? 50 : minwid) * l; if (*s == '(') { groupitem[groupdepth++] = curitem; item[curitem].type = Group; item[curitem].start = p; item[curitem].minwid = minwid; item[curitem].maxwid = maxwid; s++; curitem++; continue; } if (vim_strchr(STL_ALL, *s) == NULL) { s++; continue; } opt = *s++; /* OK - now for the real work */ base = 'D'; itemisflag = FALSE; fillable = TRUE; num = -1; str = NULL; switch (opt) { case STL_FILEPATH: case STL_FULLPATH: case STL_FILENAME: fillable = FALSE; /* don't change ' ' to fillchar */ if (buf_spname(wp->w_buffer) != NULL) STRCPY(NameBuff, buf_spname(wp->w_buffer)); else { t = (opt == STL_FULLPATH) ? wp->w_buffer->b_ffname : wp->w_buffer->b_fname; home_replace(wp->w_buffer, t, NameBuff, MAXPATHL, TRUE); } trans_characters(NameBuff, MAXPATHL); if (opt != STL_FILENAME) str = NameBuff; else str = gettail(NameBuff); break; case STL_VIM_EXPR: /* '{' */ itemisflag = TRUE; t = p; while (*s != '}' && *s != NUL && p + 1 < out + outlen) *p++ = *s++; if (*s != '}') /* missing '}' or out of space */ break; s++; *p = 0; p = t; #ifdef FEAT_EVAL vim_snprintf((char *)tmp, sizeof(tmp), "%d", curbuf->b_fnum); set_internal_string_var((char_u *)"actual_curbuf", tmp); o_curbuf = curbuf; o_curwin = curwin; curwin = wp; curbuf = wp->w_buffer; str = eval_to_string_safe(p, &t, use_sandbox); curwin = o_curwin; curbuf = o_curbuf; do_unlet((char_u *)"g:actual_curbuf", TRUE); if (str != NULL && *str != 0) { if (*skipdigits(str) == NUL) { num = atoi((char *)str); vim_free(str); str = NULL; itemisflag = FALSE; } } #endif break; case STL_LINE: num = (wp->w_buffer->b_ml.ml_flags & ML_EMPTY) ? 0L : (long)(wp->w_cursor.lnum); break; case STL_NUMLINES: num = wp->w_buffer->b_ml.ml_line_count; break; case STL_COLUMN: num = !(State & INSERT) && empty_line ? 0 : (int)wp->w_cursor.col + 1; break; case STL_VIRTCOL: case STL_VIRTCOL_ALT: /* In list mode virtcol needs to be recomputed */ virtcol = wp->w_virtcol; if (wp->w_p_list && lcs_tab1 == NUL) { wp->w_p_list = FALSE; getvcol(wp, &wp->w_cursor, NULL, &virtcol, NULL); wp->w_p_list = TRUE; } ++virtcol; /* Don't display %V if it's the same as %c. */ if (opt == STL_VIRTCOL_ALT && (virtcol == (colnr_T)(!(State & INSERT) && empty_line ? 0 : (int)wp->w_cursor.col + 1))) break; num = (long)virtcol; break; case STL_PERCENTAGE: num = (int)(((long)wp->w_cursor.lnum * 100L) / (long)wp->w_buffer->b_ml.ml_line_count); break; case STL_ALTPERCENT: str = tmp; get_rel_pos(wp, str, TMPLEN); break; case STL_ARGLISTSTAT: fillable = FALSE; tmp[0] = 0; if (append_arg_number(wp, tmp, (int)sizeof(tmp), FALSE)) str = tmp; break; case STL_KEYMAP: fillable = FALSE; if (get_keymap_str(wp, tmp, TMPLEN)) str = tmp; break; case STL_PAGENUM: #if defined(FEAT_PRINTER) || defined(FEAT_GUI_TABLINE) num = printer_page_num; #else num = 0; #endif break; case STL_BUFNO: num = wp->w_buffer->b_fnum; break; case STL_OFFSET_X: base = 'X'; case STL_OFFSET: #ifdef FEAT_BYTEOFF l = ml_find_line_or_offset(wp->w_buffer, wp->w_cursor.lnum, NULL); num = (wp->w_buffer->b_ml.ml_flags & ML_EMPTY) || l < 0 ? 0L : l + 1 + (!(State & INSERT) && empty_line ? 0 : (int)wp->w_cursor.col); #endif break; case STL_BYTEVAL_X: base = 'X'; case STL_BYTEVAL: if (wp->w_cursor.col > (colnr_T)STRLEN(linecont)) num = 0; else { #ifdef FEAT_MBYTE num = (*mb_ptr2char)(linecont + wp->w_cursor.col); #else num = linecont[wp->w_cursor.col]; #endif } if (num == NL) num = 0; else if (num == CAR && get_fileformat(wp->w_buffer) == EOL_MAC) num = NL; break; case STL_ROFLAG: case STL_ROFLAG_ALT: itemisflag = TRUE; if (wp->w_buffer->b_p_ro) str = (char_u *)((opt == STL_ROFLAG_ALT) ? ",RO" : "[RO]"); break; case STL_HELPFLAG: case STL_HELPFLAG_ALT: itemisflag = TRUE; if (wp->w_buffer->b_help) str = (char_u *)((opt == STL_HELPFLAG_ALT) ? ",HLP" : _("[Help]")); break; #ifdef FEAT_AUTOCMD case STL_FILETYPE: if (*wp->w_buffer->b_p_ft != NUL && STRLEN(wp->w_buffer->b_p_ft) < TMPLEN - 3) { vim_snprintf((char *)tmp, sizeof(tmp), "[%s]", wp->w_buffer->b_p_ft); str = tmp; } break; case STL_FILETYPE_ALT: itemisflag = TRUE; if (*wp->w_buffer->b_p_ft != NUL && STRLEN(wp->w_buffer->b_p_ft) < TMPLEN - 2) { vim_snprintf((char *)tmp, sizeof(tmp), ",%s", wp->w_buffer->b_p_ft); for (t = tmp; *t != 0; t++) *t = TOUPPER_LOC(*t); str = tmp; } break; #endif #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX) case STL_PREVIEWFLAG: case STL_PREVIEWFLAG_ALT: itemisflag = TRUE; if (wp->w_p_pvw) str = (char_u *)((opt == STL_PREVIEWFLAG_ALT) ? ",PRV" : _("[Preview]")); break; case STL_QUICKFIX: if (bt_quickfix(wp->w_buffer)) str = (char_u *)(wp->w_llist_ref ? _(msg_loclist) : _(msg_qflist)); break; #endif case STL_MODIFIED: case STL_MODIFIED_ALT: itemisflag = TRUE; switch ((opt == STL_MODIFIED_ALT) + bufIsChanged(wp->w_buffer) * 2 + (!wp->w_buffer->b_p_ma) * 4) { case 2: str = (char_u *)"[+]"; break; case 3: str = (char_u *)",+"; break; case 4: str = (char_u *)"[-]"; break; case 5: str = (char_u *)",-"; break; case 6: str = (char_u *)"[+-]"; break; case 7: str = (char_u *)",+-"; break; } break; case STL_HIGHLIGHT: t = s; while (*s != '#' && *s != NUL) ++s; if (*s == '#') { item[curitem].type = Highlight; item[curitem].start = p; item[curitem].minwid = -syn_namen2id(t, (int)(s - t)); curitem++; } ++s; continue; } item[curitem].start = p; item[curitem].type = Normal; if (str != NULL && *str) { t = str; if (itemisflag) { if ((t[0] && t[1]) && ((!prevchar_isitem && *t == ',') || (prevchar_isflag && *t == ' '))) t++; prevchar_isflag = TRUE; } l = vim_strsize(t); if (l > 0) prevchar_isitem = TRUE; if (l > maxwid) { while (l >= maxwid) #ifdef FEAT_MBYTE if (has_mbyte) { l -= ptr2cells(t); t += (*mb_ptr2len)(t); } else #endif l -= byte2cells(*t++); if (p + 1 >= out + outlen) break; *p++ = '<'; } if (minwid > 0) { for (; l < minwid && p + 1 < out + outlen; l++) { /* Don't put a "-" in front of a digit. */ if (l + 1 == minwid && fillchar == '-' && VIM_ISDIGIT(*t)) *p++ = ' '; else *p++ = fillchar; } minwid = 0; } else minwid *= -1; while (*t && p + 1 < out + outlen) { *p++ = *t++; /* Change a space by fillchar, unless fillchar is '-' and a * digit follows. */ if (fillable && p[-1] == ' ' && (!VIM_ISDIGIT(*t) || fillchar != '-')) p[-1] = fillchar; } for (; l < minwid && p + 1 < out + outlen; l++) *p++ = fillchar; } else if (num >= 0) { int nbase = (base == 'D' ? 10 : (base == 'O' ? 8 : 16)); char_u nstr[20]; if (p + 20 >= out + outlen) break; /* not sufficient space */ prevchar_isitem = TRUE; t = nstr; if (opt == STL_VIRTCOL_ALT) { *t++ = '-'; minwid--; } *t++ = '%'; if (zeropad) *t++ = '0'; *t++ = '*'; *t++ = nbase == 16 ? base : (char_u)(nbase == 8 ? 'o' : 'd'); *t = 0; for (n = num, l = 1; n >= nbase; n /= nbase) l++; if (opt == STL_VIRTCOL_ALT) l++; if (l > maxwid) { l += 2; n = l - maxwid; while (l-- > maxwid) num /= nbase; *t++ = '>'; *t++ = '%'; *t = t[-3]; *++t = 0; vim_snprintf((char *)p, outlen - (p - out), (char *)nstr, 0, num, n); } else vim_snprintf((char *)p, outlen - (p - out), (char *)nstr, minwid, num); p += STRLEN(p); } else item[curitem].type = Empty; if (opt == STL_VIM_EXPR) vim_free(str); if (num >= 0 || (!itemisflag && str && *str)) prevchar_isflag = FALSE; /* Item not NULL, but not a flag */ curitem++; } *p = NUL; itemcnt = curitem; #ifdef FEAT_EVAL if (usefmt != fmt) vim_free(usefmt); #endif width = vim_strsize(out); if (maxwidth > 0 && width > maxwidth) { /* Result is too long, must truncate somewhere. */ l = 0; if (itemcnt == 0) s = out; else { for ( ; l < itemcnt; l++) if (item[l].type == Trunc) { /* Truncate at %< item. */ s = item[l].start; break; } if (l == itemcnt) { /* No %< item, truncate first item. */ s = item[0].start; l = 0; } } if (width - vim_strsize(s) >= maxwidth) { /* Truncation mark is beyond max length */ #ifdef FEAT_MBYTE if (has_mbyte) { s = out; width = 0; for (;;) { width += ptr2cells(s); if (width >= maxwidth) break; s += (*mb_ptr2len)(s); } /* Fill up for half a double-wide character. */ while (++width < maxwidth) *s++ = fillchar; } else #endif s = out + maxwidth - 1; for (l = 0; l < itemcnt; l++) if (item[l].start > s) break; itemcnt = l; *s++ = '>'; *s = 0; } else { #ifdef FEAT_MBYTE if (has_mbyte) { n = 0; while (width >= maxwidth) { width -= ptr2cells(s + n); n += (*mb_ptr2len)(s + n); } } else #endif n = width - maxwidth + 1; p = s + n; STRMOVE(s + 1, p); *s = '<'; /* Fill up for half a double-wide character. */ while (++width < maxwidth) { s = s + STRLEN(s); *s++ = fillchar; *s = NUL; } --n; /* count the '<' */ for (; l < itemcnt; l++) { if (item[l].start - n >= s) item[l].start -= n; else item[l].start = s; } } width = maxwidth; } else if (width < maxwidth && STRLEN(out) + maxwidth - width + 1 < outlen) { /* Apply STL_MIDDLE if any */ for (l = 0; l < itemcnt; l++) if (item[l].type == Middle) break; if (l < itemcnt) { p = item[l].start + maxwidth - width; STRMOVE(p, item[l].start); for (s = item[l].start; s < p; s++) *s = fillchar; for (l++; l < itemcnt; l++) item[l].start += maxwidth - width; width = maxwidth; } } /* Store the info about highlighting. */ if (hltab != NULL) { sp = hltab; for (l = 0; l < itemcnt; l++) { if (item[l].type == Highlight) { sp->start = item[l].start; sp->userhl = item[l].minwid; sp++; } } sp->start = NULL; sp->userhl = 0; } /* Store the info about tab pages labels. */ if (tabtab != NULL) { sp = tabtab; for (l = 0; l < itemcnt; l++) { if (item[l].type == TabPage) { sp->start = item[l].start; sp->userhl = item[l].minwid; sp++; } } sp->start = NULL; sp->userhl = 0; } return width; } #endif /* FEAT_STL_OPT */ #if defined(FEAT_STL_OPT) || defined(FEAT_CMDL_INFO) \ || defined(FEAT_GUI_TABLINE) || defined(PROTO) /* * Get relative cursor position in window into "buf[buflen]", in the form 99%, * using "Top", "Bot" or "All" when appropriate. */ void get_rel_pos(wp, buf, buflen) win_T *wp; char_u *buf; int buflen; { long above; /* number of lines above window */ long below; /* number of lines below window */ above = wp->w_topline - 1; #ifdef FEAT_DIFF above += diff_check_fill(wp, wp->w_topline) - wp->w_topfill; #endif below = wp->w_buffer->b_ml.ml_line_count - wp->w_botline + 1; if (below <= 0) vim_strncpy(buf, (char_u *)(above == 0 ? _("All") : _("Bot")), (size_t)(buflen - 1)); else if (above <= 0) vim_strncpy(buf, (char_u *)_("Top"), (size_t)(buflen - 1)); else vim_snprintf((char *)buf, (size_t)buflen, "%2d%%", above > 1000000L ? (int)(above / ((above + below) / 100L)) : (int)(above * 100L / (above + below))); } #endif /* * Append (file 2 of 8) to "buf[buflen]", if editing more than one file. * Return TRUE if it was appended. */ static int append_arg_number(wp, buf, buflen, add_file) win_T *wp; char_u *buf; int buflen; int add_file; /* Add "file" before the arg number */ { char_u *p; if (ARGCOUNT <= 1) /* nothing to do */ return FALSE; p = buf + STRLEN(buf); /* go to the end of the buffer */ if (p - buf + 35 >= buflen) /* getting too long */ return FALSE; *p++ = ' '; *p++ = '('; if (add_file) { STRCPY(p, "file "); p += 5; } vim_snprintf((char *)p, (size_t)(buflen - (p - buf)), wp->w_arg_idx_invalid ? "(%d) of %d)" : "%d of %d)", wp->w_arg_idx + 1, ARGCOUNT); return TRUE; } /* * If fname is not a full path, make it a full path. * Returns pointer to allocated memory (NULL for failure). */ char_u * fix_fname(fname) char_u *fname; { /* * Force expanding the path always for Unix, because symbolic links may * mess up the full path name, even though it starts with a '/'. * Also expand when there is ".." in the file name, try to remove it, * because "c:/src/../README" is equal to "c:/README". * Similarly "c:/src//file" is equal to "c:/src/file". * For MS-Windows also expand names like "longna~1" to "longname". */ #ifdef UNIX return FullName_save(fname, TRUE); #else if (!vim_isAbsName(fname) || strstr((char *)fname, "..") != NULL || strstr((char *)fname, "//") != NULL # ifdef BACKSLASH_IN_FILENAME || strstr((char *)fname, "\\\\") != NULL # endif # if defined(MSWIN) || defined(DJGPP) || vim_strchr(fname, '~') != NULL # endif ) return FullName_save(fname, FALSE); fname = vim_strsave(fname); # ifdef USE_FNAME_CASE # ifdef USE_LONG_FNAME if (USE_LONG_FNAME) # endif { if (fname != NULL) fname_case(fname, 0); /* set correct case for file name */ } # endif return fname; #endif } /* * Make "ffname" a full file name, set "sfname" to "ffname" if not NULL. * "ffname" becomes a pointer to allocated memory (or NULL). */ void fname_expand(buf, ffname, sfname) buf_T *buf UNUSED; char_u **ffname; char_u **sfname; { if (*ffname == NULL) /* if no file name given, nothing to do */ return; if (*sfname == NULL) /* if no short file name given, use ffname */ *sfname = *ffname; *ffname = fix_fname(*ffname); /* expand to full path */ #ifdef FEAT_SHORTCUT if (!buf->b_p_bin) { char_u *rfname; /* If the file name is a shortcut file, use the file it links to. */ rfname = mch_resolve_shortcut(*ffname); if (rfname != NULL) { vim_free(*ffname); *ffname = rfname; *sfname = rfname; } } #endif } /* * Get the file name for an argument list entry. */ char_u * alist_name(aep) aentry_T *aep; { buf_T *bp; /* Use the name from the associated buffer if it exists. */ bp = buflist_findnr(aep->ae_fnum); if (bp == NULL || bp->b_fname == NULL) return aep->ae_fname; return bp->b_fname; } #if defined(FEAT_WINDOWS) || defined(PROTO) /* * do_arg_all(): Open up to 'count' windows, one for each argument. */ void do_arg_all(count, forceit, keep_tabs) int count; int forceit; /* hide buffers in current windows */ int keep_tabs; /* keep current tabs, for ":tab drop file" */ { int i; win_T *wp, *wpnext; char_u *opened; /* Array of weight for which args are open: * 0: not opened * 1: opened in other tab * 2: opened in curtab * 3: opened in curtab and curwin */ int opened_len; /* length of opened[] */ int use_firstwin = FALSE; /* use first window for arglist */ int split_ret = OK; int p_ea_save; alist_T *alist; /* argument list to be used */ buf_T *buf; tabpage_T *tpnext; int had_tab = cmdmod.tab; win_T *old_curwin, *last_curwin; tabpage_T *old_curtab, *last_curtab; win_T *new_curwin = NULL; tabpage_T *new_curtab = NULL; if (ARGCOUNT <= 0) { /* Don't give an error message. We don't want it when the ":all" * command is in the .vimrc. */ return; } setpcmark(); opened_len = ARGCOUNT; opened = alloc_clear((unsigned)opened_len); if (opened == NULL) return; /* Autocommands may do anything to the argument list. Make sure it's not * freed while we are working here by "locking" it. We still have to * watch out for its size to be changed. */ alist = curwin->w_alist; ++alist->al_refcount; old_curwin = curwin; old_curtab = curtab; #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif /* * Try closing all windows that are not in the argument list. * Also close windows that are not full width; * When 'hidden' or "forceit" set the buffer becomes hidden. * Windows that have a changed buffer and can't be hidden won't be closed. * When the ":tab" modifier was used do this for all tab pages. */ if (had_tab > 0) goto_tabpage_tp(first_tabpage, TRUE); for (;;) { tpnext = curtab->tp_next; for (wp = firstwin; wp != NULL; wp = wpnext) { wpnext = wp->w_next; buf = wp->w_buffer; if (buf->b_ffname == NULL || (!keep_tabs && buf->b_nwindows > 1) #ifdef FEAT_VERTSPLIT || wp->w_width != Columns #endif ) i = opened_len; else { /* check if the buffer in this window is in the arglist */ for (i = 0; i < opened_len; ++i) { if (i < alist->al_ga.ga_len && (AARGLIST(alist)[i].ae_fnum == buf->b_fnum || fullpathcmp(alist_name(&AARGLIST(alist)[i]), buf->b_ffname, TRUE) & FPC_SAME)) { int weight = 1; if (old_curtab == curtab) { ++weight; if (old_curwin == wp) ++weight; } if (weight > (int)opened[i]) { opened[i] = (char_u)weight; if (i == 0) { if (new_curwin != NULL) new_curwin->w_arg_idx = opened_len; new_curwin = wp; new_curtab = curtab; } } else if (keep_tabs) i = opened_len; if (wp->w_alist != alist) { /* Use the current argument list for all windows * containing a file from it. */ alist_unlink(wp->w_alist); wp->w_alist = alist; ++wp->w_alist->al_refcount; } break; } } } wp->w_arg_idx = i; if (i == opened_len && !keep_tabs)/* close this window */ { if (P_HID(buf) || forceit || buf->b_nwindows > 1 || !bufIsChanged(buf)) { /* If the buffer was changed, and we would like to hide it, * try autowriting. */ if (!P_HID(buf) && buf->b_nwindows <= 1 && bufIsChanged(buf)) { (void)autowrite(buf, FALSE); #ifdef FEAT_AUTOCMD /* check if autocommands removed the window */ if (!win_valid(wp) || !buf_valid(buf)) { wpnext = firstwin; /* start all over... */ continue; } #endif } #ifdef FEAT_WINDOWS /* don't close last window */ if (firstwin == lastwin && (first_tabpage->tp_next == NULL || !had_tab)) #endif use_firstwin = TRUE; #ifdef FEAT_WINDOWS else { win_close(wp, !P_HID(buf) && !bufIsChanged(buf)); # ifdef FEAT_AUTOCMD /* check if autocommands removed the next window */ if (!win_valid(wpnext)) wpnext = firstwin; /* start all over... */ # endif } #endif } } } /* Without the ":tab" modifier only do the current tab page. */ if (had_tab == 0 || tpnext == NULL) break; # ifdef FEAT_AUTOCMD /* check if autocommands removed the next tab page */ if (!valid_tabpage(tpnext)) tpnext = first_tabpage; /* start all over...*/ # endif goto_tabpage_tp(tpnext, TRUE); } /* * Open a window for files in the argument list that don't have one. * ARGCOUNT may change while doing this, because of autocommands. */ if (count > opened_len || count <= 0) count = opened_len; #ifdef FEAT_AUTOCMD /* Don't execute Win/Buf Enter/Leave autocommands here. */ ++autocmd_no_enter; ++autocmd_no_leave; #endif last_curwin = curwin; last_curtab = curtab; win_enter(lastwin, FALSE); #ifdef FEAT_WINDOWS /* ":drop all" should re-use an empty window to avoid "--remote-tab" * leaving an empty tab page when executed locally. */ if (keep_tabs && bufempty() && curbuf->b_nwindows == 1 && curbuf->b_ffname == NULL && !curbuf->b_changed) use_firstwin = TRUE; #endif for (i = 0; i < count && i < opened_len && !got_int; ++i) { if (alist == &global_alist && i == global_alist.al_ga.ga_len - 1) arg_had_last = TRUE; if (opened[i] > 0) { /* Move the already present window to below the current window */ if (curwin->w_arg_idx != i) { for (wpnext = firstwin; wpnext != NULL; wpnext = wpnext->w_next) { if (wpnext->w_arg_idx == i) { if (keep_tabs) { new_curwin = wpnext; new_curtab = curtab; } else win_move_after(wpnext, curwin); break; } } } } else if (split_ret == OK) { if (!use_firstwin) /* split current window */ { p_ea_save = p_ea; p_ea = TRUE; /* use space from all windows */ split_ret = win_split(0, WSP_ROOM | WSP_BELOW); p_ea = p_ea_save; if (split_ret == FAIL) continue; } #ifdef FEAT_AUTOCMD else /* first window: do autocmd for leaving this buffer */ --autocmd_no_leave; #endif /* * edit file "i" */ curwin->w_arg_idx = i; if (i == 0) { new_curwin = curwin; new_curtab = curtab; } (void)do_ecmd(0, alist_name(&AARGLIST(alist)[i]), NULL, NULL, ECMD_ONE, ((P_HID(curwin->w_buffer) || bufIsChanged(curwin->w_buffer)) ? ECMD_HIDE : 0) + ECMD_OLDBUF, curwin); #ifdef FEAT_AUTOCMD if (use_firstwin) ++autocmd_no_leave; #endif use_firstwin = FALSE; } ui_breakcheck(); /* When ":tab" was used open a new tab for a new window repeatedly. */ if (had_tab > 0 && tabpage_index(NULL) <= p_tpm) cmdmod.tab = 9999; } /* Remove the "lock" on the argument list. */ alist_unlink(alist); #ifdef FEAT_AUTOCMD --autocmd_no_enter; #endif /* restore last referenced tabpage's curwin */ if (last_curtab != new_curtab) { if (valid_tabpage(last_curtab)) goto_tabpage_tp(last_curtab, TRUE); if (win_valid(last_curwin)) win_enter(last_curwin, FALSE); } /* to window with first arg */ if (valid_tabpage(new_curtab)) goto_tabpage_tp(new_curtab, TRUE); if (win_valid(new_curwin)) win_enter(new_curwin, FALSE); #ifdef FEAT_AUTOCMD --autocmd_no_leave; #endif vim_free(opened); } # if defined(FEAT_LISTCMDS) || defined(PROTO) /* * Open a window for a number of buffers. */ void ex_buffer_all(eap) exarg_T *eap; { buf_T *buf; win_T *wp, *wpnext; int split_ret = OK; int p_ea_save; int open_wins = 0; int r; int count; /* Maximum number of windows to open. */ int all; /* When TRUE also load inactive buffers. */ #ifdef FEAT_WINDOWS int had_tab = cmdmod.tab; tabpage_T *tpnext; #endif if (eap->addr_count == 0) /* make as many windows as possible */ count = 9999; else count = eap->line2; /* make as many windows as specified */ if (eap->cmdidx == CMD_unhide || eap->cmdidx == CMD_sunhide) all = FALSE; else all = TRUE; setpcmark(); #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif /* * Close superfluous windows (two windows for the same buffer). * Also close windows that are not full-width. */ #ifdef FEAT_WINDOWS if (had_tab > 0) goto_tabpage_tp(first_tabpage, TRUE); for (;;) { #endif tpnext = curtab->tp_next; for (wp = firstwin; wp != NULL; wp = wpnext) { wpnext = wp->w_next; if ((wp->w_buffer->b_nwindows > 1 #ifdef FEAT_VERTSPLIT || ((cmdmod.split & WSP_VERT) ? wp->w_height + wp->w_status_height < Rows - p_ch - tabline_height() : wp->w_width != Columns) #endif #ifdef FEAT_WINDOWS || (had_tab > 0 && wp != firstwin) #endif ) && firstwin != lastwin #ifdef FEAT_AUTOCMD && !(wp->w_closing || wp->w_buffer->b_closing) #endif ) { win_close(wp, FALSE); #ifdef FEAT_AUTOCMD wpnext = firstwin; /* just in case an autocommand does something strange with windows */ tpnext = first_tabpage; /* start all over...*/ open_wins = 0; #endif } else ++open_wins; } #ifdef FEAT_WINDOWS /* Without the ":tab" modifier only do the current tab page. */ if (had_tab == 0 || tpnext == NULL) break; goto_tabpage_tp(tpnext, TRUE); } #endif /* * Go through the buffer list. When a buffer doesn't have a window yet, * open one. Otherwise move the window to the right position. * Watch out for autocommands that delete buffers or windows! */ #ifdef FEAT_AUTOCMD /* Don't execute Win/Buf Enter/Leave autocommands here. */ ++autocmd_no_enter; #endif win_enter(lastwin, FALSE); #ifdef FEAT_AUTOCMD ++autocmd_no_leave; #endif for (buf = firstbuf; buf != NULL && open_wins < count; buf = buf->b_next) { /* Check if this buffer needs a window */ if ((!all && buf->b_ml.ml_mfp == NULL) || !buf->b_p_bl) continue; #ifdef FEAT_WINDOWS if (had_tab != 0) { /* With the ":tab" modifier don't move the window. */ if (buf->b_nwindows > 0) wp = lastwin; /* buffer has a window, skip it */ else wp = NULL; } else #endif { /* Check if this buffer already has a window */ for (wp = firstwin; wp != NULL; wp = wp->w_next) if (wp->w_buffer == buf) break; /* If the buffer already has a window, move it */ if (wp != NULL) win_move_after(wp, curwin); } if (wp == NULL && split_ret == OK) { /* Split the window and put the buffer in it */ p_ea_save = p_ea; p_ea = TRUE; /* use space from all windows */ split_ret = win_split(0, WSP_ROOM | WSP_BELOW); ++open_wins; p_ea = p_ea_save; if (split_ret == FAIL) continue; /* Open the buffer in this window. */ #if defined(HAS_SWAP_EXISTS_ACTION) swap_exists_action = SEA_DIALOG; #endif set_curbuf(buf, DOBUF_GOTO); #ifdef FEAT_AUTOCMD if (!buf_valid(buf)) /* autocommands deleted the buffer!!! */ { #if defined(HAS_SWAP_EXISTS_ACTION) swap_exists_action = SEA_NONE; # endif break; } #endif #if defined(HAS_SWAP_EXISTS_ACTION) if (swap_exists_action == SEA_QUIT) { # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL) cleanup_T cs; /* Reset the error/interrupt/exception state here so that * aborting() returns FALSE when closing a window. */ enter_cleanup(&cs); # endif /* User selected Quit at ATTENTION prompt; close this window. */ win_close(curwin, TRUE); --open_wins; swap_exists_action = SEA_NONE; swap_exists_did_quit = TRUE; # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL) /* Restore the error/interrupt/exception state if not * discarded by a new aborting error, interrupt, or uncaught * exception. */ leave_cleanup(&cs); # endif } else handle_swap_exists(NULL); #endif } ui_breakcheck(); if (got_int) { (void)vgetc(); /* only break the file loading, not the rest */ break; } #ifdef FEAT_EVAL /* Autocommands deleted the buffer or aborted script processing!!! */ if (aborting()) break; #endif #ifdef FEAT_WINDOWS /* When ":tab" was used open a new tab for a new window repeatedly. */ if (had_tab > 0 && tabpage_index(NULL) <= p_tpm) cmdmod.tab = 9999; #endif } #ifdef FEAT_AUTOCMD --autocmd_no_enter; #endif win_enter(firstwin, FALSE); /* back to first window */ #ifdef FEAT_AUTOCMD --autocmd_no_leave; #endif /* * Close superfluous windows. */ for (wp = lastwin; open_wins > count; ) { r = (P_HID(wp->w_buffer) || !bufIsChanged(wp->w_buffer) || autowrite(wp->w_buffer, FALSE) == OK); #ifdef FEAT_AUTOCMD if (!win_valid(wp)) { /* BufWrite Autocommands made the window invalid, start over */ wp = lastwin; } else #endif if (r) { win_close(wp, !P_HID(wp->w_buffer)); --open_wins; wp = lastwin; } else { wp = wp->w_prev; if (wp == NULL) break; } } } # endif /* FEAT_LISTCMDS */ #endif /* FEAT_WINDOWS */ static int chk_modeline __ARGS((linenr_T, int)); /* * do_modelines() - process mode lines for the current file * * "flags" can be: * OPT_WINONLY only set options local to window * OPT_NOWIN don't set options local to window * * Returns immediately if the "ml" option isn't set. */ void do_modelines(flags) int flags; { linenr_T lnum; int nmlines; static int entered = 0; if (!curbuf->b_p_ml || (nmlines = (int)p_mls) == 0) return; /* Disallow recursive entry here. Can happen when executing a modeline * triggers an autocommand, which reloads modelines with a ":do". */ if (entered) return; ++entered; for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count && lnum <= nmlines; ++lnum) if (chk_modeline(lnum, flags) == FAIL) nmlines = 0; for (lnum = curbuf->b_ml.ml_line_count; lnum > 0 && lnum > nmlines && lnum > curbuf->b_ml.ml_line_count - nmlines; --lnum) if (chk_modeline(lnum, flags) == FAIL) nmlines = 0; --entered; } #include "version.h" /* for version number */ /* * chk_modeline() - check a single line for a mode string * Return FAIL if an error encountered. */ static int chk_modeline(lnum, flags) linenr_T lnum; int flags; /* Same as for do_modelines(). */ { char_u *s; char_u *e; char_u *linecopy; /* local copy of any modeline found */ int prev; int vers; int end; int retval = OK; char_u *save_sourcing_name; linenr_T save_sourcing_lnum; #ifdef FEAT_EVAL scid_T save_SID; #endif prev = -1; for (s = ml_get(lnum); *s != NUL; ++s) { if (prev == -1 || vim_isspace(prev)) { if ((prev != -1 && STRNCMP(s, "ex:", (size_t)3) == 0) || STRNCMP(s, "vi:", (size_t)3) == 0) break; if (STRNCMP(s, "vim", 3) == 0) { if (s[3] == '<' || s[3] == '=' || s[3] == '>') e = s + 4; else e = s + 3; vers = getdigits(&e); if (*e == ':' && (s[3] == ':' || (VIM_VERSION_100 >= vers && isdigit(s[3])) || (VIM_VERSION_100 < vers && s[3] == '<') || (VIM_VERSION_100 > vers && s[3] == '>') || (VIM_VERSION_100 == vers && s[3] == '='))) break; } } prev = *s; } if (*s) { do /* skip over "ex:", "vi:" or "vim:" */ ++s; while (s[-1] != ':'); s = linecopy = vim_strsave(s); /* copy the line, it will change */ if (linecopy == NULL) return FAIL; save_sourcing_lnum = sourcing_lnum; save_sourcing_name = sourcing_name; sourcing_lnum = lnum; /* prepare for emsg() */ sourcing_name = (char_u *)"modelines"; end = FALSE; while (end == FALSE) { s = skipwhite(s); if (*s == NUL) break; /* * Find end of set command: ':' or end of line. * Skip over "\:", replacing it with ":". */ for (e = s; *e != ':' && *e != NUL; ++e) if (e[0] == '\\' && e[1] == ':') STRMOVE(e, e + 1); if (*e == NUL) end = TRUE; /* * If there is a "set" command, require a terminating ':' and * ignore the stuff after the ':'. * "vi:set opt opt opt: foo" -- foo not interpreted * "vi:opt opt opt: foo" -- foo interpreted * Accept "se" for compatibility with Elvis. */ if (STRNCMP(s, "set ", (size_t)4) == 0 || STRNCMP(s, "se ", (size_t)3) == 0) { if (*e != ':') /* no terminating ':'? */ break; end = TRUE; s = vim_strchr(s, ' ') + 1; } *e = NUL; /* truncate the set command */ if (*s != NUL) /* skip over an empty "::" */ { #ifdef FEAT_EVAL save_SID = current_SID; current_SID = SID_MODELINE; #endif retval = do_set(s, OPT_MODELINE | OPT_LOCAL | flags); #ifdef FEAT_EVAL current_SID = save_SID; #endif if (retval == FAIL) /* stop if error found */ break; } s = e + 1; /* advance to next part */ } sourcing_lnum = save_sourcing_lnum; sourcing_name = save_sourcing_name; vim_free(linecopy); } return retval; } #if defined(FEAT_VIMINFO) || defined(PROTO) int read_viminfo_bufferlist(virp, writing) vir_T *virp; int writing; { char_u *tab; linenr_T lnum; colnr_T col; buf_T *buf; char_u *sfname; char_u *xline; /* Handle long line and escaped characters. */ xline = viminfo_readstring(virp, 1, FALSE); /* don't read in if there are files on the command-line or if writing: */ if (xline != NULL && !writing && ARGCOUNT == 0 && find_viminfo_parameter('%') != NULL) { /* Format is: <fname> Tab <lnum> Tab <col>. * Watch out for a Tab in the file name, work from the end. */ lnum = 0; col = 0; tab = vim_strrchr(xline, '\t'); if (tab != NULL) { *tab++ = '\0'; col = (colnr_T)atoi((char *)tab); tab = vim_strrchr(xline, '\t'); if (tab != NULL) { *tab++ = '\0'; lnum = atol((char *)tab); } } /* Expand "~/" in the file name at "line + 1" to a full path. * Then try shortening it by comparing with the current directory */ expand_env(xline, NameBuff, MAXPATHL); sfname = shorten_fname1(NameBuff); buf = buflist_new(NameBuff, sfname, (linenr_T)0, BLN_LISTED); if (buf != NULL) /* just in case... */ { buf->b_last_cursor.lnum = lnum; buf->b_last_cursor.col = col; buflist_setfpos(buf, curwin, lnum, col, FALSE); } } vim_free(xline); return viminfo_readline(virp); } void write_viminfo_bufferlist(fp) FILE *fp; { buf_T *buf; #ifdef FEAT_WINDOWS win_T *win; tabpage_T *tp; #endif char_u *line; int max_buffers; if (find_viminfo_parameter('%') == NULL) return; /* Without a number -1 is returned: do all buffers. */ max_buffers = get_viminfo_parameter('%'); /* Allocate room for the file name, lnum and col. */ #define LINE_BUF_LEN (MAXPATHL + 40) line = alloc(LINE_BUF_LEN); if (line == NULL) return; #ifdef FEAT_WINDOWS FOR_ALL_TAB_WINDOWS(tp, win) set_last_cursor(win); #else set_last_cursor(curwin); #endif fputs(_("\n# Buffer list:\n"), fp); for (buf = firstbuf; buf != NULL ; buf = buf->b_next) { if (buf->b_fname == NULL || !buf->b_p_bl #ifdef FEAT_QUICKFIX || bt_quickfix(buf) #endif || removable(buf->b_ffname)) continue; if (max_buffers-- == 0) break; putc('%', fp); home_replace(NULL, buf->b_ffname, line, MAXPATHL, TRUE); vim_snprintf_add((char *)line, LINE_BUF_LEN, "\t%ld\t%d", (long)buf->b_last_cursor.lnum, buf->b_last_cursor.col); viminfo_writestring(fp, line); } vim_free(line); } #endif /* * Return special buffer name. * Returns NULL when the buffer has a normal file name. */ char * buf_spname(buf) buf_T *buf; { #if defined(FEAT_QUICKFIX) && defined(FEAT_WINDOWS) if (bt_quickfix(buf)) { win_T *win = NULL; tabpage_T *tp; /* * For location list window, w_llist_ref points to the location list. * For quickfix window, w_llist_ref is NULL. */ FOR_ALL_TAB_WINDOWS(tp, win) if (win->w_buffer == buf) goto win_found; win_found: if (win != NULL && win->w_llist_ref != NULL) return _(msg_loclist); else return _(msg_qflist); } #endif #ifdef FEAT_QUICKFIX /* There is no _file_ when 'buftype' is "nofile", b_sfname * contains the name as specified by the user */ if (bt_nofile(buf)) { if (buf->b_sfname != NULL) return (char *)buf->b_sfname; return _("[Scratch]"); } #endif if (buf->b_fname == NULL) return _("[No Name]"); return NULL; } #if defined(FEAT_SIGNS) || defined(PROTO) /* * Insert the sign into the signlist. */ static void insert_sign(buf, prev, next, id, lnum, typenr) buf_T *buf; /* buffer to store sign in */ signlist_T *prev; /* previous sign entry */ signlist_T *next; /* next sign entry */ int id; /* sign ID */ linenr_T lnum; /* line number which gets the mark */ int typenr; /* typenr of sign we are adding */ { signlist_T *newsign; newsign = (signlist_T *)lalloc((long_u)sizeof(signlist_T), FALSE); if (newsign != NULL) { newsign->id = id; newsign->lnum = lnum; newsign->typenr = typenr; newsign->next = next; #ifdef FEAT_NETBEANS_INTG newsign->prev = prev; if (next != NULL) next->prev = newsign; #endif if (prev == NULL) { /* When adding first sign need to redraw the windows to create the * column for signs. */ if (buf->b_signlist == NULL) { redraw_buf_later(buf, NOT_VALID); changed_cline_bef_curs(); } /* first sign in signlist */ buf->b_signlist = newsign; } else prev->next = newsign; } } /* * Add the sign into the signlist. Find the right spot to do it though. */ void buf_addsign(buf, id, lnum, typenr) buf_T *buf; /* buffer to store sign in */ int id; /* sign ID */ linenr_T lnum; /* line number which gets the mark */ int typenr; /* typenr of sign we are adding */ { signlist_T *sign; /* a sign in the signlist */ signlist_T *prev; /* the previous sign */ prev = NULL; for (sign = buf->b_signlist; sign != NULL; sign = sign->next) { if (lnum == sign->lnum && id == sign->id) { sign->typenr = typenr; return; } else if ( #ifndef FEAT_NETBEANS_INTG /* keep signs sorted by lnum */ id < 0 && #endif lnum < sign->lnum) { #ifdef FEAT_NETBEANS_INTG /* insert new sign at head of list for this lnum */ /* XXX - GRP: Is this because of sign slide problem? Or is it * really needed? Or is it because we allow multiple signs per * line? If so, should I add that feature to FEAT_SIGNS? */ while (prev != NULL && prev->lnum == lnum) prev = prev->prev; if (prev == NULL) sign = buf->b_signlist; else sign = prev->next; #endif insert_sign(buf, prev, sign, id, lnum, typenr); return; } prev = sign; } #ifdef FEAT_NETBEANS_INTG /* insert new sign at head of list for this lnum */ /* XXX - GRP: See previous comment */ while (prev != NULL && prev->lnum == lnum) prev = prev->prev; if (prev == NULL) sign = buf->b_signlist; else sign = prev->next; #endif insert_sign(buf, prev, sign, id, lnum, typenr); return; } linenr_T buf_change_sign_type(buf, markId, typenr) buf_T *buf; /* buffer to store sign in */ int markId; /* sign ID */ int typenr; /* typenr of sign we are adding */ { signlist_T *sign; /* a sign in the signlist */ for (sign = buf->b_signlist; sign != NULL; sign = sign->next) { if (sign->id == markId) { sign->typenr = typenr; return sign->lnum; } } return (linenr_T)0; } int buf_getsigntype(buf, lnum, type) buf_T *buf; linenr_T lnum; int type; /* SIGN_ICON, SIGN_TEXT, SIGN_ANY, SIGN_LINEHL */ { signlist_T *sign; /* a sign in a b_signlist */ for (sign = buf->b_signlist; sign != NULL; sign = sign->next) if (sign->lnum == lnum && (type == SIGN_ANY # ifdef FEAT_SIGN_ICONS || (type == SIGN_ICON && sign_get_image(sign->typenr) != NULL) # endif || (type == SIGN_TEXT && sign_get_text(sign->typenr) != NULL) || (type == SIGN_LINEHL && sign_get_attr(sign->typenr, TRUE) != 0))) return sign->typenr; return 0; } linenr_T buf_delsign(buf, id) buf_T *buf; /* buffer sign is stored in */ int id; /* sign id */ { signlist_T **lastp; /* pointer to pointer to current sign */ signlist_T *sign; /* a sign in a b_signlist */ signlist_T *next; /* the next sign in a b_signlist */ linenr_T lnum; /* line number whose sign was deleted */ lastp = &buf->b_signlist; lnum = 0; for (sign = buf->b_signlist; sign != NULL; sign = next) { next = sign->next; if (sign->id == id) { *lastp = next; #ifdef FEAT_NETBEANS_INTG if (next != NULL) next->prev = sign->prev; #endif lnum = sign->lnum; vim_free(sign); break; } else lastp = &sign->next; } /* When deleted the last sign need to redraw the windows to remove the * sign column. */ if (buf->b_signlist == NULL) { redraw_buf_later(buf, NOT_VALID); changed_cline_bef_curs(); } return lnum; } /* * Find the line number of the sign with the requested id. If the sign does * not exist, return 0 as the line number. This will still let the correct file * get loaded. */ int buf_findsign(buf, id) buf_T *buf; /* buffer to store sign in */ int id; /* sign ID */ { signlist_T *sign; /* a sign in the signlist */ for (sign = buf->b_signlist; sign != NULL; sign = sign->next) if (sign->id == id) return sign->lnum; return 0; } int buf_findsign_id(buf, lnum) buf_T *buf; /* buffer whose sign we are searching for */ linenr_T lnum; /* line number of sign */ { signlist_T *sign; /* a sign in the signlist */ for (sign = buf->b_signlist; sign != NULL; sign = sign->next) if (sign->lnum == lnum) return sign->id; return 0; } # if defined(FEAT_NETBEANS_INTG) || defined(PROTO) /* see if a given type of sign exists on a specific line */ int buf_findsigntype_id(buf, lnum, typenr) buf_T *buf; /* buffer whose sign we are searching for */ linenr_T lnum; /* line number of sign */ int typenr; /* sign type number */ { signlist_T *sign; /* a sign in the signlist */ for (sign = buf->b_signlist; sign != NULL; sign = sign->next) if (sign->lnum == lnum && sign->typenr == typenr) return sign->id; return 0; } # if defined(FEAT_SIGN_ICONS) || defined(PROTO) /* return the number of icons on the given line */ int buf_signcount(buf, lnum) buf_T *buf; linenr_T lnum; { signlist_T *sign; /* a sign in the signlist */ int count = 0; for (sign = buf->b_signlist; sign != NULL; sign = sign->next) if (sign->lnum == lnum) if (sign_get_image(sign->typenr) != NULL) count++; return count; } # endif /* FEAT_SIGN_ICONS */ # endif /* FEAT_NETBEANS_INTG */ /* * Delete signs in buffer "buf". */ static void buf_delete_signs(buf) buf_T *buf; { signlist_T *next; while (buf->b_signlist != NULL) { next = buf->b_signlist->next; vim_free(buf->b_signlist); buf->b_signlist = next; } } /* * Delete all signs in all buffers. */ void buf_delete_all_signs() { buf_T *buf; /* buffer we are checking for signs */ for (buf = firstbuf; buf != NULL; buf = buf->b_next) if (buf->b_signlist != NULL) { /* Need to redraw the windows to remove the sign column. */ redraw_buf_later(buf, NOT_VALID); buf_delete_signs(buf); } } /* * List placed signs for "rbuf". If "rbuf" is NULL do it for all buffers. */ void sign_list_placed(rbuf) buf_T *rbuf; { buf_T *buf; signlist_T *p; char lbuf[BUFSIZ]; MSG_PUTS_TITLE(_("\n--- Signs ---")); msg_putchar('\n'); if (rbuf == NULL) buf = firstbuf; else buf = rbuf; while (buf != NULL && !got_int) { if (buf->b_signlist != NULL) { vim_snprintf(lbuf, BUFSIZ, _("Signs for %s:"), buf->b_fname); MSG_PUTS_ATTR(lbuf, hl_attr(HLF_D)); msg_putchar('\n'); } for (p = buf->b_signlist; p != NULL && !got_int; p = p->next) { vim_snprintf(lbuf, BUFSIZ, _(" line=%ld id=%d name=%s"), (long)p->lnum, p->id, sign_typenr2name(p->typenr)); MSG_PUTS(lbuf); msg_putchar('\n'); } if (rbuf != NULL) break; buf = buf->b_next; } } /* * Adjust a placed sign for inserted/deleted lines. */ void sign_mark_adjust(line1, line2, amount, amount_after) linenr_T line1; linenr_T line2; long amount; long amount_after; { signlist_T *sign; /* a sign in a b_signlist */ for (sign = curbuf->b_signlist; sign != NULL; sign = sign->next) { if (sign->lnum >= line1 && sign->lnum <= line2) { if (amount == MAXLNUM) sign->lnum = line1; else sign->lnum += amount; } else if (sign->lnum > line2) sign->lnum += amount_after; } } #endif /* FEAT_SIGNS */ /* * Set 'buflisted' for curbuf to "on" and trigger autocommands if it changed. */ void set_buflisted(on) int on; { if (on != curbuf->b_p_bl) { curbuf->b_p_bl = on; #ifdef FEAT_AUTOCMD if (on) apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf); else apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf); #endif } } /* * Read the file for "buf" again and check if the contents changed. * Return TRUE if it changed or this could not be checked. */ int buf_contents_changed(buf) buf_T *buf; { buf_T *newbuf; int differ = TRUE; linenr_T lnum; aco_save_T aco; exarg_T ea; /* Allocate a buffer without putting it in the buffer list. */ newbuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY); if (newbuf == NULL) return TRUE; /* Force the 'fileencoding' and 'fileformat' to be equal. */ if (prep_exarg(&ea, buf) == FAIL) { wipe_buffer(newbuf, FALSE); return TRUE; } /* set curwin/curbuf to buf and save a few things */ aucmd_prepbuf(&aco, newbuf); if (ml_open(curbuf) == OK && readfile(buf->b_ffname, buf->b_fname, (linenr_T)0, (linenr_T)0, (linenr_T)MAXLNUM, &ea, READ_NEW | READ_DUMMY) == OK) { /* compare the two files line by line */ if (buf->b_ml.ml_line_count == curbuf->b_ml.ml_line_count) { differ = FALSE; for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum) if (STRCMP(ml_get_buf(buf, lnum, FALSE), ml_get(lnum)) != 0) { differ = TRUE; break; } } } vim_free(ea.cmd); /* restore curwin/curbuf and a few other things */ aucmd_restbuf(&aco); if (curbuf != newbuf) /* safety check */ wipe_buffer(newbuf, FALSE); return differ; } /* * Wipe out a buffer and decrement the last buffer number if it was used for * this buffer. Call this to wipe out a temp buffer that does not contain any * marks. */ void wipe_buffer(buf, aucmd) buf_T *buf; int aucmd UNUSED; /* When TRUE trigger autocommands. */ { if (buf->b_fnum == top_file_num - 1) --top_file_num; #ifdef FEAT_AUTOCMD if (!aucmd) /* Don't trigger BufDelete autocommands here. */ block_autocmds(); #endif close_buffer(NULL, buf, DOBUF_WIPE, FALSE); #ifdef FEAT_AUTOCMD if (!aucmd) unblock_autocmds(); #endif }
zyz2011-vim
src/buffer.c
C
gpl2
138,721
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * popupmnu.c: Popup menu (PUM) */ #include "vim.h" #if defined(FEAT_INS_EXPAND) || defined(PROTO) static pumitem_T *pum_array = NULL; /* items of displayed pum */ static int pum_size; /* nr of items in "pum_array" */ static int pum_selected; /* index of selected item or -1 */ static int pum_first = 0; /* index of top item */ static int pum_height; /* nr of displayed pum items */ static int pum_width; /* width of displayed pum items */ static int pum_base_width; /* width of pum items base */ static int pum_kind_width; /* width of pum items kind column */ static int pum_scrollbar; /* TRUE when scrollbar present */ static int pum_row; /* top row of pum */ static int pum_col; /* left column of pum */ static int pum_do_redraw = FALSE; /* do redraw anyway */ static int pum_set_selected __ARGS((int n, int repeat)); #define PUM_DEF_HEIGHT 10 #define PUM_DEF_WIDTH 15 /* * Show the popup menu with items "array[size]". * "array" must remain valid until pum_undisplay() is called! * When possible the leftmost character is aligned with screen column "col". * The menu appears above the screen line "row" or at "row" + "height" - 1. */ void pum_display(array, size, selected) pumitem_T *array; int size; int selected; /* index of initially selected item, none if out of range */ { int w; int def_width; int max_width; int kind_width; int extra_width; int i; int top_clear; int row; int context_lines; int col; int above_row = cmdline_row; int redo_count = 0; redo: def_width = PUM_DEF_WIDTH; max_width = 0; kind_width = 0; extra_width = 0; /* Pretend the pum is already there to avoid that must_redraw is set when * 'cuc' is on. */ pum_array = (pumitem_T *)1; validate_cursor_col(); pum_array = NULL; row = curwin->w_wrow + W_WINROW(curwin); if (firstwin->w_p_pvw) top_clear = firstwin->w_height; else top_clear = 0; /* When the preview window is at the bottom stop just above it. Also * avoid drawing over the status line so that it's clear there is a window * boundary. */ if (lastwin->w_p_pvw) above_row -= lastwin->w_height + lastwin->w_status_height + 1; /* * Figure out the size and position of the pum. */ if (size < PUM_DEF_HEIGHT) pum_height = size; else pum_height = PUM_DEF_HEIGHT; if (p_ph > 0 && pum_height > p_ph) pum_height = p_ph; /* Put the pum below "row" if possible. If there are few lines decide on * where there is more room. */ if (row + 2 >= above_row - pum_height && row > (above_row - top_clear) / 2) { /* pum above "row" */ /* Leave two lines of context if possible */ if (curwin->w_wrow - curwin->w_cline_row >= 2) context_lines = 2; else context_lines = curwin->w_wrow - curwin->w_cline_row; if (row >= size + context_lines) { pum_row = row - size - context_lines; pum_height = size; } else { pum_row = 0; pum_height = row - context_lines; } if (p_ph > 0 && pum_height > p_ph) { pum_row += pum_height - p_ph; pum_height = p_ph; } } else { /* pum below "row" */ /* Leave two lines of context if possible */ if (curwin->w_cline_row + curwin->w_cline_height - curwin->w_wrow >= 3) context_lines = 3; else context_lines = curwin->w_cline_row + curwin->w_cline_height - curwin->w_wrow; pum_row = row + context_lines; if (size > above_row - pum_row) pum_height = above_row - pum_row; else pum_height = size; if (p_ph > 0 && pum_height > p_ph) pum_height = p_ph; } /* don't display when we only have room for one line */ if (pum_height < 1 || (pum_height == 1 && size > 1)) return; /* If there is a preview window at the top avoid drawing over it. */ if (firstwin->w_p_pvw && pum_row < firstwin->w_height && pum_height > firstwin->w_height + 4) { pum_row += firstwin->w_height; pum_height -= firstwin->w_height; } /* Compute the width of the widest match and the widest extra. */ for (i = 0; i < size; ++i) { w = vim_strsize(array[i].pum_text); if (max_width < w) max_width = w; if (array[i].pum_kind != NULL) { w = vim_strsize(array[i].pum_kind) + 1; if (kind_width < w) kind_width = w; } if (array[i].pum_extra != NULL) { w = vim_strsize(array[i].pum_extra) + 1; if (extra_width < w) extra_width = w; } } pum_base_width = max_width; pum_kind_width = kind_width; /* Calculate column */ #ifdef FEAT_RIGHTLEFT if (curwin->w_p_rl) col = W_WINCOL(curwin) + W_WIDTH(curwin) - curwin->w_wcol - 1; else #endif col = W_WINCOL(curwin) + curwin->w_wcol; /* if there are more items than room we need a scrollbar */ if (pum_height < size) { pum_scrollbar = 1; ++max_width; } else pum_scrollbar = 0; if (def_width < max_width) def_width = max_width; if (((col < Columns - PUM_DEF_WIDTH || col < Columns - max_width) #ifdef FEAT_RIGHTLEFT && !curwin->w_p_rl) || (curwin->w_p_rl && (col > PUM_DEF_WIDTH || col > max_width) #endif )) { /* align pum column with "col" */ pum_col = col; #ifdef FEAT_RIGHTLEFT if (curwin->w_p_rl) pum_width = pum_col - pum_scrollbar + 1; else #endif pum_width = Columns - pum_col - pum_scrollbar; if (pum_width > max_width + kind_width + extra_width + 1 && pum_width > PUM_DEF_WIDTH) { pum_width = max_width + kind_width + extra_width + 1; if (pum_width < PUM_DEF_WIDTH) pum_width = PUM_DEF_WIDTH; } } else if (Columns < def_width) { /* not enough room, will use what we have */ #ifdef FEAT_RIGHTLEFT if (curwin->w_p_rl) pum_col = Columns - 1; else #endif pum_col = 0; pum_width = Columns - 1; } else { if (max_width > PUM_DEF_WIDTH) max_width = PUM_DEF_WIDTH; /* truncate */ #ifdef FEAT_RIGHTLEFT if (curwin->w_p_rl) pum_col = max_width - 1; else #endif pum_col = Columns - max_width; pum_width = max_width - pum_scrollbar; } pum_array = array; pum_size = size; /* Set selected item and redraw. If the window size changed need to redo * the positioning. Limit this to two times, when there is not much * room the window size will keep changing. */ if (pum_set_selected(selected, redo_count) && ++redo_count <= 2) goto redo; } /* * Redraw the popup menu, using "pum_first" and "pum_selected". */ void pum_redraw() { int row = pum_row; int col; int attr_norm = highlight_attr[HLF_PNI]; int attr_select = highlight_attr[HLF_PSI]; int attr_scroll = highlight_attr[HLF_PSB]; int attr_thumb = highlight_attr[HLF_PST]; int attr; int i; int idx; char_u *s; char_u *p = NULL; int totwidth, width, w; int thumb_pos = 0; int thumb_heigth = 1; int round; int n; if (pum_scrollbar) { thumb_heigth = pum_height * pum_height / pum_size; if (thumb_heigth == 0) thumb_heigth = 1; thumb_pos = (pum_first * (pum_height - thumb_heigth) + (pum_size - pum_height) / 2) / (pum_size - pum_height); } for (i = 0; i < pum_height; ++i) { idx = i + pum_first; attr = (idx == pum_selected) ? attr_select : attr_norm; /* prepend a space if there is room */ #ifdef FEAT_RIGHTLEFT if (curwin->w_p_rl) { if (pum_col < W_WINCOL(curwin) + W_WIDTH(curwin) - 1) screen_putchar(' ', row, pum_col + 1, attr); } else #endif if (pum_col > 0) screen_putchar(' ', row, pum_col - 1, attr); /* Display each entry, use two spaces for a Tab. * Do this 3 times: For the main text, kind and extra info */ col = pum_col; totwidth = 0; for (round = 1; round <= 3; ++round) { width = 0; s = NULL; switch (round) { case 1: p = pum_array[idx].pum_text; break; case 2: p = pum_array[idx].pum_kind; break; case 3: p = pum_array[idx].pum_extra; break; } if (p != NULL) for ( ; ; mb_ptr_adv(p)) { if (s == NULL) s = p; w = ptr2cells(p); if (*p == NUL || *p == TAB || totwidth + w > pum_width) { /* Display the text that fits or comes before a Tab. * First convert it to printable characters. */ char_u *st; int saved = *p; *p = NUL; st = transstr(s); *p = saved; #ifdef FEAT_RIGHTLEFT if (curwin->w_p_rl) { if (st != NULL) { char_u *rt = reverse_text(st); if (rt != NULL) { char_u *rt_start = rt; int size; size = vim_strsize(rt); if (size > pum_width) { do { size -= has_mbyte ? (*mb_ptr2cells)(rt) : 1; mb_ptr_adv(rt); } while (size > pum_width); if (size < pum_width) { /* Most left character requires * 2-cells but only 1 cell is * available on screen. Put a * '<' on the left of the pum * item */ *(--rt) = '<'; size++; } } screen_puts_len(rt, (int)STRLEN(rt), row, col - size + 1, attr); vim_free(rt_start); } vim_free(st); } col -= width; } else #endif { if (st != NULL) { screen_puts_len(st, (int)STRLEN(st), row, col, attr); vim_free(st); } col += width; } if (*p != TAB) break; /* Display two spaces for a Tab. */ #ifdef FEAT_RIGHTLEFT if (curwin->w_p_rl) { screen_puts_len((char_u *)" ", 2, row, col - 1, attr); col -= 2; } else #endif { screen_puts_len((char_u *)" ", 2, row, col, attr); col += 2; } totwidth += 2; s = NULL; /* start text at next char */ width = 0; } else width += w; } if (round > 1) n = pum_kind_width + 1; else n = 1; /* Stop when there is nothing more to display. */ if (round == 3 || (round == 2 && pum_array[idx].pum_extra == NULL) || (round == 1 && pum_array[idx].pum_kind == NULL && pum_array[idx].pum_extra == NULL) || pum_base_width + n >= pum_width) break; #ifdef FEAT_RIGHTLEFT if (curwin->w_p_rl) { screen_fill(row, row + 1, pum_col - pum_base_width - n + 1, col + 1, ' ', ' ', attr); col = pum_col - pum_base_width - n + 1; } else #endif { screen_fill(row, row + 1, col, pum_col + pum_base_width + n, ' ', ' ', attr); col = pum_col + pum_base_width + n; } totwidth = pum_base_width + n; } #ifdef FEAT_RIGHTLEFT if (curwin->w_p_rl) screen_fill(row, row + 1, pum_col - pum_width + 1, col + 1, ' ', ' ', attr); else #endif screen_fill(row, row + 1, col, pum_col + pum_width, ' ', ' ', attr); if (pum_scrollbar > 0) { #ifdef FEAT_RIGHTLEFT if (curwin->w_p_rl) screen_putchar(' ', row, pum_col - pum_width, i >= thumb_pos && i < thumb_pos + thumb_heigth ? attr_thumb : attr_scroll); else #endif screen_putchar(' ', row, pum_col + pum_width, i >= thumb_pos && i < thumb_pos + thumb_heigth ? attr_thumb : attr_scroll); } ++row; } } /* * Set the index of the currently selected item. The menu will scroll when * necessary. When "n" is out of range don't scroll. * This may be repeated when the preview window is used: * "repeat" == 0: open preview window normally * "repeat" == 1: open preview window but don't set the size * "repeat" == 2: don't open preview window * Returns TRUE when the window was resized and the location of the popup menu * must be recomputed. */ static int pum_set_selected(n, repeat) int n; int repeat; { int resized = FALSE; int context = pum_height / 2; pum_selected = n; if (pum_selected >= 0 && pum_selected < pum_size) { if (pum_first > pum_selected - 4) { /* scroll down; when we did a jump it's probably a PageUp then * scroll a whole page */ if (pum_first > pum_selected - 2) { pum_first -= pum_height - 2; if (pum_first < 0) pum_first = 0; else if (pum_first > pum_selected) pum_first = pum_selected; } else pum_first = pum_selected; } else if (pum_first < pum_selected - pum_height + 5) { /* scroll up; when we did a jump it's probably a PageDown then * scroll a whole page */ if (pum_first < pum_selected - pum_height + 1 + 2) { pum_first += pum_height - 2; if (pum_first < pum_selected - pum_height + 1) pum_first = pum_selected - pum_height + 1; } else pum_first = pum_selected - pum_height + 1; } /* Give a few lines of context when possible. */ if (context > 3) context = 3; if (pum_height > 2) { if (pum_first > pum_selected - context) { /* scroll down */ pum_first = pum_selected - context; if (pum_first < 0) pum_first = 0; } else if (pum_first < pum_selected + context - pum_height + 1) { /* scroll up */ pum_first = pum_selected + context - pum_height + 1; } } #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX) /* * Show extra info in the preview window if there is something and * 'completeopt' contains "preview". * Skip this when tried twice already. * Skip this also when there is not much room. * NOTE: Be very careful not to sync undo! */ if (pum_array[pum_selected].pum_info != NULL && Rows > 10 && repeat <= 1 && vim_strchr(p_cot, 'p') != NULL) { win_T *curwin_save = curwin; int res = OK; /* Open a preview window. 3 lines by default. Prefer * 'previewheight' if set and smaller. */ g_do_tagpreview = 3; if (p_pvh > 0 && p_pvh < g_do_tagpreview) g_do_tagpreview = p_pvh; resized = prepare_tagpreview(FALSE); g_do_tagpreview = 0; if (curwin->w_p_pvw) { if (curbuf->b_fname == NULL && curbuf->b_p_bt[0] == 'n' && curbuf->b_p_bt[2] == 'f' && curbuf->b_p_bh[0] == 'w') { /* Already a "wipeout" buffer, make it empty. */ while (!bufempty()) ml_delete((linenr_T)1, FALSE); } else { /* Don't want to sync undo in the current buffer. */ ++no_u_sync; res = do_ecmd(0, NULL, NULL, NULL, ECMD_ONE, 0, NULL); --no_u_sync; if (res == OK) { /* Edit a new, empty buffer. Set options for a "wipeout" * buffer. */ set_option_value((char_u *)"swf", 0L, NULL, OPT_LOCAL); set_option_value((char_u *)"bt", 0L, (char_u *)"nofile", OPT_LOCAL); set_option_value((char_u *)"bh", 0L, (char_u *)"wipe", OPT_LOCAL); set_option_value((char_u *)"diff", 0L, NULL, OPT_LOCAL); } } if (res == OK) { char_u *p, *e; linenr_T lnum = 0; for (p = pum_array[pum_selected].pum_info; *p != NUL; ) { e = vim_strchr(p, '\n'); if (e == NULL) { ml_append(lnum++, p, 0, FALSE); break; } else { *e = NUL; ml_append(lnum++, p, (int)(e - p + 1), FALSE); *e = '\n'; p = e + 1; } } /* Increase the height of the preview window to show the * text, but no more than 'previewheight' lines. */ if (repeat == 0) { if (lnum > p_pvh) lnum = p_pvh; if (curwin->w_height < lnum) { win_setheight((int)lnum); resized = TRUE; } } curbuf->b_changed = 0; curbuf->b_p_ma = FALSE; curwin->w_cursor.lnum = 1; curwin->w_cursor.col = 0; if (curwin != curwin_save && win_valid(curwin_save)) { /* Return cursor to where we were */ validate_cursor(); redraw_later(SOME_VALID); /* When the preview window was resized we need to * update the view on the buffer. Only go back to * the window when needed, otherwise it will always be * redraw. */ if (resized) { win_enter(curwin_save, TRUE); update_topline(); } /* Update the screen before drawing the popup menu. * Enable updating the status lines. */ pum_do_redraw = TRUE; update_screen(0); pum_do_redraw = FALSE; if (!resized && win_valid(curwin_save)) win_enter(curwin_save, TRUE); /* May need to update the screen again when there are * autocommands involved. */ pum_do_redraw = TRUE; update_screen(0); pum_do_redraw = FALSE; } } } } #endif } /* Never display more than we have */ if (pum_first > pum_size - pum_height) pum_first = pum_size - pum_height; if (!resized) pum_redraw(); return resized; } /* * Undisplay the popup menu (later). */ void pum_undisplay() { pum_array = NULL; redraw_all_later(SOME_VALID); #ifdef FEAT_WINDOWS redraw_tabline = TRUE; #endif status_redraw_all(); } /* * Clear the popup menu. Currently only resets the offset to the first * displayed item. */ void pum_clear() { pum_first = 0; } /* * Return TRUE if the popup menu is displayed. * Overruled when "pum_do_redraw" is set, used to redraw the status lines. */ int pum_visible() { return !pum_do_redraw && pum_array != NULL; } /* * Return the height of the popup menu, the number of entries visible. * Only valid when pum_visible() returns TRUE! */ int pum_get_height() { return pum_height; } #endif
zyz2011-vim
src/popupmnu.c
C
gpl2
17,551
/* vi:set ts=8 sts=8 sw=8: * * VIM - Vi IMproved by Bram Moolenaar * Visual Workshop integration by Gordon Prieur * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. */ #ifndef NBDEBUG_H #define NBDEBUG_H #ifdef NBDEBUG #ifndef ASSERT #define ASSERT(c) \ if (!(c)) { \ fprintf(stderr, "Assertion failed: line %d, file %s\n", \ __LINE__, __FILE__); \ fflush(stderr); \ abort(); \ } #endif #define nbdebug(a) nbdbg a #define NB_TRACE 0x00000001 #define NB_TRACE_VERBOSE 0x00000002 #define NB_TRACE_COLONCMD 0x00000004 #define NB_PRINT 0x00000008 #define NB_DEBUG_ALL 0xffffffff #define NBDLEVEL(flags) (nb_debug != NULL && (nb_dlevel & (flags))) #define NBDEBUG_TRACE 1 typedef enum { WT_ENV = 1, /* look for env var if set */ WT_WAIT, /* look for ~/.gvimwait if set */ WT_STOP /* look for ~/.gvimstop if set */ } WtWait; void nbdbg(char *, ...); void nbdebug_wait __ARGS((u_int wait_flags, char *wait_var, u_int wait_secs)); void nbdebug_log_init __ARGS((char *log_var, char *level_var)); extern FILE *nb_debug; extern u_int nb_dlevel; /* nb_debug verbosity level */ # else /* not NBDEBUG */ #ifndef ASSERT # define ASSERT(c) #endif /* * The following 3 stubs are needed because a macro cannot be used because of * the variable number of arguments. */ void nbdbg( char *fmt, ...) { } #endif /* NBDEBUG */ #endif /* NBDEBUG_H */
zyz2011-vim
src/nbdebug.h
C
gpl2
1,477
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * memfile.c: Contains the functions for handling blocks of memory which can * be stored in a file. This is the implementation of a sort of virtual memory. * * A memfile consists of a sequence of blocks. The blocks numbered from 0 * upwards have been assigned a place in the actual file. The block number * is equal to the page number in the file. The * blocks with negative numbers are currently in memory only. They can be * assigned a place in the file when too much memory is being used. At that * moment they get a new, positive, number. A list is used for translation of * negative to positive numbers. * * The size of a block is a multiple of a page size, normally the page size of * the device the file is on. Most blocks are 1 page long. A Block of multiple * pages is used for a line that does not fit in a single page. * * Each block can be in memory and/or in a file. The block stays in memory * as long as it is locked. If it is no longer locked it can be swapped out to * the file. It is only written to the file if it has been changed. * * Under normal operation the file is created when opening the memory file and * deleted when closing the memory file. Only with recovery an existing memory * file is opened. */ #include "vim.h" /* * Some systems have the page size in statfs.f_bsize, some in stat.st_blksize */ #ifdef HAVE_ST_BLKSIZE # define STATFS stat # define F_BSIZE st_blksize # define fstatfs(fd, buf, len, nul) mch_fstat((fd), (buf)) #else # ifdef HAVE_SYS_STATFS_H # include <sys/statfs.h> # define STATFS statfs # define F_BSIZE f_bsize # ifdef __MINT__ /* do we still need this? */ # define fstatfs(fd, buf, len, nul) mch_fstat((fd), (buf)) # endif # endif #endif /* * for Amiga Dos 2.0x we use Flush */ #ifdef AMIGA # ifdef FEAT_ARP extern int dos2; /* this is in os_amiga.c */ # endif # ifdef SASC # include <proto/dos.h> # include <ios1.h> /* for chkufb() */ # endif #endif #define MEMFILE_PAGE_SIZE 4096 /* default page size */ static long_u total_mem_used = 0; /* total memory used for memfiles */ static void mf_ins_hash __ARGS((memfile_T *, bhdr_T *)); static void mf_rem_hash __ARGS((memfile_T *, bhdr_T *)); static bhdr_T *mf_find_hash __ARGS((memfile_T *, blocknr_T)); static void mf_ins_used __ARGS((memfile_T *, bhdr_T *)); static void mf_rem_used __ARGS((memfile_T *, bhdr_T *)); static bhdr_T *mf_release __ARGS((memfile_T *, int)); static bhdr_T *mf_alloc_bhdr __ARGS((memfile_T *, int)); static void mf_free_bhdr __ARGS((bhdr_T *)); static void mf_ins_free __ARGS((memfile_T *, bhdr_T *)); static bhdr_T *mf_rem_free __ARGS((memfile_T *)); static int mf_read __ARGS((memfile_T *, bhdr_T *)); static int mf_write __ARGS((memfile_T *, bhdr_T *)); static int mf_write_block __ARGS((memfile_T *mfp, bhdr_T *hp, off_t offset, unsigned size)); static int mf_trans_add __ARGS((memfile_T *, bhdr_T *)); static void mf_do_open __ARGS((memfile_T *, char_u *, int)); static void mf_hash_init __ARGS((mf_hashtab_T *)); static void mf_hash_free __ARGS((mf_hashtab_T *)); static void mf_hash_free_all __ARGS((mf_hashtab_T *)); static mf_hashitem_T *mf_hash_find __ARGS((mf_hashtab_T *, blocknr_T)); static void mf_hash_add_item __ARGS((mf_hashtab_T *, mf_hashitem_T *)); static void mf_hash_rem_item __ARGS((mf_hashtab_T *, mf_hashitem_T *)); static int mf_hash_grow __ARGS((mf_hashtab_T *)); /* * The functions for using a memfile: * * mf_open() open a new or existing memfile * mf_open_file() open a swap file for an existing memfile * mf_close() close (and delete) a memfile * mf_new() create a new block in a memfile and lock it * mf_get() get an existing block and lock it * mf_put() unlock a block, may be marked for writing * mf_free() remove a block * mf_sync() sync changed parts of memfile to disk * mf_release_all() release as much memory as possible * mf_trans_del() may translate negative to positive block number * mf_fullname() make file name full path (use before first :cd) */ /* * Open an existing or new memory block file. * * fname: name of file to use (NULL means no file at all) * Note: fname must have been allocated, it is not copied! * If opening the file fails, fname is freed. * flags: flags for open() call * * If fname != NULL and file cannot be opened, fail. * * return value: identifier for this memory block file. */ memfile_T * mf_open(fname, flags) char_u *fname; int flags; { memfile_T *mfp; off_t size; #if defined(STATFS) && defined(UNIX) && !defined(__QNX__) # define USE_FSTATFS struct STATFS stf; #endif if ((mfp = (memfile_T *)alloc((unsigned)sizeof(memfile_T))) == NULL) return NULL; if (fname == NULL) /* no file for this memfile, use memory only */ { mfp->mf_fname = NULL; mfp->mf_ffname = NULL; mfp->mf_fd = -1; } else { mf_do_open(mfp, fname, flags); /* try to open the file */ /* if the file cannot be opened, return here */ if (mfp->mf_fd < 0) { vim_free(mfp); return NULL; } } mfp->mf_free_first = NULL; /* free list is empty */ mfp->mf_used_first = NULL; /* used list is empty */ mfp->mf_used_last = NULL; mfp->mf_dirty = FALSE; mfp->mf_used_count = 0; mf_hash_init(&mfp->mf_hash); mf_hash_init(&mfp->mf_trans); mfp->mf_page_size = MEMFILE_PAGE_SIZE; #ifdef FEAT_CRYPT mfp->mf_old_key = NULL; #endif #ifdef USE_FSTATFS /* * Try to set the page size equal to the block size of the device. * Speeds up I/O a lot. * When recovering, the actual block size will be retrieved from block 0 * in ml_recover(). The size used here may be wrong, therefore * mf_blocknr_max must be rounded up. */ if (mfp->mf_fd >= 0 && fstatfs(mfp->mf_fd, &stf, sizeof(struct statfs), 0) == 0 && stf.F_BSIZE >= MIN_SWAP_PAGE_SIZE && stf.F_BSIZE <= MAX_SWAP_PAGE_SIZE) mfp->mf_page_size = stf.F_BSIZE; #endif if (mfp->mf_fd < 0 || (flags & (O_TRUNC|O_EXCL)) || (size = lseek(mfp->mf_fd, (off_t)0L, SEEK_END)) <= 0) mfp->mf_blocknr_max = 0; /* no file or empty file */ else mfp->mf_blocknr_max = (blocknr_T)((size + mfp->mf_page_size - 1) / mfp->mf_page_size); mfp->mf_blocknr_min = -1; mfp->mf_neg_count = 0; mfp->mf_infile_count = mfp->mf_blocknr_max; /* * Compute maximum number of pages ('maxmem' is in Kbyte): * 'mammem' * 1Kbyte / page-size-in-bytes. * Avoid overflow by first reducing page size as much as possible. */ { int shift = 10; unsigned page_size = mfp->mf_page_size; while (shift > 0 && (page_size & 1) == 0) { page_size = page_size >> 1; --shift; } mfp->mf_used_count_max = (p_mm << shift) / page_size; if (mfp->mf_used_count_max < 10) mfp->mf_used_count_max = 10; } return mfp; } /* * Open a file for an existing memfile. Used when updatecount set from 0 to * some value. * If the file already exists, this fails. * "fname" is the name of file to use (NULL means no file at all) * Note: "fname" must have been allocated, it is not copied! If opening the * file fails, "fname" is freed. * * return value: FAIL if file could not be opened, OK otherwise */ int mf_open_file(mfp, fname) memfile_T *mfp; char_u *fname; { mf_do_open(mfp, fname, O_RDWR|O_CREAT|O_EXCL); /* try to open the file */ if (mfp->mf_fd < 0) return FAIL; mfp->mf_dirty = TRUE; return OK; } /* * Close a memory file and delete the associated file if 'del_file' is TRUE. */ void mf_close(mfp, del_file) memfile_T *mfp; int del_file; { bhdr_T *hp, *nextp; if (mfp == NULL) /* safety check */ return; if (mfp->mf_fd >= 0) { if (close(mfp->mf_fd) < 0) EMSG(_(e_swapclose)); } if (del_file && mfp->mf_fname != NULL) mch_remove(mfp->mf_fname); /* free entries in used list */ for (hp = mfp->mf_used_first; hp != NULL; hp = nextp) { total_mem_used -= hp->bh_page_count * mfp->mf_page_size; nextp = hp->bh_next; mf_free_bhdr(hp); } while (mfp->mf_free_first != NULL) /* free entries in free list */ vim_free(mf_rem_free(mfp)); mf_hash_free(&mfp->mf_hash); mf_hash_free_all(&mfp->mf_trans); /* free hashtable and its items */ vim_free(mfp->mf_fname); vim_free(mfp->mf_ffname); vim_free(mfp); } /* * Close the swap file for a memfile. Used when 'swapfile' is reset. */ void mf_close_file(buf, getlines) buf_T *buf; int getlines; /* get all lines into memory? */ { memfile_T *mfp; linenr_T lnum; mfp = buf->b_ml.ml_mfp; if (mfp == NULL || mfp->mf_fd < 0) /* nothing to close */ return; if (getlines) { /* get all blocks in memory by accessing all lines (clumsy!) */ mf_dont_release = TRUE; for (lnum = 1; lnum <= buf->b_ml.ml_line_count; ++lnum) (void)ml_get_buf(buf, lnum, FALSE); mf_dont_release = FALSE; /* TODO: should check if all blocks are really in core */ } if (close(mfp->mf_fd) < 0) /* close the file */ EMSG(_(e_swapclose)); mfp->mf_fd = -1; if (mfp->mf_fname != NULL) { mch_remove(mfp->mf_fname); /* delete the swap file */ vim_free(mfp->mf_fname); vim_free(mfp->mf_ffname); mfp->mf_fname = NULL; mfp->mf_ffname = NULL; } } /* * Set new size for a memfile. Used when block 0 of a swapfile has been read * and the size it indicates differs from what was guessed. */ void mf_new_page_size(mfp, new_size) memfile_T *mfp; unsigned new_size; { /* Correct the memory used for block 0 to the new size, because it will be * freed with that size later on. */ total_mem_used += new_size - mfp->mf_page_size; mfp->mf_page_size = new_size; } /* * get a new block * * negative: TRUE if negative block number desired (data block) */ bhdr_T * mf_new(mfp, negative, page_count) memfile_T *mfp; int negative; int page_count; { bhdr_T *hp; /* new bhdr_T */ bhdr_T *freep; /* first block in free list */ char_u *p; /* * If we reached the maximum size for the used memory blocks, release one * If a bhdr_T is returned, use it and adjust the page_count if necessary. */ hp = mf_release(mfp, page_count); /* * Decide on the number to use: * If there is a free block, use its number. * Otherwise use mf_block_min for a negative number, mf_block_max for * a positive number. */ freep = mfp->mf_free_first; if (!negative && freep != NULL && freep->bh_page_count >= page_count) { /* * If the block in the free list has more pages, take only the number * of pages needed and allocate a new bhdr_T with data * * If the number of pages matches and mf_release() did not return a * bhdr_T, use the bhdr_T from the free list and allocate the data * * If the number of pages matches and mf_release() returned a bhdr_T, * just use the number and free the bhdr_T from the free list */ if (freep->bh_page_count > page_count) { if (hp == NULL && (hp = mf_alloc_bhdr(mfp, page_count)) == NULL) return NULL; hp->bh_bnum = freep->bh_bnum; freep->bh_bnum += page_count; freep->bh_page_count -= page_count; } else if (hp == NULL) /* need to allocate memory for this block */ { if ((p = (char_u *)alloc(mfp->mf_page_size * page_count)) == NULL) return NULL; hp = mf_rem_free(mfp); hp->bh_data = p; } else /* use the number, remove entry from free list */ { freep = mf_rem_free(mfp); hp->bh_bnum = freep->bh_bnum; vim_free(freep); } } else /* get a new number */ { if (hp == NULL && (hp = mf_alloc_bhdr(mfp, page_count)) == NULL) return NULL; if (negative) { hp->bh_bnum = mfp->mf_blocknr_min--; mfp->mf_neg_count++; } else { hp->bh_bnum = mfp->mf_blocknr_max; mfp->mf_blocknr_max += page_count; } } hp->bh_flags = BH_LOCKED | BH_DIRTY; /* new block is always dirty */ mfp->mf_dirty = TRUE; hp->bh_page_count = page_count; mf_ins_used(mfp, hp); mf_ins_hash(mfp, hp); /* * Init the data to all zero, to avoid reading uninitialized data. * This also avoids that the passwd file ends up in the swap file! */ (void)vim_memset((char *)(hp->bh_data), 0, (size_t)mfp->mf_page_size * page_count); return hp; } /* * Get existing block "nr" with "page_count" pages. * * Note: The caller should first check a negative nr with mf_trans_del() */ bhdr_T * mf_get(mfp, nr, page_count) memfile_T *mfp; blocknr_T nr; int page_count; { bhdr_T *hp; /* doesn't exist */ if (nr >= mfp->mf_blocknr_max || nr <= mfp->mf_blocknr_min) return NULL; /* * see if it is in the cache */ hp = mf_find_hash(mfp, nr); if (hp == NULL) /* not in the hash list */ { if (nr < 0 || nr >= mfp->mf_infile_count) /* can't be in the file */ return NULL; /* could check here if the block is in the free list */ /* * Check if we need to flush an existing block. * If so, use that block. * If not, allocate a new block. */ hp = mf_release(mfp, page_count); if (hp == NULL && (hp = mf_alloc_bhdr(mfp, page_count)) == NULL) return NULL; hp->bh_bnum = nr; hp->bh_flags = 0; hp->bh_page_count = page_count; if (mf_read(mfp, hp) == FAIL) /* cannot read the block! */ { mf_free_bhdr(hp); return NULL; } } else { mf_rem_used(mfp, hp); /* remove from list, insert in front below */ mf_rem_hash(mfp, hp); } hp->bh_flags |= BH_LOCKED; mf_ins_used(mfp, hp); /* put in front of used list */ mf_ins_hash(mfp, hp); /* put in front of hash list */ return hp; } /* * release the block *hp * * dirty: Block must be written to file later * infile: Block should be in file (needed for recovery) * * no return value, function cannot fail */ void mf_put(mfp, hp, dirty, infile) memfile_T *mfp; bhdr_T *hp; int dirty; int infile; { int flags; flags = hp->bh_flags; if ((flags & BH_LOCKED) == 0) EMSG(_("E293: block was not locked")); flags &= ~BH_LOCKED; if (dirty) { flags |= BH_DIRTY; mfp->mf_dirty = TRUE; } hp->bh_flags = flags; if (infile) mf_trans_add(mfp, hp); /* may translate negative in positive nr */ } /* * block *hp is no longer in used, may put it in the free list of memfile *mfp */ void mf_free(mfp, hp) memfile_T *mfp; bhdr_T *hp; { vim_free(hp->bh_data); /* free the memory */ mf_rem_hash(mfp, hp); /* get *hp out of the hash list */ mf_rem_used(mfp, hp); /* get *hp out of the used list */ if (hp->bh_bnum < 0) { vim_free(hp); /* don't want negative numbers in free list */ mfp->mf_neg_count--; } else mf_ins_free(mfp, hp); /* put *hp in the free list */ } #if defined(__MORPHOS__) && defined(__libnix__) /* function is missing in MorphOS libnix version */ extern unsigned long *__stdfiledes; static unsigned long fdtofh(int filedescriptor) { return __stdfiledes[filedescriptor]; } #endif /* * Sync the memory file *mfp to disk. * Flags: * MFS_ALL If not given, blocks with negative numbers are not synced, * even when they are dirty! * MFS_STOP Stop syncing when a character becomes available, but sync at * least one block. * MFS_FLUSH Make sure buffers are flushed to disk, so they will survive a * system crash. * MFS_ZERO Only write block 0. * * Return FAIL for failure, OK otherwise */ int mf_sync(mfp, flags) memfile_T *mfp; int flags; { int status; bhdr_T *hp; #if defined(SYNC_DUP_CLOSE) && !defined(MSDOS) int fd; #endif int got_int_save = got_int; if (mfp->mf_fd < 0) /* there is no file, nothing to do */ { mfp->mf_dirty = FALSE; return FAIL; } /* Only a CTRL-C while writing will break us here, not one typed * previously. */ got_int = FALSE; /* * sync from last to first (may reduce the probability of an inconsistent * file) If a write fails, it is very likely caused by a full filesystem. * Then we only try to write blocks within the existing file. If that also * fails then we give up. */ status = OK; for (hp = mfp->mf_used_last; hp != NULL; hp = hp->bh_prev) if (((flags & MFS_ALL) || hp->bh_bnum >= 0) && (hp->bh_flags & BH_DIRTY) && (status == OK || (hp->bh_bnum >= 0 && hp->bh_bnum < mfp->mf_infile_count))) { if ((flags & MFS_ZERO) && hp->bh_bnum != 0) continue; if (mf_write(mfp, hp) == FAIL) { if (status == FAIL) /* double error: quit syncing */ break; status = FAIL; } if (flags & MFS_STOP) { /* Stop when char available now. */ if (ui_char_avail()) break; } else ui_breakcheck(); if (got_int) break; } /* * If the whole list is flushed, the memfile is not dirty anymore. * In case of an error this flag is also set, to avoid trying all the time. */ if (hp == NULL || status == FAIL) mfp->mf_dirty = FALSE; if ((flags & MFS_FLUSH) && *p_sws != NUL) { #if defined(UNIX) # ifdef HAVE_FSYNC /* * most Unixes have the very useful fsync() function, just what we need. * However, with OS/2 and EMX it is also available, but there are * reports of bad problems with it (a bug in HPFS.IFS). * So we disable use of it here in case someone tries to be smart * and changes os_os2_cfg.h... (even though there is no __EMX__ test * in the #if, as __EMX__ does not have sync(); we hope for a timely * sync from the system itself). */ # if defined(__EMX__) error "Dont use fsync with EMX! Read emxdoc.doc or emxfix01.doc for info." # endif if (STRCMP(p_sws, "fsync") == 0) { if (fsync(mfp->mf_fd)) status = FAIL; } else # endif /* OpenNT is strictly POSIX (Benzinger) */ /* Tandem/Himalaya NSK-OSS doesn't have sync() */ # if defined(__OPENNT) || defined(__TANDEM) fflush(NULL); # else sync(); # endif #endif #ifdef VMS if (STRCMP(p_sws, "fsync") == 0) { if (fsync(mfp->mf_fd)) status = FAIL; } #endif #ifdef MSDOS if (_dos_commit(mfp->mf_fd)) status = FAIL; #else # ifdef SYNC_DUP_CLOSE /* * Win32 is a bit more work: Duplicate the file handle and close it. * This should flush the file to disk. */ if ((fd = dup(mfp->mf_fd)) >= 0) close(fd); # endif #endif #ifdef AMIGA # if defined(__AROS__) || defined(__amigaos4__) if (fsync(mfp->mf_fd) != 0) status = FAIL; # else /* * Flush() only exists for AmigaDos 2.0. * For 1.3 it should be done with close() + open(), but then the risk * is that the open() may fail and lose the file.... */ # ifdef FEAT_ARP if (dos2) # endif # ifdef SASC { struct UFB *fp = chkufb(mfp->mf_fd); if (fp != NULL) Flush(fp->ufbfh); } # else # if defined(_DCC) || defined(__GNUC__) || defined(__MORPHOS__) { # if defined(__GNUC__) && !defined(__MORPHOS__) && defined(__libnix__) /* Have function (in libnix at least), * but ain't got no prototype anywhere. */ extern unsigned long fdtofh(int filedescriptor); # endif # if !defined(__libnix__) fflush(NULL); # else BPTR fh = (BPTR)fdtofh(mfp->mf_fd); if (fh != 0) Flush(fh); # endif } # else /* assume Manx */ Flush(_devtab[mfp->mf_fd].fd); # endif # endif # endif #endif /* AMIGA */ } got_int |= got_int_save; return status; } /* * For all blocks in memory file *mfp that have a positive block number set * the dirty flag. These are blocks that need to be written to a newly * created swapfile. */ void mf_set_dirty(mfp) memfile_T *mfp; { bhdr_T *hp; for (hp = mfp->mf_used_last; hp != NULL; hp = hp->bh_prev) if (hp->bh_bnum > 0) hp->bh_flags |= BH_DIRTY; mfp->mf_dirty = TRUE; } /* * insert block *hp in front of hashlist of memfile *mfp */ static void mf_ins_hash(mfp, hp) memfile_T *mfp; bhdr_T *hp; { mf_hash_add_item(&mfp->mf_hash, (mf_hashitem_T *)hp); } /* * remove block *hp from hashlist of memfile list *mfp */ static void mf_rem_hash(mfp, hp) memfile_T *mfp; bhdr_T *hp; { mf_hash_rem_item(&mfp->mf_hash, (mf_hashitem_T *)hp); } /* * look in hash lists of memfile *mfp for block header with number 'nr' */ static bhdr_T * mf_find_hash(mfp, nr) memfile_T *mfp; blocknr_T nr; { return (bhdr_T *)mf_hash_find(&mfp->mf_hash, nr); } /* * insert block *hp in front of used list of memfile *mfp */ static void mf_ins_used(mfp, hp) memfile_T *mfp; bhdr_T *hp; { hp->bh_next = mfp->mf_used_first; mfp->mf_used_first = hp; hp->bh_prev = NULL; if (hp->bh_next == NULL) /* list was empty, adjust last pointer */ mfp->mf_used_last = hp; else hp->bh_next->bh_prev = hp; mfp->mf_used_count += hp->bh_page_count; total_mem_used += hp->bh_page_count * mfp->mf_page_size; } /* * remove block *hp from used list of memfile *mfp */ static void mf_rem_used(mfp, hp) memfile_T *mfp; bhdr_T *hp; { if (hp->bh_next == NULL) /* last block in used list */ mfp->mf_used_last = hp->bh_prev; else hp->bh_next->bh_prev = hp->bh_prev; if (hp->bh_prev == NULL) /* first block in used list */ mfp->mf_used_first = hp->bh_next; else hp->bh_prev->bh_next = hp->bh_next; mfp->mf_used_count -= hp->bh_page_count; total_mem_used -= hp->bh_page_count * mfp->mf_page_size; } /* * Release the least recently used block from the used list if the number * of used memory blocks gets to big. * * Return the block header to the caller, including the memory block, so * it can be re-used. Make sure the page_count is right. */ static bhdr_T * mf_release(mfp, page_count) memfile_T *mfp; int page_count; { bhdr_T *hp; int need_release; buf_T *buf; /* don't release while in mf_close_file() */ if (mf_dont_release) return NULL; /* * Need to release a block if the number of blocks for this memfile is * higher than the maximum or total memory used is over 'maxmemtot' */ need_release = ((mfp->mf_used_count >= mfp->mf_used_count_max) || (total_mem_used >> 10) >= (long_u)p_mmt); /* * Try to create a swap file if the amount of memory used is getting too * high. */ if (mfp->mf_fd < 0 && need_release && p_uc) { /* find for which buffer this memfile is */ for (buf = firstbuf; buf != NULL; buf = buf->b_next) if (buf->b_ml.ml_mfp == mfp) break; if (buf != NULL && buf->b_may_swap) ml_open_file(buf); } /* * don't release a block if * there is no file for this memfile * or * the number of blocks for this memfile is lower than the maximum * and * total memory used is not up to 'maxmemtot' */ if (mfp->mf_fd < 0 || !need_release) return NULL; for (hp = mfp->mf_used_last; hp != NULL; hp = hp->bh_prev) if (!(hp->bh_flags & BH_LOCKED)) break; if (hp == NULL) /* not a single one that can be released */ return NULL; /* * If the block is dirty, write it. * If the write fails we don't free it. */ if ((hp->bh_flags & BH_DIRTY) && mf_write(mfp, hp) == FAIL) return NULL; mf_rem_used(mfp, hp); mf_rem_hash(mfp, hp); /* * If a bhdr_T is returned, make sure that the page_count of bh_data is * right */ if (hp->bh_page_count != page_count) { vim_free(hp->bh_data); if ((hp->bh_data = alloc(mfp->mf_page_size * page_count)) == NULL) { vim_free(hp); return NULL; } hp->bh_page_count = page_count; } return hp; } /* * release as many blocks as possible * Used in case of out of memory * * return TRUE if any memory was released */ int mf_release_all() { buf_T *buf; memfile_T *mfp; bhdr_T *hp; int retval = FALSE; for (buf = firstbuf; buf != NULL; buf = buf->b_next) { mfp = buf->b_ml.ml_mfp; if (mfp != NULL) { /* If no swap file yet, may open one */ if (mfp->mf_fd < 0 && buf->b_may_swap) ml_open_file(buf); /* only if there is a swapfile */ if (mfp->mf_fd >= 0) { for (hp = mfp->mf_used_last; hp != NULL; ) { if (!(hp->bh_flags & BH_LOCKED) && (!(hp->bh_flags & BH_DIRTY) || mf_write(mfp, hp) != FAIL)) { mf_rem_used(mfp, hp); mf_rem_hash(mfp, hp); mf_free_bhdr(hp); hp = mfp->mf_used_last; /* re-start, list was changed */ retval = TRUE; } else hp = hp->bh_prev; } } } } return retval; } /* * Allocate a block header and a block of memory for it */ static bhdr_T * mf_alloc_bhdr(mfp, page_count) memfile_T *mfp; int page_count; { bhdr_T *hp; if ((hp = (bhdr_T *)alloc((unsigned)sizeof(bhdr_T))) != NULL) { if ((hp->bh_data = (char_u *)alloc(mfp->mf_page_size * page_count)) == NULL) { vim_free(hp); /* not enough memory */ return NULL; } hp->bh_page_count = page_count; } return hp; } /* * Free a block header and the block of memory for it */ static void mf_free_bhdr(hp) bhdr_T *hp; { vim_free(hp->bh_data); vim_free(hp); } /* * insert entry *hp in the free list */ static void mf_ins_free(mfp, hp) memfile_T *mfp; bhdr_T *hp; { hp->bh_next = mfp->mf_free_first; mfp->mf_free_first = hp; } /* * remove the first entry from the free list and return a pointer to it * Note: caller must check that mfp->mf_free_first is not NULL! */ static bhdr_T * mf_rem_free(mfp) memfile_T *mfp; { bhdr_T *hp; hp = mfp->mf_free_first; mfp->mf_free_first = hp->bh_next; return hp; } /* * read a block from disk * * Return FAIL for failure, OK otherwise */ static int mf_read(mfp, hp) memfile_T *mfp; bhdr_T *hp; { off_t offset; unsigned page_size; unsigned size; if (mfp->mf_fd < 0) /* there is no file, can't read */ return FAIL; page_size = mfp->mf_page_size; offset = (off_t)page_size * hp->bh_bnum; size = page_size * hp->bh_page_count; if (lseek(mfp->mf_fd, offset, SEEK_SET) != offset) { PERROR(_("E294: Seek error in swap file read")); return FAIL; } if ((unsigned)read_eintr(mfp->mf_fd, hp->bh_data, size) != size) { PERROR(_("E295: Read error in swap file")); return FAIL; } #ifdef FEAT_CRYPT /* Decrypt if 'key' is set and this is a data block. */ if (*mfp->mf_buffer->b_p_key != NUL) ml_decrypt_data(mfp, hp->bh_data, offset, size); #endif return OK; } /* * write a block to disk * * Return FAIL for failure, OK otherwise */ static int mf_write(mfp, hp) memfile_T *mfp; bhdr_T *hp; { off_t offset; /* offset in the file */ blocknr_T nr; /* block nr which is being written */ bhdr_T *hp2; unsigned page_size; /* number of bytes in a page */ unsigned page_count; /* number of pages written */ unsigned size; /* number of bytes written */ if (mfp->mf_fd < 0) /* there is no file, can't write */ return FAIL; if (hp->bh_bnum < 0) /* must assign file block number */ if (mf_trans_add(mfp, hp) == FAIL) return FAIL; page_size = mfp->mf_page_size; /* * We don't want gaps in the file. Write the blocks in front of *hp * to extend the file. * If block 'mf_infile_count' is not in the hash list, it has been * freed. Fill the space in the file with data from the current block. */ for (;;) { nr = hp->bh_bnum; if (nr > mfp->mf_infile_count) /* beyond end of file */ { nr = mfp->mf_infile_count; hp2 = mf_find_hash(mfp, nr); /* NULL catched below */ } else hp2 = hp; offset = (off_t)page_size * nr; if (lseek(mfp->mf_fd, offset, SEEK_SET) != offset) { PERROR(_("E296: Seek error in swap file write")); return FAIL; } if (hp2 == NULL) /* freed block, fill with dummy data */ page_count = 1; else page_count = hp2->bh_page_count; size = page_size * page_count; if (mf_write_block(mfp, hp2 == NULL ? hp : hp2, offset, size) == FAIL) { /* * Avoid repeating the error message, this mostly happens when the * disk is full. We give the message again only after a successful * write or when hitting a key. We keep on trying, in case some * space becomes available. */ if (!did_swapwrite_msg) EMSG(_("E297: Write error in swap file")); did_swapwrite_msg = TRUE; return FAIL; } did_swapwrite_msg = FALSE; if (hp2 != NULL) /* written a non-dummy block */ hp2->bh_flags &= ~BH_DIRTY; /* appended to the file */ if (nr + (blocknr_T)page_count > mfp->mf_infile_count) mfp->mf_infile_count = nr + page_count; if (nr == hp->bh_bnum) /* written the desired block */ break; } return OK; } /* * Write block "hp" with data size "size" to file "mfp->mf_fd". * Takes care of encryption. * Return FAIL or OK. */ static int mf_write_block(mfp, hp, offset, size) memfile_T *mfp; bhdr_T *hp; off_t offset UNUSED; unsigned size; { char_u *data = hp->bh_data; int result = OK; #ifdef FEAT_CRYPT /* Encrypt if 'key' is set and this is a data block. */ if (*mfp->mf_buffer->b_p_key != NUL) { data = ml_encrypt_data(mfp, data, offset, size); if (data == NULL) return FAIL; } #endif if ((unsigned)write_eintr(mfp->mf_fd, data, size) != size) result = FAIL; #ifdef FEAT_CRYPT if (data != hp->bh_data) vim_free(data); #endif return result; } /* * Make block number for *hp positive and add it to the translation list * * Return FAIL for failure, OK otherwise */ static int mf_trans_add(mfp, hp) memfile_T *mfp; bhdr_T *hp; { bhdr_T *freep; blocknr_T new_bnum; NR_TRANS *np; int page_count; if (hp->bh_bnum >= 0) /* it's already positive */ return OK; if ((np = (NR_TRANS *)alloc((unsigned)sizeof(NR_TRANS))) == NULL) return FAIL; /* * Get a new number for the block. * If the first item in the free list has sufficient pages, use its number * Otherwise use mf_blocknr_max. */ freep = mfp->mf_free_first; page_count = hp->bh_page_count; if (freep != NULL && freep->bh_page_count >= page_count) { new_bnum = freep->bh_bnum; /* * If the page count of the free block was larger, recude it. * If the page count matches, remove the block from the free list */ if (freep->bh_page_count > page_count) { freep->bh_bnum += page_count; freep->bh_page_count -= page_count; } else { freep = mf_rem_free(mfp); vim_free(freep); } } else { new_bnum = mfp->mf_blocknr_max; mfp->mf_blocknr_max += page_count; } np->nt_old_bnum = hp->bh_bnum; /* adjust number */ np->nt_new_bnum = new_bnum; mf_rem_hash(mfp, hp); /* remove from old hash list */ hp->bh_bnum = new_bnum; mf_ins_hash(mfp, hp); /* insert in new hash list */ /* Insert "np" into "mf_trans" hashtable with key "np->nt_old_bnum" */ mf_hash_add_item(&mfp->mf_trans, (mf_hashitem_T *)np); return OK; } /* * Lookup a translation from the trans lists and delete the entry * * Return the positive new number when found, the old number when not found */ blocknr_T mf_trans_del(mfp, old_nr) memfile_T *mfp; blocknr_T old_nr; { NR_TRANS *np; blocknr_T new_bnum; np = (NR_TRANS *)mf_hash_find(&mfp->mf_trans, old_nr); if (np == NULL) /* not found */ return old_nr; mfp->mf_neg_count--; new_bnum = np->nt_new_bnum; /* remove entry from the trans list */ mf_hash_rem_item(&mfp->mf_trans, (mf_hashitem_T *)np); vim_free(np); return new_bnum; } /* * Set mfp->mf_ffname according to mfp->mf_fname and some other things. * Only called when creating or renaming the swapfile. Either way it's a new * name so we must work out the full path name. */ void mf_set_ffname(mfp) memfile_T *mfp; { mfp->mf_ffname = FullName_save(mfp->mf_fname, FALSE); } /* * Make the name of the file used for the memfile a full path. * Used before doing a :cd */ void mf_fullname(mfp) memfile_T *mfp; { if (mfp != NULL && mfp->mf_fname != NULL && mfp->mf_ffname != NULL) { vim_free(mfp->mf_fname); mfp->mf_fname = mfp->mf_ffname; mfp->mf_ffname = NULL; } } /* * return TRUE if there are any translations pending for 'mfp' */ int mf_need_trans(mfp) memfile_T *mfp; { return (mfp->mf_fname != NULL && mfp->mf_neg_count > 0); } /* * Open a swap file for a memfile. * The "fname" must be in allocated memory, and is consumed (also when an * error occurs). */ static void mf_do_open(mfp, fname, flags) memfile_T *mfp; char_u *fname; int flags; /* flags for open() */ { #ifdef HAVE_LSTAT struct stat sb; #endif mfp->mf_fname = fname; /* * Get the full path name before the open, because this is * not possible after the open on the Amiga. * fname cannot be NameBuff, because it must have been allocated. */ mf_set_ffname(mfp); #if defined(MSDOS) || defined(MSWIN) /* * A ":!cd e:xxx" may change the directory without us knowning, use the * full pathname always. Careful: This frees fname! */ mf_fullname(mfp); #endif #ifdef HAVE_LSTAT /* * Extra security check: When creating a swap file it really shouldn't * exist yet. If there is a symbolic link, this is most likely an attack. */ if ((flags & O_CREAT) && mch_lstat((char *)mfp->mf_fname, &sb) >= 0) { mfp->mf_fd = -1; EMSG(_("E300: Swap file already exists (symlink attack?)")); } else #endif { /* * try to open the file */ flags |= O_EXTRA | O_NOFOLLOW; #ifdef WIN32 /* Prevent handle inheritance that cause problems with Cscope * (swap file may not be deleted if cscope connection was open after * the file) */ flags |= O_NOINHERIT; #endif mfp->mf_fd = mch_open_rw((char *)mfp->mf_fname, flags); } /* * If the file cannot be opened, use memory only */ if (mfp->mf_fd < 0) { vim_free(mfp->mf_fname); vim_free(mfp->mf_ffname); mfp->mf_fname = NULL; mfp->mf_ffname = NULL; } else { #ifdef HAVE_FD_CLOEXEC int fdflags = fcntl(mfp->mf_fd, F_GETFD); if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0) fcntl(mfp->mf_fd, F_SETFD, fdflags | FD_CLOEXEC); #endif #ifdef HAVE_SELINUX mch_copy_sec(fname, mfp->mf_fname); #endif mch_hide(mfp->mf_fname); /* try setting the 'hidden' flag */ } } /* * Implementation of mf_hashtab_T follows. */ /* * The number of buckets in the hashtable is increased by a factor of * MHT_GROWTH_FACTOR when the average number of items per bucket * exceeds 2 ^ MHT_LOG_LOAD_FACTOR. */ #define MHT_LOG_LOAD_FACTOR 6 #define MHT_GROWTH_FACTOR 2 /* must be a power of two */ /* * Initialize an empty hash table. */ static void mf_hash_init(mht) mf_hashtab_T *mht; { vim_memset(mht, 0, sizeof(mf_hashtab_T)); mht->mht_buckets = mht->mht_small_buckets; mht->mht_mask = MHT_INIT_SIZE - 1; } /* * Free the array of a hash table. Does not free the items it contains! * The hash table must not be used again without another mf_hash_init() call. */ static void mf_hash_free(mht) mf_hashtab_T *mht; { if (mht->mht_buckets != mht->mht_small_buckets) vim_free(mht->mht_buckets); } /* * Free the array of a hash table and all the items it contains. */ static void mf_hash_free_all(mht) mf_hashtab_T *mht; { long_u idx; mf_hashitem_T *mhi; mf_hashitem_T *next; for (idx = 0; idx <= mht->mht_mask; idx++) for (mhi = mht->mht_buckets[idx]; mhi != NULL; mhi = next) { next = mhi->mhi_next; vim_free(mhi); } mf_hash_free(mht); } /* * Find "key" in hashtable "mht". * Returns a pointer to a mf_hashitem_T or NULL if the item was not found. */ static mf_hashitem_T * mf_hash_find(mht, key) mf_hashtab_T *mht; blocknr_T key; { mf_hashitem_T *mhi; mhi = mht->mht_buckets[key & mht->mht_mask]; while (mhi != NULL && mhi->mhi_key != key) mhi = mhi->mhi_next; return mhi; } /* * Add item "mhi" to hashtable "mht". * "mhi" must not be NULL. */ static void mf_hash_add_item(mht, mhi) mf_hashtab_T *mht; mf_hashitem_T *mhi; { long_u idx; idx = mhi->mhi_key & mht->mht_mask; mhi->mhi_next = mht->mht_buckets[idx]; mhi->mhi_prev = NULL; if (mhi->mhi_next != NULL) mhi->mhi_next->mhi_prev = mhi; mht->mht_buckets[idx] = mhi; mht->mht_count++; /* * Grow hashtable when we have more thank 2^MHT_LOG_LOAD_FACTOR * items per bucket on average */ if (mht->mht_fixed == 0 && (mht->mht_count >> MHT_LOG_LOAD_FACTOR) > mht->mht_mask) { if (mf_hash_grow(mht) == FAIL) { /* stop trying to grow after first failure to allocate memory */ mht->mht_fixed = 1; } } } /* * Remove item "mhi" from hashtable "mht". * "mhi" must not be NULL and must have been inserted into "mht". */ static void mf_hash_rem_item(mht, mhi) mf_hashtab_T *mht; mf_hashitem_T *mhi; { if (mhi->mhi_prev == NULL) mht->mht_buckets[mhi->mhi_key & mht->mht_mask] = mhi->mhi_next; else mhi->mhi_prev->mhi_next = mhi->mhi_next; if (mhi->mhi_next != NULL) mhi->mhi_next->mhi_prev = mhi->mhi_prev; mht->mht_count--; /* We could shrink the table here, but it typically takes little memory, * so why bother? */ } /* * Increase number of buckets in the hashtable by MHT_GROWTH_FACTOR and * rehash items. * Returns FAIL when out of memory. */ static int mf_hash_grow(mht) mf_hashtab_T *mht; { long_u i, j; int shift; mf_hashitem_T *mhi; mf_hashitem_T *tails[MHT_GROWTH_FACTOR]; mf_hashitem_T **buckets; size_t size; size = (mht->mht_mask + 1) * MHT_GROWTH_FACTOR * sizeof(void *); buckets = (mf_hashitem_T **)lalloc_clear(size, FALSE); if (buckets == NULL) return FAIL; shift = 0; while ((mht->mht_mask >> shift) != 0) shift++; for (i = 0; i <= mht->mht_mask; i++) { /* * Traverse the items in the i-th original bucket and move them into * MHT_GROWTH_FACTOR new buckets, preserving their relative order * within each new bucket. Preserving the order is important because * mf_get() tries to keep most recently used items at the front of * each bucket. * * Here we strongly rely on the fact the hashes are computed modulo * a power of two. */ vim_memset(tails, 0, sizeof(tails)); for (mhi = mht->mht_buckets[i]; mhi != NULL; mhi = mhi->mhi_next) { j = (mhi->mhi_key >> shift) & (MHT_GROWTH_FACTOR - 1); if (tails[j] == NULL) { buckets[i + (j << shift)] = mhi; tails[j] = mhi; mhi->mhi_prev = NULL; } else { tails[j]->mhi_next = mhi; mhi->mhi_prev = tails[j]; tails[j] = mhi; } } for (j = 0; j < MHT_GROWTH_FACTOR; j++) if (tails[j] != NULL) tails[j]->mhi_next = NULL; } if (mht->mht_buckets != mht->mht_small_buckets) vim_free(mht->mht_buckets); mht->mht_buckets = buckets; mht->mht_mask = (mht->mht_mask + 1) * MHT_GROWTH_FACTOR - 1; return OK; }
zyz2011-vim
src/memfile.c
C
gpl2
39,516
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. */ /* * proto.h: include the (automatically generated) function prototypes */ /* * Don't include these while generating prototypes. Prevents problems when * files are missing. */ #if !defined(PROTO) && !defined(NOPROTO) /* * Machine-dependent routines. */ /* avoid errors in function prototypes */ # if !defined(FEAT_X11) && !defined(FEAT_GUI_GTK) # define Display int # define Widget int # endif # ifndef FEAT_GUI_GTK # define GdkEvent int # define GdkEventKey int # endif # ifndef FEAT_X11 # define XImage int # endif # ifdef AMIGA # include "os_amiga.pro" # endif # if defined(UNIX) || defined(__EMX__) || defined(VMS) # include "os_unix.pro" # endif # if defined(MSDOS) || defined(WIN16) # include "os_msdos.pro" # endif # ifdef WIN16 typedef LPSTR LPWSTR; typedef LPCSTR LPCWSTR; typedef int LPBOOL; # include "os_win16.pro" # include "os_mswin.pro" # endif # ifdef WIN3264 # include "os_win32.pro" # include "os_mswin.pro" # if (defined(__GNUC__) && !defined(__MINGW32__)) \ || (defined(__BORLANDC__) && __BORLANDC__ < 0x502) extern int _stricoll __ARGS((char *a, char *b)); # endif # endif # ifdef VMS # include "os_vms.pro" # endif # ifdef __BEOS__ # include "os_beos.pro" # endif # ifdef __QNX__ # include "os_qnx.pro" # endif # ifdef FEAT_CRYPT # include "blowfish.pro" # endif # include "buffer.pro" # include "charset.pro" # ifdef FEAT_CSCOPE # include "if_cscope.pro" # endif # include "diff.pro" # include "digraph.pro" # include "edit.pro" # include "eval.pro" # include "ex_cmds.pro" # include "ex_cmds2.pro" # include "ex_docmd.pro" # include "ex_eval.pro" # include "ex_getln.pro" # include "fileio.pro" # include "fold.pro" # include "getchar.pro" # ifdef FEAT_HANGULIN # include "hangulin.pro" # endif # include "hardcopy.pro" # include "hashtab.pro" # include "main.pro" # include "mark.pro" # include "memfile.pro" # include "memline.pro" # ifdef FEAT_MENU # include "menu.pro" # endif # if !defined MESSAGE_FILE || defined(HAVE_STDARG_H) /* These prototypes cannot be produced automatically and conflict with * the old-style prototypes in message.c. */ int # ifdef __BORLANDC__ _RTLENTRYF # endif smsg __ARGS((char_u *, ...)); int # ifdef __BORLANDC__ _RTLENTRYF # endif smsg_attr __ARGS((int, char_u *, ...)); int # ifdef __BORLANDC__ _RTLENTRYF # endif vim_snprintf_add __ARGS((char *, size_t, char *, ...)); int # ifdef __BORLANDC__ _RTLENTRYF # endif vim_snprintf __ARGS((char *, size_t, char *, ...)); # if defined(HAVE_STDARG_H) int vim_vsnprintf(char *str, size_t str_m, char *fmt, va_list ap, typval_T *tvs); # endif # endif # include "message.pro" # include "misc1.pro" # include "misc2.pro" #ifndef HAVE_STRPBRK /* not generated automatically from misc2.c */ char_u *vim_strpbrk __ARGS((char_u *s, char_u *charset)); #endif #ifndef HAVE_QSORT /* Use our own qsort(), don't define the prototype when not used. */ void qsort __ARGS((void *base, size_t elm_count, size_t elm_size, int (*cmp)(const void *, const void *))); #endif # include "move.pro" # if defined(FEAT_MBYTE) || defined(FEAT_XIM) || defined(FEAT_KEYMAP) \ || defined(FEAT_POSTSCRIPT) # include "mbyte.pro" # endif # include "normal.pro" # include "ops.pro" # include "option.pro" # include "popupmnu.pro" # ifdef FEAT_QUICKFIX # include "quickfix.pro" # endif # include "regexp.pro" # include "screen.pro" # if defined(FEAT_CRYPT) || defined(FEAT_PERSISTENT_UNDO) # include "sha256.pro" # endif # include "search.pro" # include "spell.pro" # include "syntax.pro" # include "tag.pro" # include "term.pro" # if defined(HAVE_TGETENT) && (defined(AMIGA) || defined(VMS)) # include "termlib.pro" # endif # include "ui.pro" # include "undo.pro" # include "version.pro" # include "window.pro" # ifdef FEAT_LUA # include "if_lua.pro" # endif # ifdef FEAT_MZSCHEME # include "if_mzsch.pro" # endif # ifdef FEAT_PYTHON # include "if_python.pro" # endif # ifdef FEAT_PYTHON3 # include "if_python3.pro" # endif # ifdef FEAT_TCL # include "if_tcl.pro" # endif # ifdef FEAT_RUBY # include "if_ruby.pro" # endif /* Ugly solution for "BalloonEval" not being defined while it's used in some * .pro files. */ # ifndef FEAT_BEVAL # define BalloonEval int # endif # ifdef FEAT_NETBEANS_INTG # include "netbeans.pro" # endif # ifdef FEAT_GUI # include "gui.pro" # if defined(UNIX) || defined(MACOS) # include "pty.pro" # endif # if !defined(HAVE_SETENV) && !defined(HAVE_PUTENV) && !defined(VMS) extern int putenv __ARGS((const char *string)); /* from pty.c */ # ifdef USE_VIMPTY_GETENV extern char_u *vimpty_getenv __ARGS((const char_u *string)); /* from pty.c */ # endif # endif # ifdef FEAT_GUI_W16 # include "gui_w16.pro" # endif # ifdef FEAT_GUI_W32 # include "gui_w32.pro" # endif # ifdef FEAT_GUI_GTK # include "gui_gtk.pro" # include "gui_gtk_x11.pro" # endif # ifdef FEAT_GUI_MOTIF # include "gui_motif.pro" # include "gui_xmdlg.pro" # endif # ifdef FEAT_GUI_ATHENA # include "gui_athena.pro" # ifdef FEAT_BROWSE extern char *vim_SelFile __ARGS((Widget toplevel, char *prompt, char *init_path, int (*show_entry)(), int x, int y, guicolor_T fg, guicolor_T bg, guicolor_T scroll_fg, guicolor_T scroll_bg)); # endif # endif # ifdef FEAT_GUI_MAC # include "gui_mac.pro" # endif # ifdef FEAT_GUI_X11 # include "gui_x11.pro" # endif # ifdef FEAT_GUI_PHOTON # include "gui_photon.pro" # endif # ifdef FEAT_SUN_WORKSHOP # include "workshop.pro" # endif # endif /* FEAT_GUI */ # ifdef FEAT_OLE # include "if_ole.pro" # endif # if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11) # include "if_xcmdsrv.pro" # endif /* * The perl include files pollute the namespace, therefore proto.h must be * included before the perl include files. But then CV is not defined, which * is used in if_perl.pro. To get around this, the perl prototype files are * not included here for the perl files. Use a dummy define for CV for the * other files. */ #if defined(FEAT_PERL) && !defined(IN_PERL_FILE) # define CV void # ifdef __BORLANDC__ #pragma option -pc # endif # include "if_perl.pro" # ifdef __BORLANDC__ #pragma option -p. # endif # include "if_perlsfio.pro" #endif #ifdef MACOS_CONVERT # include "os_mac_conv.pro" #endif #if defined(MACOS_X_UNIX) && defined(FEAT_CLIPBOARD) && !defined(FEAT_GUI) /* functions in os_macosx.m */ void clip_mch_lose_selection(VimClipboard *cbd); int clip_mch_own_selection(VimClipboard *cbd); void clip_mch_request_selection(VimClipboard *cbd); void clip_mch_set_selection(VimClipboard *cbd); #endif #ifdef __BORLANDC__ # define _PROTO_H #endif #endif /* !PROTO && !NOPROTO */
zyz2011-vim
src/proto.h
C
gpl2
6,853
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * ex_cmds2.c: some more functions for command line commands */ #include "vim.h" #include "version.h" static void cmd_source __ARGS((char_u *fname, exarg_T *eap)); #ifdef FEAT_EVAL /* Growarray to store info about already sourced scripts. * For Unix also store the dev/ino, so that we don't have to stat() each * script when going through the list. */ typedef struct scriptitem_S { char_u *sn_name; # ifdef UNIX int sn_dev_valid; dev_t sn_dev; ino_t sn_ino; # endif # ifdef FEAT_PROFILE int sn_prof_on; /* TRUE when script is/was profiled */ int sn_pr_force; /* forceit: profile functions in this script */ proftime_T sn_pr_child; /* time set when going into first child */ int sn_pr_nest; /* nesting for sn_pr_child */ /* profiling the script as a whole */ int sn_pr_count; /* nr of times sourced */ proftime_T sn_pr_total; /* time spent in script + children */ proftime_T sn_pr_self; /* time spent in script itself */ proftime_T sn_pr_start; /* time at script start */ proftime_T sn_pr_children; /* time in children after script start */ /* profiling the script per line */ garray_T sn_prl_ga; /* things stored for every line */ proftime_T sn_prl_start; /* start time for current line */ proftime_T sn_prl_children; /* time spent in children for this line */ proftime_T sn_prl_wait; /* wait start time for current line */ int sn_prl_idx; /* index of line being timed; -1 if none */ int sn_prl_execed; /* line being timed was executed */ # endif } scriptitem_T; static garray_T script_items = {0, 0, sizeof(scriptitem_T), 4, NULL}; #define SCRIPT_ITEM(id) (((scriptitem_T *)script_items.ga_data)[(id) - 1]) # ifdef FEAT_PROFILE /* Struct used in sn_prl_ga for every line of a script. */ typedef struct sn_prl_S { int snp_count; /* nr of times line was executed */ proftime_T sn_prl_total; /* time spent in a line + children */ proftime_T sn_prl_self; /* time spent in a line itself */ } sn_prl_T; # define PRL_ITEM(si, idx) (((sn_prl_T *)(si)->sn_prl_ga.ga_data)[(idx)]) # endif #endif #if defined(FEAT_EVAL) || defined(PROTO) static int debug_greedy = FALSE; /* batch mode debugging: don't save and restore typeahead. */ /* * do_debug(): Debug mode. * Repeatedly get Ex commands, until told to continue normal execution. */ void do_debug(cmd) char_u *cmd; { int save_msg_scroll = msg_scroll; int save_State = State; int save_did_emsg = did_emsg; int save_cmd_silent = cmd_silent; int save_msg_silent = msg_silent; int save_emsg_silent = emsg_silent; int save_redir_off = redir_off; tasave_T typeaheadbuf; int typeahead_saved = FALSE; int save_ignore_script = 0; # ifdef FEAT_EX_EXTRA int save_ex_normal_busy; # endif int n; char_u *cmdline = NULL; char_u *p; char *tail = NULL; static int last_cmd = 0; #define CMD_CONT 1 #define CMD_NEXT 2 #define CMD_STEP 3 #define CMD_FINISH 4 #define CMD_QUIT 5 #define CMD_INTERRUPT 6 #ifdef ALWAYS_USE_GUI /* Can't do this when there is no terminal for input/output. */ if (!gui.in_use) { /* Break as soon as possible. */ debug_break_level = 9999; return; } #endif /* Make sure we are in raw mode and start termcap mode. Might have side * effects... */ settmode(TMODE_RAW); starttermcap(); ++RedrawingDisabled; /* don't redisplay the window */ ++no_wait_return; /* don't wait for return */ did_emsg = FALSE; /* don't use error from debugged stuff */ cmd_silent = FALSE; /* display commands */ msg_silent = FALSE; /* display messages */ emsg_silent = FALSE; /* display error messages */ redir_off = TRUE; /* don't redirect debug commands */ State = NORMAL; #ifdef FEAT_SNIFF want_sniff_request = 0; /* No K_SNIFF wanted */ #endif if (!debug_did_msg) MSG(_("Entering Debug mode. Type \"cont\" to continue.")); if (sourcing_name != NULL) msg(sourcing_name); if (sourcing_lnum != 0) smsg((char_u *)_("line %ld: %s"), (long)sourcing_lnum, cmd); else smsg((char_u *)_("cmd: %s"), cmd); /* * Repeat getting a command and executing it. */ for (;;) { msg_scroll = TRUE; need_wait_return = FALSE; #ifdef FEAT_SNIFF ProcessSniffRequests(); #endif /* Save the current typeahead buffer and replace it with an empty one. * This makes sure we get input from the user here and don't interfere * with the commands being executed. Reset "ex_normal_busy" to avoid * the side effects of using ":normal". Save the stuff buffer and make * it empty. Set ignore_script to avoid reading from script input. */ # ifdef FEAT_EX_EXTRA save_ex_normal_busy = ex_normal_busy; ex_normal_busy = 0; # endif if (!debug_greedy) { save_typeahead(&typeaheadbuf); typeahead_saved = TRUE; save_ignore_script = ignore_script; ignore_script = TRUE; } cmdline = getcmdline_prompt('>', NULL, 0, EXPAND_NOTHING, NULL); if (typeahead_saved) { restore_typeahead(&typeaheadbuf); ignore_script = save_ignore_script; } # ifdef FEAT_EX_EXTRA ex_normal_busy = save_ex_normal_busy; # endif cmdline_row = msg_row; if (cmdline != NULL) { /* If this is a debug command, set "last_cmd". * If not, reset "last_cmd". * For a blank line use previous command. */ p = skipwhite(cmdline); if (*p != NUL) { switch (*p) { case 'c': last_cmd = CMD_CONT; tail = "ont"; break; case 'n': last_cmd = CMD_NEXT; tail = "ext"; break; case 's': last_cmd = CMD_STEP; tail = "tep"; break; case 'f': last_cmd = CMD_FINISH; tail = "inish"; break; case 'q': last_cmd = CMD_QUIT; tail = "uit"; break; case 'i': last_cmd = CMD_INTERRUPT; tail = "nterrupt"; break; default: last_cmd = 0; } if (last_cmd != 0) { /* Check that the tail matches. */ ++p; while (*p != NUL && *p == *tail) { ++p; ++tail; } if (ASCII_ISALPHA(*p)) last_cmd = 0; } } if (last_cmd != 0) { /* Execute debug command: decided where to break next and * return. */ switch (last_cmd) { case CMD_CONT: debug_break_level = -1; break; case CMD_NEXT: debug_break_level = ex_nesting_level; break; case CMD_STEP: debug_break_level = 9999; break; case CMD_FINISH: debug_break_level = ex_nesting_level - 1; break; case CMD_QUIT: got_int = TRUE; debug_break_level = -1; break; case CMD_INTERRUPT: got_int = TRUE; debug_break_level = 9999; /* Do not repeat ">interrupt" cmd, continue stepping. */ last_cmd = CMD_STEP; break; } break; } /* don't debug this command */ n = debug_break_level; debug_break_level = -1; (void)do_cmdline(cmdline, getexline, NULL, DOCMD_VERBOSE|DOCMD_EXCRESET); debug_break_level = n; vim_free(cmdline); } lines_left = Rows - 1; } vim_free(cmdline); --RedrawingDisabled; --no_wait_return; redraw_all_later(NOT_VALID); need_wait_return = FALSE; msg_scroll = save_msg_scroll; lines_left = Rows - 1; State = save_State; did_emsg = save_did_emsg; cmd_silent = save_cmd_silent; msg_silent = save_msg_silent; emsg_silent = save_emsg_silent; redir_off = save_redir_off; /* Only print the message again when typing a command before coming back * here. */ debug_did_msg = TRUE; } /* * ":debug". */ void ex_debug(eap) exarg_T *eap; { int debug_break_level_save = debug_break_level; debug_break_level = 9999; do_cmdline_cmd(eap->arg); debug_break_level = debug_break_level_save; } static char_u *debug_breakpoint_name = NULL; static linenr_T debug_breakpoint_lnum; /* * When debugging or a breakpoint is set on a skipped command, no debug prompt * is shown by do_one_cmd(). This situation is indicated by debug_skipped, and * debug_skipped_name is then set to the source name in the breakpoint case. If * a skipped command decides itself that a debug prompt should be displayed, it * can do so by calling dbg_check_skipped(). */ static int debug_skipped; static char_u *debug_skipped_name; /* * Go to debug mode when a breakpoint was encountered or "ex_nesting_level" is * at or below the break level. But only when the line is actually * executed. Return TRUE and set breakpoint_name for skipped commands that * decide to execute something themselves. * Called from do_one_cmd() before executing a command. */ void dbg_check_breakpoint(eap) exarg_T *eap; { char_u *p; debug_skipped = FALSE; if (debug_breakpoint_name != NULL) { if (!eap->skip) { /* replace K_SNR with "<SNR>" */ if (debug_breakpoint_name[0] == K_SPECIAL && debug_breakpoint_name[1] == KS_EXTRA && debug_breakpoint_name[2] == (int)KE_SNR) p = (char_u *)"<SNR>"; else p = (char_u *)""; smsg((char_u *)_("Breakpoint in \"%s%s\" line %ld"), p, debug_breakpoint_name + (*p == NUL ? 0 : 3), (long)debug_breakpoint_lnum); debug_breakpoint_name = NULL; do_debug(eap->cmd); } else { debug_skipped = TRUE; debug_skipped_name = debug_breakpoint_name; debug_breakpoint_name = NULL; } } else if (ex_nesting_level <= debug_break_level) { if (!eap->skip) do_debug(eap->cmd); else { debug_skipped = TRUE; debug_skipped_name = NULL; } } } /* * Go to debug mode if skipped by dbg_check_breakpoint() because eap->skip was * set. Return TRUE when the debug mode is entered this time. */ int dbg_check_skipped(eap) exarg_T *eap; { int prev_got_int; if (debug_skipped) { /* * Save the value of got_int and reset it. We don't want a previous * interruption cause flushing the input buffer. */ prev_got_int = got_int; got_int = FALSE; debug_breakpoint_name = debug_skipped_name; /* eap->skip is TRUE */ eap->skip = FALSE; (void)dbg_check_breakpoint(eap); eap->skip = TRUE; got_int |= prev_got_int; return TRUE; } return FALSE; } /* * The list of breakpoints: dbg_breakp. * This is a grow-array of structs. */ struct debuggy { int dbg_nr; /* breakpoint number */ int dbg_type; /* DBG_FUNC or DBG_FILE */ char_u *dbg_name; /* function or file name */ regprog_T *dbg_prog; /* regexp program */ linenr_T dbg_lnum; /* line number in function or file */ int dbg_forceit; /* ! used */ }; static garray_T dbg_breakp = {0, 0, sizeof(struct debuggy), 4, NULL}; #define BREAKP(idx) (((struct debuggy *)dbg_breakp.ga_data)[idx]) #define DEBUGGY(gap, idx) (((struct debuggy *)gap->ga_data)[idx]) static int last_breakp = 0; /* nr of last defined breakpoint */ #ifdef FEAT_PROFILE /* Profiling uses file and func names similar to breakpoints. */ static garray_T prof_ga = {0, 0, sizeof(struct debuggy), 4, NULL}; #endif #define DBG_FUNC 1 #define DBG_FILE 2 static int dbg_parsearg __ARGS((char_u *arg, garray_T *gap)); static linenr_T debuggy_find __ARGS((int file,char_u *fname, linenr_T after, garray_T *gap, int *fp)); /* * Parse the arguments of ":profile", ":breakadd" or ":breakdel" and put them * in the entry just after the last one in dbg_breakp. Note that "dbg_name" * is allocated. * Returns FAIL for failure. */ static int dbg_parsearg(arg, gap) char_u *arg; garray_T *gap; /* either &dbg_breakp or &prof_ga */ { char_u *p = arg; char_u *q; struct debuggy *bp; int here = FALSE; if (ga_grow(gap, 1) == FAIL) return FAIL; bp = &DEBUGGY(gap, gap->ga_len); /* Find "func" or "file". */ if (STRNCMP(p, "func", 4) == 0) bp->dbg_type = DBG_FUNC; else if (STRNCMP(p, "file", 4) == 0) bp->dbg_type = DBG_FILE; else if ( #ifdef FEAT_PROFILE gap != &prof_ga && #endif STRNCMP(p, "here", 4) == 0) { if (curbuf->b_ffname == NULL) { EMSG(_(e_noname)); return FAIL; } bp->dbg_type = DBG_FILE; here = TRUE; } else { EMSG2(_(e_invarg2), p); return FAIL; } p = skipwhite(p + 4); /* Find optional line number. */ if (here) bp->dbg_lnum = curwin->w_cursor.lnum; else if ( #ifdef FEAT_PROFILE gap != &prof_ga && #endif VIM_ISDIGIT(*p)) { bp->dbg_lnum = getdigits(&p); p = skipwhite(p); } else bp->dbg_lnum = 0; /* Find the function or file name. Don't accept a function name with (). */ if ((!here && *p == NUL) || (here && *p != NUL) || (bp->dbg_type == DBG_FUNC && strstr((char *)p, "()") != NULL)) { EMSG2(_(e_invarg2), arg); return FAIL; } if (bp->dbg_type == DBG_FUNC) bp->dbg_name = vim_strsave(p); else if (here) bp->dbg_name = vim_strsave(curbuf->b_ffname); else { /* Expand the file name in the same way as do_source(). This means * doing it twice, so that $DIR/file gets expanded when $DIR is * "~/dir". */ q = expand_env_save(p); if (q == NULL) return FAIL; p = expand_env_save(q); vim_free(q); if (p == NULL) return FAIL; if (*p != '*') { bp->dbg_name = fix_fname(p); vim_free(p); } else bp->dbg_name = p; } if (bp->dbg_name == NULL) return FAIL; return OK; } /* * ":breakadd". */ void ex_breakadd(eap) exarg_T *eap; { struct debuggy *bp; char_u *pat; garray_T *gap; gap = &dbg_breakp; #ifdef FEAT_PROFILE if (eap->cmdidx == CMD_profile) gap = &prof_ga; #endif if (dbg_parsearg(eap->arg, gap) == OK) { bp = &DEBUGGY(gap, gap->ga_len); bp->dbg_forceit = eap->forceit; pat = file_pat_to_reg_pat(bp->dbg_name, NULL, NULL, FALSE); if (pat != NULL) { bp->dbg_prog = vim_regcomp(pat, RE_MAGIC + RE_STRING); vim_free(pat); } if (pat == NULL || bp->dbg_prog == NULL) vim_free(bp->dbg_name); else { if (bp->dbg_lnum == 0) /* default line number is 1 */ bp->dbg_lnum = 1; #ifdef FEAT_PROFILE if (eap->cmdidx != CMD_profile) #endif { DEBUGGY(gap, gap->ga_len).dbg_nr = ++last_breakp; ++debug_tick; } ++gap->ga_len; } } } /* * ":debuggreedy". */ void ex_debuggreedy(eap) exarg_T *eap; { if (eap->addr_count == 0 || eap->line2 != 0) debug_greedy = TRUE; else debug_greedy = FALSE; } /* * ":breakdel" and ":profdel". */ void ex_breakdel(eap) exarg_T *eap; { struct debuggy *bp, *bpi; int nr; int todel = -1; int del_all = FALSE; int i; linenr_T best_lnum = 0; garray_T *gap; gap = &dbg_breakp; if (eap->cmdidx == CMD_profdel) { #ifdef FEAT_PROFILE gap = &prof_ga; #else ex_ni(eap); return; #endif } if (vim_isdigit(*eap->arg)) { /* ":breakdel {nr}" */ nr = atol((char *)eap->arg); for (i = 0; i < gap->ga_len; ++i) if (DEBUGGY(gap, i).dbg_nr == nr) { todel = i; break; } } else if (*eap->arg == '*') { todel = 0; del_all = TRUE; } else { /* ":breakdel {func|file} [lnum] {name}" */ if (dbg_parsearg(eap->arg, gap) == FAIL) return; bp = &DEBUGGY(gap, gap->ga_len); for (i = 0; i < gap->ga_len; ++i) { bpi = &DEBUGGY(gap, i); if (bp->dbg_type == bpi->dbg_type && STRCMP(bp->dbg_name, bpi->dbg_name) == 0 && (bp->dbg_lnum == bpi->dbg_lnum || (bp->dbg_lnum == 0 && (best_lnum == 0 || bpi->dbg_lnum < best_lnum)))) { todel = i; best_lnum = bpi->dbg_lnum; } } vim_free(bp->dbg_name); } if (todel < 0) EMSG2(_("E161: Breakpoint not found: %s"), eap->arg); else { while (gap->ga_len > 0) { vim_free(DEBUGGY(gap, todel).dbg_name); vim_free(DEBUGGY(gap, todel).dbg_prog); --gap->ga_len; if (todel < gap->ga_len) mch_memmove(&DEBUGGY(gap, todel), &DEBUGGY(gap, todel + 1), (gap->ga_len - todel) * sizeof(struct debuggy)); #ifdef FEAT_PROFILE if (eap->cmdidx == CMD_breakdel) #endif ++debug_tick; if (!del_all) break; } /* If all breakpoints were removed clear the array. */ if (gap->ga_len == 0) ga_clear(gap); } } /* * ":breaklist". */ void ex_breaklist(eap) exarg_T *eap UNUSED; { struct debuggy *bp; int i; if (dbg_breakp.ga_len == 0) MSG(_("No breakpoints defined")); else for (i = 0; i < dbg_breakp.ga_len; ++i) { bp = &BREAKP(i); if (bp->dbg_type == DBG_FILE) home_replace(NULL, bp->dbg_name, NameBuff, MAXPATHL, TRUE); smsg((char_u *)_("%3d %s %s line %ld"), bp->dbg_nr, bp->dbg_type == DBG_FUNC ? "func" : "file", bp->dbg_type == DBG_FUNC ? bp->dbg_name : NameBuff, (long)bp->dbg_lnum); } } /* * Find a breakpoint for a function or sourced file. * Returns line number at which to break; zero when no matching breakpoint. */ linenr_T dbg_find_breakpoint(file, fname, after) int file; /* TRUE for a file, FALSE for a function */ char_u *fname; /* file or function name */ linenr_T after; /* after this line number */ { return debuggy_find(file, fname, after, &dbg_breakp, NULL); } #if defined(FEAT_PROFILE) || defined(PROTO) /* * Return TRUE if profiling is on for a function or sourced file. */ int has_profiling(file, fname, fp) int file; /* TRUE for a file, FALSE for a function */ char_u *fname; /* file or function name */ int *fp; /* return: forceit */ { return (debuggy_find(file, fname, (linenr_T)0, &prof_ga, fp) != (linenr_T)0); } #endif /* * Common code for dbg_find_breakpoint() and has_profiling(). */ static linenr_T debuggy_find(file, fname, after, gap, fp) int file; /* TRUE for a file, FALSE for a function */ char_u *fname; /* file or function name */ linenr_T after; /* after this line number */ garray_T *gap; /* either &dbg_breakp or &prof_ga */ int *fp; /* if not NULL: return forceit */ { struct debuggy *bp; int i; linenr_T lnum = 0; regmatch_T regmatch; char_u *name = fname; int prev_got_int; /* Return quickly when there are no breakpoints. */ if (gap->ga_len == 0) return (linenr_T)0; /* Replace K_SNR in function name with "<SNR>". */ if (!file && fname[0] == K_SPECIAL) { name = alloc((unsigned)STRLEN(fname) + 3); if (name == NULL) name = fname; else { STRCPY(name, "<SNR>"); STRCPY(name + 5, fname + 3); } } for (i = 0; i < gap->ga_len; ++i) { /* Skip entries that are not useful or are for a line that is beyond * an already found breakpoint. */ bp = &DEBUGGY(gap, i); if (((bp->dbg_type == DBG_FILE) == file && ( #ifdef FEAT_PROFILE gap == &prof_ga || #endif (bp->dbg_lnum > after && (lnum == 0 || bp->dbg_lnum < lnum))))) { regmatch.regprog = bp->dbg_prog; regmatch.rm_ic = FALSE; /* * Save the value of got_int and reset it. We don't want a * previous interruption cancel matching, only hitting CTRL-C * while matching should abort it. */ prev_got_int = got_int; got_int = FALSE; if (vim_regexec(&regmatch, name, (colnr_T)0)) { lnum = bp->dbg_lnum; if (fp != NULL) *fp = bp->dbg_forceit; } got_int |= prev_got_int; } } if (name != fname) vim_free(name); return lnum; } /* * Called when a breakpoint was encountered. */ void dbg_breakpoint(name, lnum) char_u *name; linenr_T lnum; { /* We need to check if this line is actually executed in do_one_cmd() */ debug_breakpoint_name = name; debug_breakpoint_lnum = lnum; } # if defined(FEAT_PROFILE) || defined(FEAT_RELTIME) || defined(PROTO) /* * Store the current time in "tm". */ void profile_start(tm) proftime_T *tm; { # ifdef WIN3264 QueryPerformanceCounter(tm); # else gettimeofday(tm, NULL); # endif } /* * Compute the elapsed time from "tm" till now and store in "tm". */ void profile_end(tm) proftime_T *tm; { proftime_T now; # ifdef WIN3264 QueryPerformanceCounter(&now); tm->QuadPart = now.QuadPart - tm->QuadPart; # else gettimeofday(&now, NULL); tm->tv_usec = now.tv_usec - tm->tv_usec; tm->tv_sec = now.tv_sec - tm->tv_sec; if (tm->tv_usec < 0) { tm->tv_usec += 1000000; --tm->tv_sec; } # endif } /* * Subtract the time "tm2" from "tm". */ void profile_sub(tm, tm2) proftime_T *tm, *tm2; { # ifdef WIN3264 tm->QuadPart -= tm2->QuadPart; # else tm->tv_usec -= tm2->tv_usec; tm->tv_sec -= tm2->tv_sec; if (tm->tv_usec < 0) { tm->tv_usec += 1000000; --tm->tv_sec; } # endif } /* * Return a string that represents the time in "tm". * Uses a static buffer! */ char * profile_msg(tm) proftime_T *tm; { static char buf[50]; # ifdef WIN3264 LARGE_INTEGER fr; QueryPerformanceFrequency(&fr); sprintf(buf, "%10.6lf", (double)tm->QuadPart / (double)fr.QuadPart); # else sprintf(buf, "%3ld.%06ld", (long)tm->tv_sec, (long)tm->tv_usec); # endif return buf; } /* * Put the time "msec" past now in "tm". */ void profile_setlimit(msec, tm) long msec; proftime_T *tm; { if (msec <= 0) /* no limit */ profile_zero(tm); else { # ifdef WIN3264 LARGE_INTEGER fr; QueryPerformanceCounter(tm); QueryPerformanceFrequency(&fr); tm->QuadPart += (LONGLONG)((double)msec / 1000.0 * (double)fr.QuadPart); # else long usec; gettimeofday(tm, NULL); usec = (long)tm->tv_usec + (long)msec * 1000; tm->tv_usec = usec % 1000000L; tm->tv_sec += usec / 1000000L; # endif } } /* * Return TRUE if the current time is past "tm". */ int profile_passed_limit(tm) proftime_T *tm; { proftime_T now; # ifdef WIN3264 if (tm->QuadPart == 0) /* timer was not set */ return FALSE; QueryPerformanceCounter(&now); return (now.QuadPart > tm->QuadPart); # else if (tm->tv_sec == 0) /* timer was not set */ return FALSE; gettimeofday(&now, NULL); return (now.tv_sec > tm->tv_sec || (now.tv_sec == tm->tv_sec && now.tv_usec > tm->tv_usec)); # endif } /* * Set the time in "tm" to zero. */ void profile_zero(tm) proftime_T *tm; { # ifdef WIN3264 tm->QuadPart = 0; # else tm->tv_usec = 0; tm->tv_sec = 0; # endif } # endif /* FEAT_PROFILE || FEAT_RELTIME */ # if defined(FEAT_PROFILE) || defined(PROTO) /* * Functions for profiling. */ static void script_do_profile __ARGS((scriptitem_T *si)); static void script_dump_profile __ARGS((FILE *fd)); static proftime_T prof_wait_time; /* * Add the time "tm2" to "tm". */ void profile_add(tm, tm2) proftime_T *tm, *tm2; { # ifdef WIN3264 tm->QuadPart += tm2->QuadPart; # else tm->tv_usec += tm2->tv_usec; tm->tv_sec += tm2->tv_sec; if (tm->tv_usec >= 1000000) { tm->tv_usec -= 1000000; ++tm->tv_sec; } # endif } /* * Add the "self" time from the total time and the children's time. */ void profile_self(self, total, children) proftime_T *self, *total, *children; { /* Check that the result won't be negative. Can happen with recursive * calls. */ #ifdef WIN3264 if (total->QuadPart <= children->QuadPart) return; #else if (total->tv_sec < children->tv_sec || (total->tv_sec == children->tv_sec && total->tv_usec <= children->tv_usec)) return; #endif profile_add(self, total); profile_sub(self, children); } /* * Get the current waittime. */ void profile_get_wait(tm) proftime_T *tm; { *tm = prof_wait_time; } /* * Subtract the passed waittime since "tm" from "tma". */ void profile_sub_wait(tm, tma) proftime_T *tm, *tma; { proftime_T tm3 = prof_wait_time; profile_sub(&tm3, tm); profile_sub(tma, &tm3); } /* * Return TRUE if "tm1" and "tm2" are equal. */ int profile_equal(tm1, tm2) proftime_T *tm1, *tm2; { # ifdef WIN3264 return (tm1->QuadPart == tm2->QuadPart); # else return (tm1->tv_usec == tm2->tv_usec && tm1->tv_sec == tm2->tv_sec); # endif } /* * Return <0, 0 or >0 if "tm1" < "tm2", "tm1" == "tm2" or "tm1" > "tm2" */ int profile_cmp(tm1, tm2) proftime_T *tm1, *tm2; { # ifdef WIN3264 return (int)(tm2->QuadPart - tm1->QuadPart); # else if (tm1->tv_sec == tm2->tv_sec) return tm2->tv_usec - tm1->tv_usec; return tm2->tv_sec - tm1->tv_sec; # endif } static char_u *profile_fname = NULL; static proftime_T pause_time; /* * ":profile cmd args" */ void ex_profile(eap) exarg_T *eap; { char_u *e; int len; e = skiptowhite(eap->arg); len = (int)(e - eap->arg); e = skipwhite(e); if (len == 5 && STRNCMP(eap->arg, "start", 5) == 0 && *e != NUL) { vim_free(profile_fname); profile_fname = vim_strsave(e); do_profiling = PROF_YES; profile_zero(&prof_wait_time); set_vim_var_nr(VV_PROFILING, 1L); } else if (do_profiling == PROF_NONE) EMSG(_("E750: First use \":profile start {fname}\"")); else if (STRCMP(eap->arg, "pause") == 0) { if (do_profiling == PROF_YES) profile_start(&pause_time); do_profiling = PROF_PAUSED; } else if (STRCMP(eap->arg, "continue") == 0) { if (do_profiling == PROF_PAUSED) { profile_end(&pause_time); profile_add(&prof_wait_time, &pause_time); } do_profiling = PROF_YES; } else { /* The rest is similar to ":breakadd". */ ex_breakadd(eap); } } /* Command line expansion for :profile. */ static enum { PEXP_SUBCMD, /* expand :profile sub-commands */ PEXP_FUNC /* expand :profile func {funcname} */ } pexpand_what; static char *pexpand_cmds[] = { "start", #define PROFCMD_START 0 "pause", #define PROFCMD_PAUSE 1 "continue", #define PROFCMD_CONTINUE 2 "func", #define PROFCMD_FUNC 3 "file", #define PROFCMD_FILE 4 NULL #define PROFCMD_LAST 5 }; /* * Function given to ExpandGeneric() to obtain the profile command * specific expansion. */ char_u * get_profile_name(xp, idx) expand_T *xp UNUSED; int idx; { switch (pexpand_what) { case PEXP_SUBCMD: return (char_u *)pexpand_cmds[idx]; /* case PEXP_FUNC: TODO */ default: return NULL; } } /* * Handle command line completion for :profile command. */ void set_context_in_profile_cmd(xp, arg) expand_T *xp; char_u *arg; { char_u *end_subcmd; /* Default: expand subcommands. */ xp->xp_context = EXPAND_PROFILE; pexpand_what = PEXP_SUBCMD; xp->xp_pattern = arg; end_subcmd = skiptowhite(arg); if (*end_subcmd == NUL) return; if (end_subcmd - arg == 5 && STRNCMP(arg, "start", 5) == 0) { xp->xp_context = EXPAND_FILES; xp->xp_pattern = skipwhite(end_subcmd); return; } /* TODO: expand function names after "func" */ xp->xp_context = EXPAND_NOTHING; } /* * Dump the profiling info. */ void profile_dump() { FILE *fd; if (profile_fname != NULL) { fd = mch_fopen((char *)profile_fname, "w"); if (fd == NULL) EMSG2(_(e_notopen), profile_fname); else { script_dump_profile(fd); func_dump_profile(fd); fclose(fd); } } } /* * Start profiling script "fp". */ static void script_do_profile(si) scriptitem_T *si; { si->sn_pr_count = 0; profile_zero(&si->sn_pr_total); profile_zero(&si->sn_pr_self); ga_init2(&si->sn_prl_ga, sizeof(sn_prl_T), 100); si->sn_prl_idx = -1; si->sn_prof_on = TRUE; si->sn_pr_nest = 0; } /* * save time when starting to invoke another script or function. */ void script_prof_save(tm) proftime_T *tm; /* place to store wait time */ { scriptitem_T *si; if (current_SID > 0 && current_SID <= script_items.ga_len) { si = &SCRIPT_ITEM(current_SID); if (si->sn_prof_on && si->sn_pr_nest++ == 0) profile_start(&si->sn_pr_child); } profile_get_wait(tm); } /* * Count time spent in children after invoking another script or function. */ void script_prof_restore(tm) proftime_T *tm; { scriptitem_T *si; if (current_SID > 0 && current_SID <= script_items.ga_len) { si = &SCRIPT_ITEM(current_SID); if (si->sn_prof_on && --si->sn_pr_nest == 0) { profile_end(&si->sn_pr_child); profile_sub_wait(tm, &si->sn_pr_child); /* don't count wait time */ profile_add(&si->sn_pr_children, &si->sn_pr_child); profile_add(&si->sn_prl_children, &si->sn_pr_child); } } } static proftime_T inchar_time; /* * Called when starting to wait for the user to type a character. */ void prof_inchar_enter() { profile_start(&inchar_time); } /* * Called when finished waiting for the user to type a character. */ void prof_inchar_exit() { profile_end(&inchar_time); profile_add(&prof_wait_time, &inchar_time); } /* * Dump the profiling results for all scripts in file "fd". */ static void script_dump_profile(fd) FILE *fd; { int id; scriptitem_T *si; int i; FILE *sfd; sn_prl_T *pp; for (id = 1; id <= script_items.ga_len; ++id) { si = &SCRIPT_ITEM(id); if (si->sn_prof_on) { fprintf(fd, "SCRIPT %s\n", si->sn_name); if (si->sn_pr_count == 1) fprintf(fd, "Sourced 1 time\n"); else fprintf(fd, "Sourced %d times\n", si->sn_pr_count); fprintf(fd, "Total time: %s\n", profile_msg(&si->sn_pr_total)); fprintf(fd, " Self time: %s\n", profile_msg(&si->sn_pr_self)); fprintf(fd, "\n"); fprintf(fd, "count total (s) self (s)\n"); sfd = mch_fopen((char *)si->sn_name, "r"); if (sfd == NULL) fprintf(fd, "Cannot open file!\n"); else { for (i = 0; i < si->sn_prl_ga.ga_len; ++i) { if (vim_fgets(IObuff, IOSIZE, sfd)) break; pp = &PRL_ITEM(si, i); if (pp->snp_count > 0) { fprintf(fd, "%5d ", pp->snp_count); if (profile_equal(&pp->sn_prl_total, &pp->sn_prl_self)) fprintf(fd, " "); else fprintf(fd, "%s ", profile_msg(&pp->sn_prl_total)); fprintf(fd, "%s ", profile_msg(&pp->sn_prl_self)); } else fprintf(fd, " "); fprintf(fd, "%s", IObuff); } fclose(sfd); } fprintf(fd, "\n"); } } } /* * Return TRUE when a function defined in the current script should be * profiled. */ int prof_def_func() { if (current_SID > 0) return SCRIPT_ITEM(current_SID).sn_pr_force; return FALSE; } # endif #endif /* * If 'autowrite' option set, try to write the file. * Careful: autocommands may make "buf" invalid! * * return FAIL for failure, OK otherwise */ int autowrite(buf, forceit) buf_T *buf; int forceit; { int r; if (!(p_aw || p_awa) || !p_write #ifdef FEAT_QUICKFIX /* never autowrite a "nofile" or "nowrite" buffer */ || bt_dontwrite(buf) #endif || (!forceit && buf->b_p_ro) || buf->b_ffname == NULL) return FAIL; r = buf_write_all(buf, forceit); /* Writing may succeed but the buffer still changed, e.g., when there is a * conversion error. We do want to return FAIL then. */ if (buf_valid(buf) && bufIsChanged(buf)) r = FAIL; return r; } /* * flush all buffers, except the ones that are readonly */ void autowrite_all() { buf_T *buf; if (!(p_aw || p_awa) || !p_write) return; for (buf = firstbuf; buf; buf = buf->b_next) if (bufIsChanged(buf) && !buf->b_p_ro) { (void)buf_write_all(buf, FALSE); #ifdef FEAT_AUTOCMD /* an autocommand may have deleted the buffer */ if (!buf_valid(buf)) buf = firstbuf; #endif } } /* * return TRUE if buffer was changed and cannot be abandoned. */ int check_changed(buf, checkaw, mult_win, forceit, allbuf) buf_T *buf; int checkaw; /* do autowrite if buffer was changed */ int mult_win; /* check also when several wins for the buf */ int forceit; int allbuf UNUSED; /* may write all buffers */ { if ( !forceit && bufIsChanged(buf) && (mult_win || buf->b_nwindows <= 1) && (!checkaw || autowrite(buf, forceit) == FAIL)) { #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) if ((p_confirm || cmdmod.confirm) && p_write) { buf_T *buf2; int count = 0; if (allbuf) for (buf2 = firstbuf; buf2 != NULL; buf2 = buf2->b_next) if (bufIsChanged(buf2) && (buf2->b_ffname != NULL # ifdef FEAT_BROWSE || cmdmod.browse # endif )) ++count; # ifdef FEAT_AUTOCMD if (!buf_valid(buf)) /* Autocommand deleted buffer, oops! It's not changed now. */ return FALSE; # endif dialog_changed(buf, count > 1); # ifdef FEAT_AUTOCMD if (!buf_valid(buf)) /* Autocommand deleted buffer, oops! It's not changed now. */ return FALSE; # endif return bufIsChanged(buf); } #endif EMSG(_(e_nowrtmsg)); return TRUE; } return FALSE; } #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) || defined(PROTO) #if defined(FEAT_BROWSE) || defined(PROTO) /* * When wanting to write a file without a file name, ask the user for a name. */ void browse_save_fname(buf) buf_T *buf; { if (buf->b_fname == NULL) { char_u *fname; fname = do_browse(BROWSE_SAVE, (char_u *)_("Save As"), NULL, NULL, NULL, NULL, buf); if (fname != NULL) { if (setfname(buf, fname, NULL, TRUE) == OK) buf->b_flags |= BF_NOTEDITED; vim_free(fname); } } } #endif /* * Ask the user what to do when abandoning a changed buffer. * Must check 'write' option first! */ void dialog_changed(buf, checkall) buf_T *buf; int checkall; /* may abandon all changed buffers */ { char_u buff[DIALOG_MSG_SIZE]; int ret; buf_T *buf2; exarg_T ea; dialog_msg(buff, _("Save changes to \"%s\"?"), (buf->b_fname != NULL) ? buf->b_fname : (char_u *)_("Untitled")); if (checkall) ret = vim_dialog_yesnoallcancel(VIM_QUESTION, NULL, buff, 1); else ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1); /* Init ea pseudo-structure, this is needed for the check_overwrite() * function. */ ea.append = ea.forceit = FALSE; if (ret == VIM_YES) { #ifdef FEAT_BROWSE /* May get file name, when there is none */ browse_save_fname(buf); #endif if (buf->b_fname != NULL && check_overwrite(&ea, buf, buf->b_fname, buf->b_ffname, FALSE) == OK) /* didn't hit Cancel */ (void)buf_write_all(buf, FALSE); } else if (ret == VIM_NO) { unchanged(buf, TRUE); } else if (ret == VIM_ALL) { /* * Write all modified files that can be written. * Skip readonly buffers, these need to be confirmed * individually. */ for (buf2 = firstbuf; buf2 != NULL; buf2 = buf2->b_next) { if (bufIsChanged(buf2) && (buf2->b_ffname != NULL #ifdef FEAT_BROWSE || cmdmod.browse #endif ) && !buf2->b_p_ro) { #ifdef FEAT_BROWSE /* May get file name, when there is none */ browse_save_fname(buf2); #endif if (buf2->b_fname != NULL && check_overwrite(&ea, buf2, buf2->b_fname, buf2->b_ffname, FALSE) == OK) /* didn't hit Cancel */ (void)buf_write_all(buf2, FALSE); #ifdef FEAT_AUTOCMD /* an autocommand may have deleted the buffer */ if (!buf_valid(buf2)) buf2 = firstbuf; #endif } } } else if (ret == VIM_DISCARDALL) { /* * mark all buffers as unchanged */ for (buf2 = firstbuf; buf2 != NULL; buf2 = buf2->b_next) unchanged(buf2, TRUE); } } #endif /* * Return TRUE if the buffer "buf" can be abandoned, either by making it * hidden, autowriting it or unloading it. */ int can_abandon(buf, forceit) buf_T *buf; int forceit; { return ( P_HID(buf) || !bufIsChanged(buf) || buf->b_nwindows > 1 || autowrite(buf, forceit) == OK || forceit); } static void add_bufnum __ARGS((int *bufnrs, int *bufnump, int nr)); /* * Add a buffer number to "bufnrs", unless it's already there. */ static void add_bufnum(bufnrs, bufnump, nr) int *bufnrs; int *bufnump; int nr; { int i; for (i = 0; i < *bufnump; ++i) if (bufnrs[i] == nr) return; bufnrs[*bufnump] = nr; *bufnump = *bufnump + 1; } /* * Return TRUE if any buffer was changed and cannot be abandoned. * That changed buffer becomes the current buffer. */ int check_changed_any(hidden) int hidden; /* Only check hidden buffers */ { int ret = FALSE; buf_T *buf; int save; int i; int bufnum = 0; int bufcount = 0; int *bufnrs; #ifdef FEAT_WINDOWS tabpage_T *tp; win_T *wp; #endif for (buf = firstbuf; buf != NULL; buf = buf->b_next) ++bufcount; if (bufcount == 0) return FALSE; bufnrs = (int *)alloc(sizeof(int) * bufcount); if (bufnrs == NULL) return FALSE; /* curbuf */ bufnrs[bufnum++] = curbuf->b_fnum; #ifdef FEAT_WINDOWS /* buf in curtab */ FOR_ALL_WINDOWS(wp) if (wp->w_buffer != curbuf) add_bufnum(bufnrs, &bufnum, wp->w_buffer->b_fnum); /* buf in other tab */ for (tp = first_tabpage; tp != NULL; tp = tp->tp_next) if (tp != curtab) for (wp = tp->tp_firstwin; wp != NULL; wp = wp->w_next) add_bufnum(bufnrs, &bufnum, wp->w_buffer->b_fnum); #endif /* any other buf */ for (buf = firstbuf; buf != NULL; buf = buf->b_next) add_bufnum(bufnrs, &bufnum, buf->b_fnum); for (i = 0; i < bufnum; ++i) { buf = buflist_findnr(bufnrs[i]); if (buf == NULL) continue; if ((!hidden || buf->b_nwindows == 0) && bufIsChanged(buf)) { /* Try auto-writing the buffer. If this fails but the buffer no * longer exists it's not changed, that's OK. */ if (check_changed(buf, p_awa, TRUE, FALSE, TRUE) && buf_valid(buf)) break; /* didn't save - still changes */ } } if (i >= bufnum) goto theend; ret = TRUE; exiting = FALSE; #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) /* * When ":confirm" used, don't give an error message. */ if (!(p_confirm || cmdmod.confirm)) #endif { /* There must be a wait_return for this message, do_buffer() * may cause a redraw. But wait_return() is a no-op when vgetc() * is busy (Quit used from window menu), then make sure we don't * cause a scroll up. */ if (vgetc_busy > 0) { msg_row = cmdline_row; msg_col = 0; msg_didout = FALSE; } if (EMSG2(_("E162: No write since last change for buffer \"%s\""), buf_spname(buf) != NULL ? (char_u *)buf_spname(buf) : buf->b_fname)) { save = no_wait_return; no_wait_return = FALSE; wait_return(FALSE); no_wait_return = save; } } #ifdef FEAT_WINDOWS /* Try to find a window that contains the buffer. */ if (buf != curbuf) FOR_ALL_TAB_WINDOWS(tp, wp) if (wp->w_buffer == buf) { goto_tabpage_win(tp, wp); # ifdef FEAT_AUTOCMD /* Paranoia: did autocms wipe out the buffer with changes? */ if (!buf_valid(buf)) { goto theend; } # endif goto buf_found; } buf_found: #endif /* Open the changed buffer in the current window. */ if (buf != curbuf) set_curbuf(buf, DOBUF_GOTO); theend: vim_free(bufnrs); return ret; } /* * return FAIL if there is no file name, OK if there is one * give error message for FAIL */ int check_fname() { if (curbuf->b_ffname == NULL) { EMSG(_(e_noname)); return FAIL; } return OK; } /* * flush the contents of a buffer, unless it has no file name * * return FAIL for failure, OK otherwise */ int buf_write_all(buf, forceit) buf_T *buf; int forceit; { int retval; #ifdef FEAT_AUTOCMD buf_T *old_curbuf = curbuf; #endif retval = (buf_write(buf, buf->b_ffname, buf->b_fname, (linenr_T)1, buf->b_ml.ml_line_count, NULL, FALSE, forceit, TRUE, FALSE)); #ifdef FEAT_AUTOCMD if (curbuf != old_curbuf) { msg_source(hl_attr(HLF_W)); MSG(_("Warning: Entered other buffer unexpectedly (check autocommands)")); } #endif return retval; } /* * Code to handle the argument list. */ static char_u *do_one_arg __ARGS((char_u *str)); static int do_arglist __ARGS((char_u *str, int what, int after)); static void alist_check_arg_idx __ARGS((void)); static int editing_arg_idx __ARGS((win_T *win)); #ifdef FEAT_LISTCMDS static int alist_add_list __ARGS((int count, char_u **files, int after)); #endif #define AL_SET 1 #define AL_ADD 2 #define AL_DEL 3 /* * Isolate one argument, taking backticks. * Changes the argument in-place, puts a NUL after it. Backticks remain. * Return a pointer to the start of the next argument. */ static char_u * do_one_arg(str) char_u *str; { char_u *p; int inbacktick; inbacktick = FALSE; for (p = str; *str; ++str) { /* When the backslash is used for escaping the special meaning of a * character we need to keep it until wildcard expansion. */ if (rem_backslash(str)) { *p++ = *str++; *p++ = *str; } else { /* An item ends at a space not in backticks */ if (!inbacktick && vim_isspace(*str)) break; if (*str == '`') inbacktick ^= TRUE; *p++ = *str; } } str = skipwhite(str); *p = NUL; return str; } /* * Separate the arguments in "str" and return a list of pointers in the * growarray "gap". */ int get_arglist(gap, str) garray_T *gap; char_u *str; { ga_init2(gap, (int)sizeof(char_u *), 20); while (*str != NUL) { if (ga_grow(gap, 1) == FAIL) { ga_clear(gap); return FAIL; } ((char_u **)gap->ga_data)[gap->ga_len++] = str; /* Isolate one argument, change it in-place, put a NUL after it. */ str = do_one_arg(str); } return OK; } #if defined(FEAT_QUICKFIX) || defined(FEAT_SYN_HL) || defined(PROTO) /* * Parse a list of arguments (file names), expand them and return in * "fnames[fcountp]". * Return FAIL or OK. */ int get_arglist_exp(str, fcountp, fnamesp) char_u *str; int *fcountp; char_u ***fnamesp; { garray_T ga; int i; if (get_arglist(&ga, str) == FAIL) return FAIL; i = gen_expand_wildcards(ga.ga_len, (char_u **)ga.ga_data, fcountp, fnamesp, EW_FILE|EW_NOTFOUND); ga_clear(&ga); return i; } #endif #if defined(FEAT_GUI) || defined(FEAT_CLIENTSERVER) || defined(PROTO) /* * Redefine the argument list. */ void set_arglist(str) char_u *str; { do_arglist(str, AL_SET, 0); } #endif /* * "what" == AL_SET: Redefine the argument list to 'str'. * "what" == AL_ADD: add files in 'str' to the argument list after "after". * "what" == AL_DEL: remove files in 'str' from the argument list. * * Return FAIL for failure, OK otherwise. */ static int do_arglist(str, what, after) char_u *str; int what UNUSED; int after UNUSED; /* 0 means before first one */ { garray_T new_ga; int exp_count; char_u **exp_files; int i; #ifdef FEAT_LISTCMDS char_u *p; int match; #endif /* * Collect all file name arguments in "new_ga". */ if (get_arglist(&new_ga, str) == FAIL) return FAIL; #ifdef FEAT_LISTCMDS if (what == AL_DEL) { regmatch_T regmatch; int didone; /* * Delete the items: use each item as a regexp and find a match in the * argument list. */ #ifdef CASE_INSENSITIVE_FILENAME regmatch.rm_ic = TRUE; /* Always ignore case */ #else regmatch.rm_ic = FALSE; /* Never ignore case */ #endif for (i = 0; i < new_ga.ga_len && !got_int; ++i) { p = ((char_u **)new_ga.ga_data)[i]; p = file_pat_to_reg_pat(p, NULL, NULL, FALSE); if (p == NULL) break; regmatch.regprog = vim_regcomp(p, p_magic ? RE_MAGIC : 0); if (regmatch.regprog == NULL) { vim_free(p); break; } didone = FALSE; for (match = 0; match < ARGCOUNT; ++match) if (vim_regexec(&regmatch, alist_name(&ARGLIST[match]), (colnr_T)0)) { didone = TRUE; vim_free(ARGLIST[match].ae_fname); mch_memmove(ARGLIST + match, ARGLIST + match + 1, (ARGCOUNT - match - 1) * sizeof(aentry_T)); --ALIST(curwin)->al_ga.ga_len; if (curwin->w_arg_idx > match) --curwin->w_arg_idx; --match; } vim_free(regmatch.regprog); vim_free(p); if (!didone) EMSG2(_(e_nomatch2), ((char_u **)new_ga.ga_data)[i]); } ga_clear(&new_ga); } else #endif { i = expand_wildcards(new_ga.ga_len, (char_u **)new_ga.ga_data, &exp_count, &exp_files, EW_DIR|EW_FILE|EW_ADDSLASH|EW_NOTFOUND); ga_clear(&new_ga); if (i == FAIL) return FAIL; if (exp_count == 0) { EMSG(_(e_nomatch)); return FAIL; } #ifdef FEAT_LISTCMDS if (what == AL_ADD) { (void)alist_add_list(exp_count, exp_files, after); vim_free(exp_files); } else /* what == AL_SET */ #endif alist_set(ALIST(curwin), exp_count, exp_files, FALSE, NULL, 0); } alist_check_arg_idx(); return OK; } /* * Check the validity of the arg_idx for each other window. */ static void alist_check_arg_idx() { #ifdef FEAT_WINDOWS win_T *win; tabpage_T *tp; FOR_ALL_TAB_WINDOWS(tp, win) if (win->w_alist == curwin->w_alist) check_arg_idx(win); #else check_arg_idx(curwin); #endif } /* * Return TRUE if window "win" is editing the file at the current argument * index. */ static int editing_arg_idx(win) win_T *win; { return !(win->w_arg_idx >= WARGCOUNT(win) || (win->w_buffer->b_fnum != WARGLIST(win)[win->w_arg_idx].ae_fnum && (win->w_buffer->b_ffname == NULL || !(fullpathcmp( alist_name(&WARGLIST(win)[win->w_arg_idx]), win->w_buffer->b_ffname, TRUE) & FPC_SAME)))); } /* * Check if window "win" is editing the w_arg_idx file in its argument list. */ void check_arg_idx(win) win_T *win; { if (WARGCOUNT(win) > 1 && !editing_arg_idx(win)) { /* We are not editing the current entry in the argument list. * Set "arg_had_last" if we are editing the last one. */ win->w_arg_idx_invalid = TRUE; if (win->w_arg_idx != WARGCOUNT(win) - 1 && arg_had_last == FALSE #ifdef FEAT_WINDOWS && ALIST(win) == &global_alist #endif && GARGCOUNT > 0 && win->w_arg_idx < GARGCOUNT && (win->w_buffer->b_fnum == GARGLIST[GARGCOUNT - 1].ae_fnum || (win->w_buffer->b_ffname != NULL && (fullpathcmp(alist_name(&GARGLIST[GARGCOUNT - 1]), win->w_buffer->b_ffname, TRUE) & FPC_SAME)))) arg_had_last = TRUE; } else { /* We are editing the current entry in the argument list. * Set "arg_had_last" if it's also the last one */ win->w_arg_idx_invalid = FALSE; if (win->w_arg_idx == WARGCOUNT(win) - 1 #ifdef FEAT_WINDOWS && win->w_alist == &global_alist #endif ) arg_had_last = TRUE; } } /* * ":args", ":argslocal" and ":argsglobal". */ void ex_args(eap) exarg_T *eap; { int i; if (eap->cmdidx != CMD_args) { #if defined(FEAT_WINDOWS) && defined(FEAT_LISTCMDS) alist_unlink(ALIST(curwin)); if (eap->cmdidx == CMD_argglobal) ALIST(curwin) = &global_alist; else /* eap->cmdidx == CMD_arglocal */ alist_new(); #else ex_ni(eap); return; #endif } if (!ends_excmd(*eap->arg)) { /* * ":args file ..": define new argument list, handle like ":next" * Also for ":argslocal file .." and ":argsglobal file ..". */ ex_next(eap); } else #if defined(FEAT_WINDOWS) && defined(FEAT_LISTCMDS) if (eap->cmdidx == CMD_args) #endif { /* * ":args": list arguments. */ if (ARGCOUNT > 0) { /* Overwrite the command, for a short list there is no scrolling * required and no wait_return(). */ gotocmdline(TRUE); for (i = 0; i < ARGCOUNT; ++i) { if (i == curwin->w_arg_idx) msg_putchar('['); msg_outtrans(alist_name(&ARGLIST[i])); if (i == curwin->w_arg_idx) msg_putchar(']'); msg_putchar(' '); } } } #if defined(FEAT_WINDOWS) && defined(FEAT_LISTCMDS) else if (eap->cmdidx == CMD_arglocal) { garray_T *gap = &curwin->w_alist->al_ga; /* * ":argslocal": make a local copy of the global argument list. */ if (ga_grow(gap, GARGCOUNT) == OK) for (i = 0; i < GARGCOUNT; ++i) if (GARGLIST[i].ae_fname != NULL) { AARGLIST(curwin->w_alist)[gap->ga_len].ae_fname = vim_strsave(GARGLIST[i].ae_fname); AARGLIST(curwin->w_alist)[gap->ga_len].ae_fnum = GARGLIST[i].ae_fnum; ++gap->ga_len; } } #endif } /* * ":previous", ":sprevious", ":Next" and ":sNext". */ void ex_previous(eap) exarg_T *eap; { /* If past the last one already, go to the last one. */ if (curwin->w_arg_idx - (int)eap->line2 >= ARGCOUNT) do_argfile(eap, ARGCOUNT - 1); else do_argfile(eap, curwin->w_arg_idx - (int)eap->line2); } /* * ":rewind", ":first", ":sfirst" and ":srewind". */ void ex_rewind(eap) exarg_T *eap; { do_argfile(eap, 0); } /* * ":last" and ":slast". */ void ex_last(eap) exarg_T *eap; { do_argfile(eap, ARGCOUNT - 1); } /* * ":argument" and ":sargument". */ void ex_argument(eap) exarg_T *eap; { int i; if (eap->addr_count > 0) i = eap->line2 - 1; else i = curwin->w_arg_idx; do_argfile(eap, i); } /* * Edit file "argn" of the argument lists. */ void do_argfile(eap, argn) exarg_T *eap; int argn; { int other; char_u *p; int old_arg_idx = curwin->w_arg_idx; if (argn < 0 || argn >= ARGCOUNT) { if (ARGCOUNT <= 1) EMSG(_("E163: There is only one file to edit")); else if (argn < 0) EMSG(_("E164: Cannot go before first file")); else EMSG(_("E165: Cannot go beyond last file")); } else { setpcmark(); #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif #ifdef FEAT_WINDOWS /* split window or create new tab page first */ if (*eap->cmd == 's' || cmdmod.tab != 0) { if (win_split(0, 0) == FAIL) return; RESET_BINDING(curwin); } else #endif { /* * if 'hidden' set, only check for changed file when re-editing * the same buffer */ other = TRUE; if (P_HID(curbuf)) { p = fix_fname(alist_name(&ARGLIST[argn])); other = otherfile(p); vim_free(p); } if ((!P_HID(curbuf) || !other) && check_changed(curbuf, TRUE, !other, eap->forceit, FALSE)) return; } curwin->w_arg_idx = argn; if (argn == ARGCOUNT - 1 #ifdef FEAT_WINDOWS && curwin->w_alist == &global_alist #endif ) arg_had_last = TRUE; /* Edit the file; always use the last known line number. * When it fails (e.g. Abort for already edited file) restore the * argument index. */ if (do_ecmd(0, alist_name(&ARGLIST[curwin->w_arg_idx]), NULL, eap, ECMD_LAST, (P_HID(curwin->w_buffer) ? ECMD_HIDE : 0) + (eap->forceit ? ECMD_FORCEIT : 0), curwin) == FAIL) curwin->w_arg_idx = old_arg_idx; /* like Vi: set the mark where the cursor is in the file. */ else if (eap->cmdidx != CMD_argdo) setmark('\''); } } /* * ":next", and commands that behave like it. */ void ex_next(eap) exarg_T *eap; { int i; /* * check for changed buffer now, if this fails the argument list is not * redefined. */ if ( P_HID(curbuf) || eap->cmdidx == CMD_snext || !check_changed(curbuf, TRUE, FALSE, eap->forceit, FALSE)) { if (*eap->arg != NUL) /* redefine file list */ { if (do_arglist(eap->arg, AL_SET, 0) == FAIL) return; i = 0; } else i = curwin->w_arg_idx + (int)eap->line2; do_argfile(eap, i); } } #ifdef FEAT_LISTCMDS /* * ":argedit" */ void ex_argedit(eap) exarg_T *eap; { int fnum; int i; char_u *s; /* Add the argument to the buffer list and get the buffer number. */ fnum = buflist_add(eap->arg, BLN_LISTED); /* Check if this argument is already in the argument list. */ for (i = 0; i < ARGCOUNT; ++i) if (ARGLIST[i].ae_fnum == fnum) break; if (i == ARGCOUNT) { /* Can't find it, add it to the argument list. */ s = vim_strsave(eap->arg); if (s == NULL) return; i = alist_add_list(1, &s, eap->addr_count > 0 ? (int)eap->line2 : curwin->w_arg_idx + 1); if (i < 0) return; curwin->w_arg_idx = i; } alist_check_arg_idx(); /* Edit the argument. */ do_argfile(eap, i); } /* * ":argadd" */ void ex_argadd(eap) exarg_T *eap; { do_arglist(eap->arg, AL_ADD, eap->addr_count > 0 ? (int)eap->line2 : curwin->w_arg_idx + 1); #ifdef FEAT_TITLE maketitle(); #endif } /* * ":argdelete" */ void ex_argdelete(eap) exarg_T *eap; { int i; int n; if (eap->addr_count > 0) { /* ":1,4argdel": Delete all arguments in the range. */ if (eap->line2 > ARGCOUNT) eap->line2 = ARGCOUNT; n = eap->line2 - eap->line1 + 1; if (*eap->arg != NUL || n <= 0) EMSG(_(e_invarg)); else { for (i = eap->line1; i <= eap->line2; ++i) vim_free(ARGLIST[i - 1].ae_fname); mch_memmove(ARGLIST + eap->line1 - 1, ARGLIST + eap->line2, (size_t)((ARGCOUNT - eap->line2) * sizeof(aentry_T))); ALIST(curwin)->al_ga.ga_len -= n; if (curwin->w_arg_idx >= eap->line2) curwin->w_arg_idx -= n; else if (curwin->w_arg_idx > eap->line1) curwin->w_arg_idx = eap->line1; } } else if (*eap->arg == NUL) EMSG(_(e_argreq)); else do_arglist(eap->arg, AL_DEL, 0); #ifdef FEAT_TITLE maketitle(); #endif } /* * ":argdo", ":windo", ":bufdo", ":tabdo" */ void ex_listdo(eap) exarg_T *eap; { int i; #ifdef FEAT_WINDOWS win_T *wp; tabpage_T *tp; #endif buf_T *buf; int next_fnum = 0; #if defined(FEAT_AUTOCMD) && defined(FEAT_SYN_HL) char_u *save_ei = NULL; #endif char_u *p_shm_save; #ifndef FEAT_WINDOWS if (eap->cmdidx == CMD_windo) { ex_ni(eap); return; } #endif #if defined(FEAT_AUTOCMD) && defined(FEAT_SYN_HL) if (eap->cmdidx != CMD_windo && eap->cmdidx != CMD_tabdo) /* Don't do syntax HL autocommands. Skipping the syntax file is a * great speed improvement. */ save_ei = au_event_disable(",Syntax"); #endif if (eap->cmdidx == CMD_windo || eap->cmdidx == CMD_tabdo || P_HID(curbuf) || !check_changed(curbuf, TRUE, FALSE, eap->forceit, FALSE)) { /* start at the first argument/window/buffer */ i = 0; #ifdef FEAT_WINDOWS wp = firstwin; tp = first_tabpage; #endif /* set pcmark now */ if (eap->cmdidx == CMD_bufdo) goto_buffer(eap, DOBUF_FIRST, FORWARD, 0); else setpcmark(); listcmd_busy = TRUE; /* avoids setting pcmark below */ while (!got_int) { if (eap->cmdidx == CMD_argdo) { /* go to argument "i" */ if (i == ARGCOUNT) break; /* Don't call do_argfile() when already there, it will try * reloading the file. */ if (curwin->w_arg_idx != i || !editing_arg_idx(curwin)) { /* Clear 'shm' to avoid that the file message overwrites * any output from the command. */ p_shm_save = vim_strsave(p_shm); set_option_value((char_u *)"shm", 0L, (char_u *)"", 0); do_argfile(eap, i); set_option_value((char_u *)"shm", 0L, p_shm_save, 0); vim_free(p_shm_save); } if (curwin->w_arg_idx != i) break; ++i; } #ifdef FEAT_WINDOWS else if (eap->cmdidx == CMD_windo) { /* go to window "wp" */ if (!win_valid(wp)) break; win_goto(wp); if (curwin != wp) break; /* something must be wrong */ wp = curwin->w_next; } else if (eap->cmdidx == CMD_tabdo) { /* go to window "tp" */ if (!valid_tabpage(tp)) break; goto_tabpage_tp(tp, TRUE); tp = tp->tp_next; } #endif else if (eap->cmdidx == CMD_bufdo) { /* Remember the number of the next listed buffer, in case * ":bwipe" is used or autocommands do something strange. */ next_fnum = -1; for (buf = curbuf->b_next; buf != NULL; buf = buf->b_next) if (buf->b_p_bl) { next_fnum = buf->b_fnum; break; } } /* execute the command */ do_cmdline(eap->arg, eap->getline, eap->cookie, DOCMD_VERBOSE + DOCMD_NOWAIT); if (eap->cmdidx == CMD_bufdo) { /* Done? */ if (next_fnum < 0) break; /* Check if the buffer still exists. */ for (buf = firstbuf; buf != NULL; buf = buf->b_next) if (buf->b_fnum == next_fnum) break; if (buf == NULL) break; /* Go to the next buffer. Clear 'shm' to avoid that the file * message overwrites any output from the command. */ p_shm_save = vim_strsave(p_shm); set_option_value((char_u *)"shm", 0L, (char_u *)"", 0); goto_buffer(eap, DOBUF_FIRST, FORWARD, next_fnum); set_option_value((char_u *)"shm", 0L, p_shm_save, 0); vim_free(p_shm_save); /* If autocommands took us elsewhere, quit here */ if (curbuf->b_fnum != next_fnum) break; } if (eap->cmdidx == CMD_windo) { validate_cursor(); /* cursor may have moved */ #ifdef FEAT_SCROLLBIND /* required when 'scrollbind' has been set */ if (curwin->w_p_scb) do_check_scrollbind(TRUE); #endif } } listcmd_busy = FALSE; } #if defined(FEAT_AUTOCMD) && defined(FEAT_SYN_HL) if (save_ei != NULL) { au_event_restore(save_ei); apply_autocmds(EVENT_SYNTAX, curbuf->b_p_syn, curbuf->b_fname, TRUE, curbuf); } #endif } /* * Add files[count] to the arglist of the current window after arg "after". * The file names in files[count] must have been allocated and are taken over. * Files[] itself is not taken over. * Returns index of first added argument. Returns -1 when failed (out of mem). */ static int alist_add_list(count, files, after) int count; char_u **files; int after; /* where to add: 0 = before first one */ { int i; if (ga_grow(&ALIST(curwin)->al_ga, count) == OK) { if (after < 0) after = 0; if (after > ARGCOUNT) after = ARGCOUNT; if (after < ARGCOUNT) mch_memmove(&(ARGLIST[after + count]), &(ARGLIST[after]), (ARGCOUNT - after) * sizeof(aentry_T)); for (i = 0; i < count; ++i) { ARGLIST[after + i].ae_fname = files[i]; ARGLIST[after + i].ae_fnum = buflist_add(files[i], BLN_LISTED); } ALIST(curwin)->al_ga.ga_len += count; if (curwin->w_arg_idx >= after) ++curwin->w_arg_idx; return after; } for (i = 0; i < count; ++i) vim_free(files[i]); return -1; } #endif /* FEAT_LISTCMDS */ #ifdef FEAT_EVAL /* * ":compiler[!] {name}" */ void ex_compiler(eap) exarg_T *eap; { char_u *buf; char_u *old_cur_comp = NULL; char_u *p; if (*eap->arg == NUL) { /* List all compiler scripts. */ do_cmdline_cmd((char_u *)"echo globpath(&rtp, 'compiler/*.vim')"); /* ) keep the indenter happy... */ } else { buf = alloc((unsigned)(STRLEN(eap->arg) + 14)); if (buf != NULL) { if (eap->forceit) { /* ":compiler! {name}" sets global options */ do_cmdline_cmd((char_u *) "command -nargs=* CompilerSet set <args>"); } else { /* ":compiler! {name}" sets local options. * To remain backwards compatible "current_compiler" is always * used. A user's compiler plugin may set it, the distributed * plugin will then skip the settings. Afterwards set * "b:current_compiler" and restore "current_compiler". * Explicitly prepend "g:" to make it work in a function. */ old_cur_comp = get_var_value((char_u *)"g:current_compiler"); if (old_cur_comp != NULL) old_cur_comp = vim_strsave(old_cur_comp); do_cmdline_cmd((char_u *) "command -nargs=* CompilerSet setlocal <args>"); } do_unlet((char_u *)"g:current_compiler", TRUE); do_unlet((char_u *)"b:current_compiler", TRUE); sprintf((char *)buf, "compiler/%s.vim", eap->arg); if (source_runtime(buf, TRUE) == FAIL) EMSG2(_("E666: compiler not supported: %s"), eap->arg); vim_free(buf); do_cmdline_cmd((char_u *)":delcommand CompilerSet"); /* Set "b:current_compiler" from "current_compiler". */ p = get_var_value((char_u *)"g:current_compiler"); if (p != NULL) set_internal_string_var((char_u *)"b:current_compiler", p); /* Restore "current_compiler" for ":compiler {name}". */ if (!eap->forceit) { if (old_cur_comp != NULL) { set_internal_string_var((char_u *)"g:current_compiler", old_cur_comp); vim_free(old_cur_comp); } else do_unlet((char_u *)"g:current_compiler", TRUE); } } } } #endif /* * ":runtime {name}" */ void ex_runtime(eap) exarg_T *eap; { source_runtime(eap->arg, eap->forceit); } static void source_callback __ARGS((char_u *fname, void *cookie)); static void source_callback(fname, cookie) char_u *fname; void *cookie UNUSED; { (void)do_source(fname, FALSE, DOSO_NONE); } /* * Source the file "name" from all directories in 'runtimepath'. * "name" can contain wildcards. * When "all" is TRUE, source all files, otherwise only the first one. * return FAIL when no file could be sourced, OK otherwise. */ int source_runtime(name, all) char_u *name; int all; { return do_in_runtimepath(name, all, source_callback, NULL); } /* * Find "name" in 'runtimepath'. When found, invoke the callback function for * it: callback(fname, "cookie") * When "all" is TRUE repeat for all matches, otherwise only the first one is * used. * Returns OK when at least one match found, FAIL otherwise. */ int do_in_runtimepath(name, all, callback, cookie) char_u *name; int all; void (*callback)__ARGS((char_u *fname, void *ck)); void *cookie; { char_u *rtp; char_u *np; char_u *buf; char_u *rtp_copy; char_u *tail; int num_files; char_u **files; int i; int did_one = FALSE; #ifdef AMIGA struct Process *proc = (struct Process *)FindTask(0L); APTR save_winptr = proc->pr_WindowPtr; /* Avoid a requester here for a volume that doesn't exist. */ proc->pr_WindowPtr = (APTR)-1L; #endif /* Make a copy of 'runtimepath'. Invoking the callback may change the * value. */ rtp_copy = vim_strsave(p_rtp); buf = alloc(MAXPATHL); if (buf != NULL && rtp_copy != NULL) { if (p_verbose > 1) { verbose_enter(); smsg((char_u *)_("Searching for \"%s\" in \"%s\""), (char *)name, (char *)p_rtp); verbose_leave(); } /* Loop over all entries in 'runtimepath'. */ rtp = rtp_copy; while (*rtp != NUL && (all || !did_one)) { /* Copy the path from 'runtimepath' to buf[]. */ copy_option_part(&rtp, buf, MAXPATHL, ","); if (STRLEN(buf) + STRLEN(name) + 2 < MAXPATHL) { add_pathsep(buf); tail = buf + STRLEN(buf); /* Loop over all patterns in "name" */ np = name; while (*np != NUL && (all || !did_one)) { /* Append the pattern from "name" to buf[]. */ copy_option_part(&np, tail, (int)(MAXPATHL - (tail - buf)), "\t "); if (p_verbose > 2) { verbose_enter(); smsg((char_u *)_("Searching for \"%s\""), buf); verbose_leave(); } /* Expand wildcards, invoke the callback for each match. */ if (gen_expand_wildcards(1, &buf, &num_files, &files, EW_FILE) == OK) { for (i = 0; i < num_files; ++i) { (*callback)(files[i], cookie); did_one = TRUE; if (!all) break; } FreeWild(num_files, files); } } } } } vim_free(buf); vim_free(rtp_copy); if (p_verbose > 0 && !did_one) { verbose_enter(); smsg((char_u *)_("not found in 'runtimepath': \"%s\""), name); verbose_leave(); } #ifdef AMIGA proc->pr_WindowPtr = save_winptr; #endif return did_one ? OK : FAIL; } #if defined(FEAT_EVAL) && defined(FEAT_AUTOCMD) /* * ":options" */ void ex_options(eap) exarg_T *eap UNUSED; { cmd_source((char_u *)SYS_OPTWIN_FILE, NULL); } #endif /* * ":source {fname}" */ void ex_source(eap) exarg_T *eap; { #ifdef FEAT_BROWSE if (cmdmod.browse) { char_u *fname = NULL; fname = do_browse(0, (char_u *)_("Source Vim script"), eap->arg, NULL, NULL, BROWSE_FILTER_MACROS, NULL); if (fname != NULL) { cmd_source(fname, eap); vim_free(fname); } } else #endif cmd_source(eap->arg, eap); } static void cmd_source(fname, eap) char_u *fname; exarg_T *eap; { if (*fname == NUL) EMSG(_(e_argreq)); else if (eap != NULL && eap->forceit) /* ":source!": read Normal mdoe commands * Need to execute the commands directly. This is required at least * for: * - ":g" command busy * - after ":argdo", ":windo" or ":bufdo" * - another command follows * - inside a loop */ openscript(fname, global_busy || listcmd_busy || eap->nextcmd != NULL #ifdef FEAT_EVAL || eap->cstack->cs_idx >= 0 #endif ); /* ":source" read ex commands */ else if (do_source(fname, FALSE, DOSO_NONE) == FAIL) EMSG2(_(e_notopen), fname); } /* * ":source" and associated commands. */ /* * Structure used to store info for each sourced file. * It is shared between do_source() and getsourceline(). * This is required, because it needs to be handed to do_cmdline() and * sourcing can be done recursively. */ struct source_cookie { FILE *fp; /* opened file for sourcing */ char_u *nextline; /* if not NULL: line that was read ahead */ int finished; /* ":finish" used */ #if defined(USE_CRNL) || defined(USE_CR) int fileformat; /* EOL_UNKNOWN, EOL_UNIX or EOL_DOS */ int error; /* TRUE if LF found after CR-LF */ #endif #ifdef FEAT_EVAL linenr_T breakpoint; /* next line with breakpoint or zero */ char_u *fname; /* name of sourced file */ int dbg_tick; /* debug_tick when breakpoint was set */ int level; /* top nesting level of sourced file */ #endif #ifdef FEAT_MBYTE vimconv_T conv; /* type of conversion */ #endif }; #ifdef FEAT_EVAL /* * Return the address holding the next breakpoint line for a source cookie. */ linenr_T * source_breakpoint(cookie) void *cookie; { return &((struct source_cookie *)cookie)->breakpoint; } /* * Return the address holding the debug tick for a source cookie. */ int * source_dbg_tick(cookie) void *cookie; { return &((struct source_cookie *)cookie)->dbg_tick; } /* * Return the nesting level for a source cookie. */ int source_level(cookie) void *cookie; { return ((struct source_cookie *)cookie)->level; } #endif static char_u *get_one_sourceline __ARGS((struct source_cookie *sp)); #if (defined(WIN32) && defined(FEAT_CSCOPE)) || defined(HAVE_FD_CLOEXEC) # define USE_FOPEN_NOINH static FILE *fopen_noinh_readbin __ARGS((char *filename)); /* * Special function to open a file without handle inheritance. * When possible the handle is closed on exec(). */ static FILE * fopen_noinh_readbin(filename) char *filename; { # ifdef WIN32 int fd_tmp = mch_open(filename, O_RDONLY | O_BINARY | O_NOINHERIT, 0); # else int fd_tmp = mch_open(filename, O_RDONLY, 0); # endif if (fd_tmp == -1) return NULL; # ifdef HAVE_FD_CLOEXEC { int fdflags = fcntl(fd_tmp, F_GETFD); if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0) fcntl(fd_tmp, F_SETFD, fdflags | FD_CLOEXEC); } # endif return fdopen(fd_tmp, READBIN); } #endif /* * do_source: Read the file "fname" and execute its lines as EX commands. * * This function may be called recursively! * * return FAIL if file could not be opened, OK otherwise */ int do_source(fname, check_other, is_vimrc) char_u *fname; int check_other; /* check for .vimrc and _vimrc */ int is_vimrc; /* DOSO_ value */ { struct source_cookie cookie; char_u *save_sourcing_name; linenr_T save_sourcing_lnum; char_u *p; char_u *fname_exp; char_u *firstline = NULL; int retval = FAIL; #ifdef FEAT_EVAL scid_T save_current_SID; static scid_T last_current_SID = 0; void *save_funccalp; int save_debug_break_level = debug_break_level; scriptitem_T *si = NULL; # ifdef UNIX struct stat st; int stat_ok; # endif #endif #ifdef STARTUPTIME struct timeval tv_rel; struct timeval tv_start; #endif #ifdef FEAT_PROFILE proftime_T wait_start; #endif p = expand_env_save(fname); if (p == NULL) return retval; fname_exp = fix_fname(p); vim_free(p); if (fname_exp == NULL) return retval; if (mch_isdir(fname_exp)) { smsg((char_u *)_("Cannot source a directory: \"%s\""), fname); goto theend; } #ifdef FEAT_AUTOCMD /* Apply SourceCmd autocommands, they should get the file and source it. */ if (has_autocmd(EVENT_SOURCECMD, fname_exp, NULL) && apply_autocmds(EVENT_SOURCECMD, fname_exp, fname_exp, FALSE, curbuf)) { # ifdef FEAT_EVAL retval = aborting() ? FAIL : OK; # else retval = OK; # endif goto theend; } /* Apply SourcePre autocommands, they may get the file. */ apply_autocmds(EVENT_SOURCEPRE, fname_exp, fname_exp, FALSE, curbuf); #endif #ifdef USE_FOPEN_NOINH cookie.fp = fopen_noinh_readbin((char *)fname_exp); #else cookie.fp = mch_fopen((char *)fname_exp, READBIN); #endif if (cookie.fp == NULL && check_other) { /* * Try again, replacing file name ".vimrc" by "_vimrc" or vice versa, * and ".exrc" by "_exrc" or vice versa. */ p = gettail(fname_exp); if ((*p == '.' || *p == '_') && (STRICMP(p + 1, "vimrc") == 0 || STRICMP(p + 1, "gvimrc") == 0 || STRICMP(p + 1, "exrc") == 0)) { if (*p == '_') *p = '.'; else *p = '_'; #ifdef USE_FOPEN_NOINH cookie.fp = fopen_noinh_readbin((char *)fname_exp); #else cookie.fp = mch_fopen((char *)fname_exp, READBIN); #endif } } if (cookie.fp == NULL) { if (p_verbose > 0) { verbose_enter(); if (sourcing_name == NULL) smsg((char_u *)_("could not source \"%s\""), fname); else smsg((char_u *)_("line %ld: could not source \"%s\""), sourcing_lnum, fname); verbose_leave(); } goto theend; } /* * The file exists. * - In verbose mode, give a message. * - For a vimrc file, may want to set 'compatible', call vimrc_found(). */ if (p_verbose > 1) { verbose_enter(); if (sourcing_name == NULL) smsg((char_u *)_("sourcing \"%s\""), fname); else smsg((char_u *)_("line %ld: sourcing \"%s\""), sourcing_lnum, fname); verbose_leave(); } if (is_vimrc == DOSO_VIMRC) vimrc_found(fname_exp, (char_u *)"MYVIMRC"); else if (is_vimrc == DOSO_GVIMRC) vimrc_found(fname_exp, (char_u *)"MYGVIMRC"); #ifdef USE_CRNL /* If no automatic file format: Set default to CR-NL. */ if (*p_ffs == NUL) cookie.fileformat = EOL_DOS; else cookie.fileformat = EOL_UNKNOWN; cookie.error = FALSE; #endif #ifdef USE_CR /* If no automatic file format: Set default to CR. */ if (*p_ffs == NUL) cookie.fileformat = EOL_MAC; else cookie.fileformat = EOL_UNKNOWN; cookie.error = FALSE; #endif cookie.nextline = NULL; cookie.finished = FALSE; #ifdef FEAT_EVAL /* * Check if this script has a breakpoint. */ cookie.breakpoint = dbg_find_breakpoint(TRUE, fname_exp, (linenr_T)0); cookie.fname = fname_exp; cookie.dbg_tick = debug_tick; cookie.level = ex_nesting_level; #endif /* * Keep the sourcing name/lnum, for recursive calls. */ save_sourcing_name = sourcing_name; sourcing_name = fname_exp; save_sourcing_lnum = sourcing_lnum; sourcing_lnum = 0; #ifdef FEAT_MBYTE cookie.conv.vc_type = CONV_NONE; /* no conversion */ /* Read the first line so we can check for a UTF-8 BOM. */ firstline = getsourceline(0, (void *)&cookie, 0); if (firstline != NULL && STRLEN(firstline) >= 3 && firstline[0] == 0xef && firstline[1] == 0xbb && firstline[2] == 0xbf) { /* Found BOM; setup conversion, skip over BOM and recode the line. */ convert_setup(&cookie.conv, (char_u *)"utf-8", p_enc); p = string_convert(&cookie.conv, firstline + 3, NULL); if (p == NULL) p = vim_strsave(firstline + 3); if (p != NULL) { vim_free(firstline); firstline = p; } } #endif #ifdef STARTUPTIME if (time_fd != NULL) time_push(&tv_rel, &tv_start); #endif #ifdef FEAT_EVAL # ifdef FEAT_PROFILE if (do_profiling == PROF_YES) prof_child_enter(&wait_start); /* entering a child now */ # endif /* Don't use local function variables, if called from a function. * Also starts profiling timer for nested script. */ save_funccalp = save_funccal(); /* * Check if this script was sourced before to finds its SID. * If it's new, generate a new SID. */ save_current_SID = current_SID; # ifdef UNIX stat_ok = (mch_stat((char *)fname_exp, &st) >= 0); # endif for (current_SID = script_items.ga_len; current_SID > 0; --current_SID) { si = &SCRIPT_ITEM(current_SID); if (si->sn_name != NULL && ( # ifdef UNIX /* Compare dev/ino when possible, it catches symbolic * links. Also compare file names, the inode may change * when the file was edited. */ ((stat_ok && si->sn_dev_valid) && (si->sn_dev == st.st_dev && si->sn_ino == st.st_ino)) || # endif fnamecmp(si->sn_name, fname_exp) == 0)) break; } if (current_SID == 0) { current_SID = ++last_current_SID; if (ga_grow(&script_items, (int)(current_SID - script_items.ga_len)) == FAIL) goto almosttheend; while (script_items.ga_len < current_SID) { ++script_items.ga_len; SCRIPT_ITEM(script_items.ga_len).sn_name = NULL; # ifdef FEAT_PROFILE SCRIPT_ITEM(script_items.ga_len).sn_prof_on = FALSE; # endif } si = &SCRIPT_ITEM(current_SID); si->sn_name = fname_exp; fname_exp = NULL; # ifdef UNIX if (stat_ok) { si->sn_dev_valid = TRUE; si->sn_dev = st.st_dev; si->sn_ino = st.st_ino; } else si->sn_dev_valid = FALSE; # endif /* Allocate the local script variables to use for this script. */ new_script_vars(current_SID); } # ifdef FEAT_PROFILE if (do_profiling == PROF_YES) { int forceit; /* Check if we do profiling for this script. */ if (!si->sn_prof_on && has_profiling(TRUE, si->sn_name, &forceit)) { script_do_profile(si); si->sn_pr_force = forceit; } if (si->sn_prof_on) { ++si->sn_pr_count; profile_start(&si->sn_pr_start); profile_zero(&si->sn_pr_children); } } # endif #endif /* * Call do_cmdline, which will call getsourceline() to get the lines. */ do_cmdline(firstline, getsourceline, (void *)&cookie, DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_REPEAT); retval = OK; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) { /* Get "si" again, "script_items" may have been reallocated. */ si = &SCRIPT_ITEM(current_SID); if (si->sn_prof_on) { profile_end(&si->sn_pr_start); profile_sub_wait(&wait_start, &si->sn_pr_start); profile_add(&si->sn_pr_total, &si->sn_pr_start); profile_self(&si->sn_pr_self, &si->sn_pr_start, &si->sn_pr_children); } } #endif if (got_int) EMSG(_(e_interr)); sourcing_name = save_sourcing_name; sourcing_lnum = save_sourcing_lnum; if (p_verbose > 1) { verbose_enter(); smsg((char_u *)_("finished sourcing %s"), fname); if (sourcing_name != NULL) smsg((char_u *)_("continuing in %s"), sourcing_name); verbose_leave(); } #ifdef STARTUPTIME if (time_fd != NULL) { vim_snprintf((char *)IObuff, IOSIZE, "sourcing %s", fname); time_msg((char *)IObuff, &tv_start); time_pop(&tv_rel); } #endif #ifdef FEAT_EVAL /* * After a "finish" in debug mode, need to break at first command of next * sourced file. */ if (save_debug_break_level > ex_nesting_level && debug_break_level == ex_nesting_level) ++debug_break_level; #endif #ifdef FEAT_EVAL almosttheend: current_SID = save_current_SID; restore_funccal(save_funccalp); # ifdef FEAT_PROFILE if (do_profiling == PROF_YES) prof_child_exit(&wait_start); /* leaving a child now */ # endif #endif fclose(cookie.fp); vim_free(cookie.nextline); vim_free(firstline); #ifdef FEAT_MBYTE convert_setup(&cookie.conv, NULL, NULL); #endif theend: vim_free(fname_exp); return retval; } #if defined(FEAT_EVAL) || defined(PROTO) /* * ":scriptnames" */ void ex_scriptnames(eap) exarg_T *eap UNUSED; { int i; for (i = 1; i <= script_items.ga_len && !got_int; ++i) if (SCRIPT_ITEM(i).sn_name != NULL) { home_replace(NULL, SCRIPT_ITEM(i).sn_name, NameBuff, MAXPATHL, TRUE); smsg((char_u *)"%3d: %s", i, NameBuff); } } # if defined(BACKSLASH_IN_FILENAME) || defined(PROTO) /* * Fix slashes in the list of script names for 'shellslash'. */ void scriptnames_slash_adjust() { int i; for (i = 1; i <= script_items.ga_len; ++i) if (SCRIPT_ITEM(i).sn_name != NULL) slash_adjust(SCRIPT_ITEM(i).sn_name); } # endif /* * Get a pointer to a script name. Used for ":verbose set". */ char_u * get_scriptname(id) scid_T id; { if (id == SID_MODELINE) return (char_u *)_("modeline"); if (id == SID_CMDARG) return (char_u *)_("--cmd argument"); if (id == SID_CARG) return (char_u *)_("-c argument"); if (id == SID_ENV) return (char_u *)_("environment variable"); if (id == SID_ERROR) return (char_u *)_("error handler"); return SCRIPT_ITEM(id).sn_name; } # if defined(EXITFREE) || defined(PROTO) void free_scriptnames() { int i; for (i = script_items.ga_len; i > 0; --i) vim_free(SCRIPT_ITEM(i).sn_name); ga_clear(&script_items); } # endif #endif #if defined(USE_CR) || defined(PROTO) # if defined(__MSL__) && (__MSL__ >= 22) /* * Newer version of the Metrowerks library handle DOS and UNIX files * without help. * Test with earlier versions, MSL 2.2 is the library supplied with * Codewarrior Pro 2. */ char * fgets_cr(s, n, stream) char *s; int n; FILE *stream; { return fgets(s, n, stream); } # else /* * Version of fgets() which also works for lines ending in a <CR> only * (Macintosh format). * For older versions of the Metrowerks library. * At least CodeWarrior 9 needed this code. */ char * fgets_cr(s, n, stream) char *s; int n; FILE *stream; { int c = 0; int char_read = 0; while (!feof(stream) && c != '\r' && c != '\n' && char_read < n - 1) { c = fgetc(stream); s[char_read++] = c; /* If the file is in DOS format, we need to skip a NL after a CR. I * thought it was the other way around, but this appears to work... */ if (c == '\n') { c = fgetc(stream); if (c != '\r') ungetc(c, stream); } } s[char_read] = 0; if (char_read == 0) return NULL; if (feof(stream) && char_read == 1) return NULL; return s; } # endif #endif /* * Get one full line from a sourced file. * Called by do_cmdline() when it's called from do_source(). * * Return a pointer to the line in allocated memory. * Return NULL for end-of-file or some error. */ char_u * getsourceline(c, cookie, indent) int c UNUSED; void *cookie; int indent UNUSED; { struct source_cookie *sp = (struct source_cookie *)cookie; char_u *line; char_u *p; #ifdef FEAT_EVAL /* If breakpoints have been added/deleted need to check for it. */ if (sp->dbg_tick < debug_tick) { sp->breakpoint = dbg_find_breakpoint(TRUE, sp->fname, sourcing_lnum); sp->dbg_tick = debug_tick; } # ifdef FEAT_PROFILE if (do_profiling == PROF_YES) script_line_end(); # endif #endif /* * Get current line. If there is a read-ahead line, use it, otherwise get * one now. */ if (sp->finished) line = NULL; else if (sp->nextline == NULL) line = get_one_sourceline(sp); else { line = sp->nextline; sp->nextline = NULL; ++sourcing_lnum; } #ifdef FEAT_PROFILE if (line != NULL && do_profiling == PROF_YES) script_line_start(); #endif /* Only concatenate lines starting with a \ when 'cpoptions' doesn't * contain the 'C' flag. */ if (line != NULL && (vim_strchr(p_cpo, CPO_CONCAT) == NULL)) { /* compensate for the one line read-ahead */ --sourcing_lnum; /* Get the next line and concatenate it when it starts with a * backslash. We always need to read the next line, keep it in * sp->nextline. */ sp->nextline = get_one_sourceline(sp); if (sp->nextline != NULL && *(p = skipwhite(sp->nextline)) == '\\') { garray_T ga; ga_init2(&ga, (int)sizeof(char_u), 400); ga_concat(&ga, line); ga_concat(&ga, p + 1); for (;;) { vim_free(sp->nextline); sp->nextline = get_one_sourceline(sp); if (sp->nextline == NULL) break; p = skipwhite(sp->nextline); if (*p != '\\') break; /* Adjust the growsize to the current length to speed up * concatenating many lines. */ if (ga.ga_len > 400) { if (ga.ga_len > 8000) ga.ga_growsize = 8000; else ga.ga_growsize = ga.ga_len; } ga_concat(&ga, p + 1); } ga_append(&ga, NUL); vim_free(line); line = ga.ga_data; } } #ifdef FEAT_MBYTE if (line != NULL && sp->conv.vc_type != CONV_NONE) { char_u *s; /* Convert the encoding of the script line. */ s = string_convert(&sp->conv, line, NULL); if (s != NULL) { vim_free(line); line = s; } } #endif #ifdef FEAT_EVAL /* Did we encounter a breakpoint? */ if (sp->breakpoint != 0 && sp->breakpoint <= sourcing_lnum) { dbg_breakpoint(sp->fname, sourcing_lnum); /* Find next breakpoint. */ sp->breakpoint = dbg_find_breakpoint(TRUE, sp->fname, sourcing_lnum); sp->dbg_tick = debug_tick; } #endif return line; } static char_u * get_one_sourceline(sp) struct source_cookie *sp; { garray_T ga; int len; int c; char_u *buf; #ifdef USE_CRNL int has_cr; /* CR-LF found */ #endif #ifdef USE_CR char_u *scan; #endif int have_read = FALSE; /* use a growarray to store the sourced line */ ga_init2(&ga, 1, 250); /* * Loop until there is a finished line (or end-of-file). */ sourcing_lnum++; for (;;) { /* make room to read at least 120 (more) characters */ if (ga_grow(&ga, 120) == FAIL) break; buf = (char_u *)ga.ga_data; #ifdef USE_CR if (sp->fileformat == EOL_MAC) { if (fgets_cr((char *)buf + ga.ga_len, ga.ga_maxlen - ga.ga_len, sp->fp) == NULL) break; } else #endif if (fgets((char *)buf + ga.ga_len, ga.ga_maxlen - ga.ga_len, sp->fp) == NULL) break; len = ga.ga_len + (int)STRLEN(buf + ga.ga_len); #ifdef USE_CRNL /* Ignore a trailing CTRL-Z, when in Dos mode. Only recognize the * CTRL-Z by its own, or after a NL. */ if ( (len == 1 || (len >= 2 && buf[len - 2] == '\n')) && sp->fileformat == EOL_DOS && buf[len - 1] == Ctrl_Z) { buf[len - 1] = NUL; break; } #endif #ifdef USE_CR /* If the read doesn't stop on a new line, and there's * some CR then we assume a Mac format */ if (sp->fileformat == EOL_UNKNOWN) { if (buf[len - 1] != '\n' && vim_strchr(buf, '\r') != NULL) sp->fileformat = EOL_MAC; else sp->fileformat = EOL_UNIX; } if (sp->fileformat == EOL_MAC) { scan = vim_strchr(buf, '\r'); if (scan != NULL) { *scan = '\n'; if (*(scan + 1) != 0) { *(scan + 1) = 0; fseek(sp->fp, (long)(scan - buf - len + 1), SEEK_CUR); } } len = STRLEN(buf); } #endif have_read = TRUE; ga.ga_len = len; /* If the line was longer than the buffer, read more. */ if (ga.ga_maxlen - ga.ga_len == 1 && buf[len - 1] != '\n') continue; if (len >= 1 && buf[len - 1] == '\n') /* remove trailing NL */ { #ifdef USE_CRNL has_cr = (len >= 2 && buf[len - 2] == '\r'); if (sp->fileformat == EOL_UNKNOWN) { if (has_cr) sp->fileformat = EOL_DOS; else sp->fileformat = EOL_UNIX; } if (sp->fileformat == EOL_DOS) { if (has_cr) /* replace trailing CR */ { buf[len - 2] = '\n'; --len; --ga.ga_len; } else /* lines like ":map xx yy^M" will have failed */ { if (!sp->error) { msg_source(hl_attr(HLF_W)); EMSG(_("W15: Warning: Wrong line separator, ^M may be missing")); } sp->error = TRUE; sp->fileformat = EOL_UNIX; } } #endif /* The '\n' is escaped if there is an odd number of ^V's just * before it, first set "c" just before the 'V's and then check * len&c parities (is faster than ((len-c)%2 == 0)) -- Acevedo */ for (c = len - 2; c >= 0 && buf[c] == Ctrl_V; c--) ; if ((len & 1) != (c & 1)) /* escaped NL, read more */ { sourcing_lnum++; continue; } buf[len - 1] = NUL; /* remove the NL */ } /* * Check for ^C here now and then, so recursive :so can be broken. */ line_breakcheck(); break; } if (have_read) return (char_u *)ga.ga_data; vim_free(ga.ga_data); return NULL; } #if defined(FEAT_PROFILE) || defined(PROTO) /* * Called when starting to read a script line. * "sourcing_lnum" must be correct! * When skipping lines it may not actually be executed, but we won't find out * until later and we need to store the time now. */ void script_line_start() { scriptitem_T *si; sn_prl_T *pp; if (current_SID <= 0 || current_SID > script_items.ga_len) return; si = &SCRIPT_ITEM(current_SID); if (si->sn_prof_on && sourcing_lnum >= 1) { /* Grow the array before starting the timer, so that the time spent * here isn't counted. */ ga_grow(&si->sn_prl_ga, (int)(sourcing_lnum - si->sn_prl_ga.ga_len)); si->sn_prl_idx = sourcing_lnum - 1; while (si->sn_prl_ga.ga_len <= si->sn_prl_idx && si->sn_prl_ga.ga_len < si->sn_prl_ga.ga_maxlen) { /* Zero counters for a line that was not used before. */ pp = &PRL_ITEM(si, si->sn_prl_ga.ga_len); pp->snp_count = 0; profile_zero(&pp->sn_prl_total); profile_zero(&pp->sn_prl_self); ++si->sn_prl_ga.ga_len; } si->sn_prl_execed = FALSE; profile_start(&si->sn_prl_start); profile_zero(&si->sn_prl_children); profile_get_wait(&si->sn_prl_wait); } } /* * Called when actually executing a function line. */ void script_line_exec() { scriptitem_T *si; if (current_SID <= 0 || current_SID > script_items.ga_len) return; si = &SCRIPT_ITEM(current_SID); if (si->sn_prof_on && si->sn_prl_idx >= 0) si->sn_prl_execed = TRUE; } /* * Called when done with a function line. */ void script_line_end() { scriptitem_T *si; sn_prl_T *pp; if (current_SID <= 0 || current_SID > script_items.ga_len) return; si = &SCRIPT_ITEM(current_SID); if (si->sn_prof_on && si->sn_prl_idx >= 0 && si->sn_prl_idx < si->sn_prl_ga.ga_len) { if (si->sn_prl_execed) { pp = &PRL_ITEM(si, si->sn_prl_idx); ++pp->snp_count; profile_end(&si->sn_prl_start); profile_sub_wait(&si->sn_prl_wait, &si->sn_prl_start); profile_add(&pp->sn_prl_total, &si->sn_prl_start); profile_self(&pp->sn_prl_self, &si->sn_prl_start, &si->sn_prl_children); } si->sn_prl_idx = -1; } } #endif /* * ":scriptencoding": Set encoding conversion for a sourced script. * Without the multi-byte feature it's simply ignored. */ void ex_scriptencoding(eap) exarg_T *eap UNUSED; { #ifdef FEAT_MBYTE struct source_cookie *sp; char_u *name; if (!getline_equal(eap->getline, eap->cookie, getsourceline)) { EMSG(_("E167: :scriptencoding used outside of a sourced file")); return; } if (*eap->arg != NUL) { name = enc_canonize(eap->arg); if (name == NULL) /* out of memory */ return; } else name = eap->arg; /* Setup for conversion from the specified encoding to 'encoding'. */ sp = (struct source_cookie *)getline_cookie(eap->getline, eap->cookie); convert_setup(&sp->conv, name, p_enc); if (name != eap->arg) vim_free(name); #endif } #if defined(FEAT_EVAL) || defined(PROTO) /* * ":finish": Mark a sourced file as finished. */ void ex_finish(eap) exarg_T *eap; { if (getline_equal(eap->getline, eap->cookie, getsourceline)) do_finish(eap, FALSE); else EMSG(_("E168: :finish used outside of a sourced file")); } /* * Mark a sourced file as finished. Possibly makes the ":finish" pending. * Also called for a pending finish at the ":endtry" or after returning from * an extra do_cmdline(). "reanimate" is used in the latter case. */ void do_finish(eap, reanimate) exarg_T *eap; int reanimate; { int idx; if (reanimate) ((struct source_cookie *)getline_cookie(eap->getline, eap->cookie))->finished = FALSE; /* * Cleanup (and inactivate) conditionals, but stop when a try conditional * not in its finally clause (which then is to be executed next) is found. * In this case, make the ":finish" pending for execution at the ":endtry". * Otherwise, finish normally. */ idx = cleanup_conditionals(eap->cstack, 0, TRUE); if (idx >= 0) { eap->cstack->cs_pending[idx] = CSTP_FINISH; report_make_pending(CSTP_FINISH, NULL); } else ((struct source_cookie *)getline_cookie(eap->getline, eap->cookie))->finished = TRUE; } /* * Return TRUE when a sourced file had the ":finish" command: Don't give error * message for missing ":endif". * Return FALSE when not sourcing a file. */ int source_finished(fgetline, cookie) char_u *(*fgetline) __ARGS((int, void *, int)); void *cookie; { return (getline_equal(fgetline, cookie, getsourceline) && ((struct source_cookie *)getline_cookie( fgetline, cookie))->finished); } #endif #if defined(FEAT_LISTCMDS) || defined(PROTO) /* * ":checktime [buffer]" */ void ex_checktime(eap) exarg_T *eap; { buf_T *buf; int save_no_check_timestamps = no_check_timestamps; no_check_timestamps = 0; if (eap->addr_count == 0) /* default is all buffers */ check_timestamps(FALSE); else { buf = buflist_findnr((int)eap->line2); if (buf != NULL) /* cannot happen? */ (void)buf_check_timestamp(buf, FALSE); } no_check_timestamps = save_no_check_timestamps; } #endif #if (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \ && (defined(FEAT_EVAL) || defined(FEAT_MULTI_LANG)) # define HAVE_GET_LOCALE_VAL static char *get_locale_val __ARGS((int what)); static char * get_locale_val(what) int what; { char *loc; /* Obtain the locale value from the libraries. For DJGPP this is * redefined and it doesn't use the arguments. */ loc = setlocale(what, NULL); # ifdef WIN32 if (loc != NULL) { char_u *p; /* setocale() returns something like "LC_COLLATE=<name>;LC_..." when * one of the values (e.g., LC_CTYPE) differs. */ p = vim_strchr(loc, '='); if (p != NULL) { loc = ++p; while (*p != NUL) /* remove trailing newline */ { if (*p < ' ' || *p == ';') { *p = NUL; break; } ++p; } } } # endif return loc; } #endif #ifdef WIN32 /* * On MS-Windows locale names are strings like "German_Germany.1252", but * gettext expects "de". Try to translate one into another here for a few * supported languages. */ static char_u * gettext_lang(char_u *name) { int i; static char *(mtable[]) = { "afrikaans", "af", "czech", "cs", "dutch", "nl", "german", "de", "english_united kingdom", "en_GB", "spanish", "es", "french", "fr", "italian", "it", "japanese", "ja", "korean", "ko", "norwegian", "no", "polish", "pl", "russian", "ru", "slovak", "sk", "swedish", "sv", "ukrainian", "uk", "chinese_china", "zh_CN", "chinese_taiwan", "zh_TW", NULL}; for (i = 0; mtable[i] != NULL; i += 2) if (STRNICMP(mtable[i], name, STRLEN(mtable[i])) == 0) return mtable[i + 1]; return name; } #endif #if defined(FEAT_MULTI_LANG) || defined(PROTO) /* * Obtain the current messages language. Used to set the default for * 'helplang'. May return NULL or an empty string. */ char_u * get_mess_lang() { char_u *p; # ifdef HAVE_GET_LOCALE_VAL # if defined(LC_MESSAGES) p = (char_u *)get_locale_val(LC_MESSAGES); # else /* This is necessary for Win32, where LC_MESSAGES is not defined and $LANG * may be set to the LCID number. LC_COLLATE is the best guess, LC_TIME * and LC_MONETARY may be set differently for a Japanese working in the * US. */ p = (char_u *)get_locale_val(LC_COLLATE); # endif # else p = mch_getenv((char_u *)"LC_ALL"); if (p == NULL || *p == NUL) { p = mch_getenv((char_u *)"LC_MESSAGES"); if (p == NULL || *p == NUL) p = mch_getenv((char_u *)"LANG"); } # endif # ifdef WIN32 p = gettext_lang(p); # endif return p; } #endif /* Complicated #if; matches with where get_mess_env() is used below. */ #if (defined(FEAT_EVAL) && !((defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \ && defined(LC_MESSAGES))) \ || ((defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \ && (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE)) \ && !defined(LC_MESSAGES)) static char_u *get_mess_env __ARGS((void)); /* * Get the language used for messages from the environment. */ static char_u * get_mess_env() { char_u *p; p = mch_getenv((char_u *)"LC_ALL"); if (p == NULL || *p == NUL) { p = mch_getenv((char_u *)"LC_MESSAGES"); if (p == NULL || *p == NUL) { p = mch_getenv((char_u *)"LANG"); if (p != NULL && VIM_ISDIGIT(*p)) p = NULL; /* ignore something like "1043" */ # ifdef HAVE_GET_LOCALE_VAL if (p == NULL || *p == NUL) p = (char_u *)get_locale_val(LC_CTYPE); # endif } } return p; } #endif #if defined(FEAT_EVAL) || defined(PROTO) /* * Set the "v:lang" variable according to the current locale setting. * Also do "v:lc_time"and "v:ctype". */ void set_lang_var() { char_u *loc; # ifdef HAVE_GET_LOCALE_VAL loc = (char_u *)get_locale_val(LC_CTYPE); # else /* setlocale() not supported: use the default value */ loc = (char_u *)"C"; # endif set_vim_var_string(VV_CTYPE, loc, -1); /* When LC_MESSAGES isn't defined use the value from $LC_MESSAGES, fall * back to LC_CTYPE if it's empty. */ # if defined(HAVE_GET_LOCALE_VAL) && defined(LC_MESSAGES) loc = (char_u *)get_locale_val(LC_MESSAGES); # else loc = get_mess_env(); # endif set_vim_var_string(VV_LANG, loc, -1); # ifdef HAVE_GET_LOCALE_VAL loc = (char_u *)get_locale_val(LC_TIME); # endif set_vim_var_string(VV_LC_TIME, loc, -1); } #endif #if (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \ && (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE)) /* * ":language": Set the language (locale). */ void ex_language(eap) exarg_T *eap; { char *loc; char_u *p; char_u *name; int what = LC_ALL; char *whatstr = ""; #ifdef LC_MESSAGES # define VIM_LC_MESSAGES LC_MESSAGES #else # define VIM_LC_MESSAGES 6789 #endif name = eap->arg; /* Check for "messages {name}", "ctype {name}" or "time {name}" argument. * Allow abbreviation, but require at least 3 characters to avoid * confusion with a two letter language name "me" or "ct". */ p = skiptowhite(eap->arg); if ((*p == NUL || vim_iswhite(*p)) && p - eap->arg >= 3) { if (STRNICMP(eap->arg, "messages", p - eap->arg) == 0) { what = VIM_LC_MESSAGES; name = skipwhite(p); whatstr = "messages "; } else if (STRNICMP(eap->arg, "ctype", p - eap->arg) == 0) { what = LC_CTYPE; name = skipwhite(p); whatstr = "ctype "; } else if (STRNICMP(eap->arg, "time", p - eap->arg) == 0) { what = LC_TIME; name = skipwhite(p); whatstr = "time "; } } if (*name == NUL) { #ifndef LC_MESSAGES if (what == VIM_LC_MESSAGES) p = get_mess_env(); else #endif p = (char_u *)setlocale(what, NULL); if (p == NULL || *p == NUL) p = (char_u *)"Unknown"; smsg((char_u *)_("Current %slanguage: \"%s\""), whatstr, p); } else { #ifndef LC_MESSAGES if (what == VIM_LC_MESSAGES) loc = ""; else #endif { loc = setlocale(what, (char *)name); #if defined(FEAT_FLOAT) && defined(LC_NUMERIC) /* Make sure strtod() uses a decimal point, not a comma. */ setlocale(LC_NUMERIC, "C"); #endif } if (loc == NULL) EMSG2(_("E197: Cannot set language to \"%s\""), name); else { #ifdef HAVE_NL_MSG_CAT_CNTR /* Need to do this for GNU gettext, otherwise cached translations * will be used again. */ extern int _nl_msg_cat_cntr; ++_nl_msg_cat_cntr; #endif /* Reset $LC_ALL, otherwise it would overrule everything. */ vim_setenv((char_u *)"LC_ALL", (char_u *)""); if (what != LC_TIME) { /* Tell gettext() what to translate to. It apparently doesn't * use the currently effective locale. Also do this when * FEAT_GETTEXT isn't defined, so that shell commands use this * value. */ if (what == LC_ALL) { vim_setenv((char_u *)"LANG", name); # ifdef WIN32 /* Apparently MS-Windows printf() may cause a crash when * we give it 8-bit text while it's expecting text in the * current locale. This call avoids that. */ setlocale(LC_CTYPE, "C"); # endif } if (what != LC_CTYPE) { char_u *mname; #ifdef WIN32 mname = gettext_lang(name); #else mname = name; #endif vim_setenv((char_u *)"LC_MESSAGES", mname); #ifdef FEAT_MULTI_LANG set_helplang_default(mname); #endif } } # ifdef FEAT_EVAL /* Set v:lang, v:lc_time and v:ctype to the final result. */ set_lang_var(); # endif # ifdef FEAT_TITLE maketitle(); # endif } } } # if defined(FEAT_CMDL_COMPL) || defined(PROTO) static char_u **locales = NULL; /* Array of all available locales */ static int did_init_locales = FALSE; static void init_locales __ARGS((void)); static char_u **find_locales __ARGS((void)); /* * Lazy initialization of all available locales. */ static void init_locales() { if (!did_init_locales) { did_init_locales = TRUE; locales = find_locales(); } } /* Return an array of strings for all available locales + NULL for the * last element. Return NULL in case of error. */ static char_u ** find_locales() { garray_T locales_ga; char_u *loc; /* Find all available locales by running command "locale -a". If this * doesn't work we won't have completion. */ char_u *locale_a = get_cmd_output((char_u *)"locale -a", NULL, SHELL_SILENT); if (locale_a == NULL) return NULL; ga_init2(&locales_ga, sizeof(char_u *), 20); /* Transform locale_a string where each locale is separated by "\n" * into an array of locale strings. */ loc = (char_u *)strtok((char *)locale_a, "\n"); while (loc != NULL) { if (ga_grow(&locales_ga, 1) == FAIL) break; loc = vim_strsave(loc); if (loc == NULL) break; ((char_u **)locales_ga.ga_data)[locales_ga.ga_len++] = loc; loc = (char_u *)strtok(NULL, "\n"); } vim_free(locale_a); if (ga_grow(&locales_ga, 1) == FAIL) { ga_clear(&locales_ga); return NULL; } ((char_u **)locales_ga.ga_data)[locales_ga.ga_len] = NULL; return (char_u **)locales_ga.ga_data; } # if defined(EXITFREE) || defined(PROTO) void free_locales() { int i; if (locales != NULL) { for (i = 0; locales[i] != NULL; i++) vim_free(locales[i]); vim_free(locales); locales = NULL; } } # endif /* * Function given to ExpandGeneric() to obtain the possible arguments of the * ":language" command. */ char_u * get_lang_arg(xp, idx) expand_T *xp UNUSED; int idx; { if (idx == 0) return (char_u *)"messages"; if (idx == 1) return (char_u *)"ctype"; if (idx == 2) return (char_u *)"time"; init_locales(); if (locales == NULL) return NULL; return locales[idx - 3]; } /* * Function given to ExpandGeneric() to obtain the available locales. */ char_u * get_locales(xp, idx) expand_T *xp UNUSED; int idx; { init_locales(); if (locales == NULL) return NULL; return locales[idx]; } # endif #endif
zyz2011-vim
src/ex_cmds2.c
C
gpl2
100,323
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. */ /* * MSDOS Machine-dependent things. */ #include "os_dos.h" /* common MS-DOS and Win32 stuff */ #define BINARY_FILE_IO #define USE_EXE_NAME /* use argv[0] for $VIM */ #define SYNC_DUP_CLOSE /* sync() a file with dup() and close() */ #define USE_TERM_CONSOLE #ifdef DJGPP # include <fcntl.h> /* defines _USE_LFN */ # define USE_LONG_FNAME _USE_LFN /* decide at run time */ # define USE_FNAME_CASE # define HAVE_PUTENV # define HAVE_STDARG_H #else # define SHORT_FNAME /* always 8.3 file name */ #endif #define HAVE_STDLIB_H #define HAVE_STRING_H #define HAVE_FCNTL_H #define HAVE_STRCSPN #define HAVE_STRICMP #define HAVE_STRFTIME /* guessed */ #define HAVE_STRNICMP #define HAVE_MEMSET #define HAVE_QSORT #define HAVE_ST_MODE /* have stat.st_mode */ #define HAVE_MATH_H #if defined(__DATE__) && defined(__TIME__) # define HAVE_DATE_TIME #endif #define BREAKCHECK_SKIP 1 /* call mch_breakcheck() each time, it's fast */ #define HAVE_AVAIL_MEM /* * Borland C++ 3.1 doesn't have _RTLENTRYF */ #ifdef __BORLANDC__ # if __BORLANDC__ < 0x450 # define _RTLENTRYF # endif #endif #define FNAME_ILLEGAL "\"*?><|" /* illegal characters in a file name */ #include <dos.h> #include <dir.h> #include <time.h> #ifdef DJGPP # include <unistd.h> # define HAVE_LOCALE_H # define setlocale(c, p) djgpp_setlocale() #endif #ifndef DJGPP typedef long off_t; #endif /* * Try several directories to put the temp files. */ #define TEMPDIRNAMES "$TMP", "$TEMP", "c:\\TMP", "c:\\TEMP", "" #define TEMPNAMELEN 128 #ifndef DFLT_MAXMEM # define DFLT_MAXMEM 256 /* use up to 256Kbyte for buffer */ #endif #ifndef DFLT_MAXMEMTOT # define DFLT_MAXMEMTOT 0 /* decide in set_init */ #endif #ifdef DJGPP # define BASENAMELEN (_USE_LFN?250:8) /* length of base of file name */ #else # define BASENAMELEN 8 /* length of base of file name */ #endif /* codes for msdos mouse event */ #define MSDOS_MOUSE_LEFT 0x01 #define MSDOS_MOUSE_RIGHT 0x02 #define MSDOS_MOUSE_MIDDLE 0x04 #ifdef DJGPP int mch_rename(const char *OldFile, const char *NewFile); #else # define mch_rename(src, dst) rename(src, dst) #endif #ifdef DJGPP # define vim_mkdir(x, y) mkdir((char *)(x), y) #else # define vim_mkdir(x, y) mkdir((char *)(x)) #endif #define mch_rmdir(x) rmdir((char *)(x)) #define mch_setenv(name, val, x) setenv(name, val, x)
zyz2011-vim
src/os_msdos.h
C
gpl2
2,539
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. */ /* * Arabic characters are categorized into following types: * * Isolated - iso-8859-6 form char denoted with a_* * Initial - unicode form-B start char denoted with a_i_* * Medial - unicode form-B middle char denoted with a_m_* * Final - unicode form-B final char denoted with a_f_* * Stand-Alone - unicode form-B isolated char denoted with a_s_* (NOT USED) * * -- * * Author: Nadim Shaikli & Isam Bayazidi * - (based on Unicode) * */ /* * Arabic ISO-10646-1 character set definition */ /* * Arabic ISO-8859-6 (subset of 10646; 0600 - 06FF) */ #define a_COMMA 0x060C #define a_SEMICOLON 0x061B #define a_QUESTION 0x061F #define a_HAMZA 0x0621 #define a_ALEF_MADDA 0x0622 #define a_ALEF_HAMZA_ABOVE 0x0623 #define a_WAW_HAMZA 0x0624 #define a_ALEF_HAMZA_BELOW 0x0625 #define a_YEH_HAMZA 0x0626 #define a_ALEF 0x0627 #define a_BEH 0x0628 #define a_TEH_MARBUTA 0x0629 #define a_TEH 0x062a #define a_THEH 0x062b #define a_JEEM 0x062c #define a_HAH 0x062d #define a_KHAH 0x062e #define a_DAL 0x062f #define a_THAL 0x0630 #define a_REH 0x0631 #define a_ZAIN 0x0632 #define a_SEEN 0x0633 #define a_SHEEN 0x0634 #define a_SAD 0x0635 #define a_DAD 0x0636 #define a_TAH 0x0637 #define a_ZAH 0x0638 #define a_AIN 0x0639 #define a_GHAIN 0x063a #define a_TATWEEL 0x0640 #define a_FEH 0x0641 #define a_QAF 0x0642 #define a_KAF 0x0643 #define a_LAM 0x0644 #define a_MEEM 0x0645 #define a_NOON 0x0646 #define a_HEH 0x0647 #define a_WAW 0x0648 #define a_ALEF_MAKSURA 0x0649 #define a_YEH 0x064a #define a_FATHATAN 0x064b #define a_DAMMATAN 0x064c #define a_KASRATAN 0x064d #define a_FATHA 0x064e #define a_DAMMA 0x064f #define a_KASRA 0x0650 #define a_SHADDA 0x0651 #define a_SUKUN 0x0652 #define a_MADDA_ABOVE 0x0653 #define a_HAMZA_ABOVE 0x0654 #define a_HAMZA_BELOW 0x0655 #define a_ZERO 0x0660 #define a_ONE 0x0661 #define a_TWO 0x0662 #define a_THREE 0x0663 #define a_FOUR 0x0664 #define a_FIVE 0x0665 #define a_SIX 0x0666 #define a_SEVEN 0x0667 #define a_EIGHT 0x0668 #define a_NINE 0x0669 #define a_PERCENT 0x066a #define a_DECIMAL 0x066b #define a_THOUSANDS 0x066c #define a_STAR 0x066d #define a_MINI_ALEF 0x0670 /* Rest of 8859-6 does not relate to Arabic */ /* * Arabic Presentation Form-B (subset of 10646; FE70 - FEFF) * * s -> isolated * i -> initial * m -> medial * f -> final * */ #define a_s_FATHATAN 0xfe70 #define a_m_TATWEEL_FATHATAN 0xfe71 #define a_s_DAMMATAN 0xfe72 #define a_s_KASRATAN 0xfe74 #define a_s_FATHA 0xfe76 #define a_m_FATHA 0xfe77 #define a_s_DAMMA 0xfe78 #define a_m_DAMMA 0xfe79 #define a_s_KASRA 0xfe7a #define a_m_KASRA 0xfe7b #define a_s_SHADDA 0xfe7c #define a_m_SHADDA 0xfe7d #define a_s_SUKUN 0xfe7e #define a_m_SUKUN 0xfe7f #define a_s_HAMZA 0xfe80 #define a_s_ALEF_MADDA 0xfe81 #define a_f_ALEF_MADDA 0xfe82 #define a_s_ALEF_HAMZA_ABOVE 0xfe83 #define a_f_ALEF_HAMZA_ABOVE 0xfe84 #define a_s_WAW_HAMZA 0xfe85 #define a_f_WAW_HAMZA 0xfe86 #define a_s_ALEF_HAMZA_BELOW 0xfe87 #define a_f_ALEF_HAMZA_BELOW 0xfe88 #define a_s_YEH_HAMZA 0xfe89 #define a_f_YEH_HAMZA 0xfe8a #define a_i_YEH_HAMZA 0xfe8b #define a_m_YEH_HAMZA 0xfe8c #define a_s_ALEF 0xfe8d #define a_f_ALEF 0xfe8e #define a_s_BEH 0xfe8f #define a_f_BEH 0xfe90 #define a_i_BEH 0xfe91 #define a_m_BEH 0xfe92 #define a_s_TEH_MARBUTA 0xfe93 #define a_f_TEH_MARBUTA 0xfe94 #define a_s_TEH 0xfe95 #define a_f_TEH 0xfe96 #define a_i_TEH 0xfe97 #define a_m_TEH 0xfe98 #define a_s_THEH 0xfe99 #define a_f_THEH 0xfe9a #define a_i_THEH 0xfe9b #define a_m_THEH 0xfe9c #define a_s_JEEM 0xfe9d #define a_f_JEEM 0xfe9e #define a_i_JEEM 0xfe9f #define a_m_JEEM 0xfea0 #define a_s_HAH 0xfea1 #define a_f_HAH 0xfea2 #define a_i_HAH 0xfea3 #define a_m_HAH 0xfea4 #define a_s_KHAH 0xfea5 #define a_f_KHAH 0xfea6 #define a_i_KHAH 0xfea7 #define a_m_KHAH 0xfea8 #define a_s_DAL 0xfea9 #define a_f_DAL 0xfeaa #define a_s_THAL 0xfeab #define a_f_THAL 0xfeac #define a_s_REH 0xfead #define a_f_REH 0xfeae #define a_s_ZAIN 0xfeaf #define a_f_ZAIN 0xfeb0 #define a_s_SEEN 0xfeb1 #define a_f_SEEN 0xfeb2 #define a_i_SEEN 0xfeb3 #define a_m_SEEN 0xfeb4 #define a_s_SHEEN 0xfeb5 #define a_f_SHEEN 0xfeb6 #define a_i_SHEEN 0xfeb7 #define a_m_SHEEN 0xfeb8 #define a_s_SAD 0xfeb9 #define a_f_SAD 0xfeba #define a_i_SAD 0xfebb #define a_m_SAD 0xfebc #define a_s_DAD 0xfebd #define a_f_DAD 0xfebe #define a_i_DAD 0xfebf #define a_m_DAD 0xfec0 #define a_s_TAH 0xfec1 #define a_f_TAH 0xfec2 #define a_i_TAH 0xfec3 #define a_m_TAH 0xfec4 #define a_s_ZAH 0xfec5 #define a_f_ZAH 0xfec6 #define a_i_ZAH 0xfec7 #define a_m_ZAH 0xfec8 #define a_s_AIN 0xfec9 #define a_f_AIN 0xfeca #define a_i_AIN 0xfecb #define a_m_AIN 0xfecc #define a_s_GHAIN 0xfecd #define a_f_GHAIN 0xfece #define a_i_GHAIN 0xfecf #define a_m_GHAIN 0xfed0 #define a_s_FEH 0xfed1 #define a_f_FEH 0xfed2 #define a_i_FEH 0xfed3 #define a_m_FEH 0xfed4 #define a_s_QAF 0xfed5 #define a_f_QAF 0xfed6 #define a_i_QAF 0xfed7 #define a_m_QAF 0xfed8 #define a_s_KAF 0xfed9 #define a_f_KAF 0xfeda #define a_i_KAF 0xfedb #define a_m_KAF 0xfedc #define a_s_LAM 0xfedd #define a_f_LAM 0xfede #define a_i_LAM 0xfedf #define a_m_LAM 0xfee0 #define a_s_MEEM 0xfee1 #define a_f_MEEM 0xfee2 #define a_i_MEEM 0xfee3 #define a_m_MEEM 0xfee4 #define a_s_NOON 0xfee5 #define a_f_NOON 0xfee6 #define a_i_NOON 0xfee7 #define a_m_NOON 0xfee8 #define a_s_HEH 0xfee9 #define a_f_HEH 0xfeea #define a_i_HEH 0xfeeb #define a_m_HEH 0xfeec #define a_s_WAW 0xfeed #define a_f_WAW 0xfeee #define a_s_ALEF_MAKSURA 0xfeef #define a_f_ALEF_MAKSURA 0xfef0 #define a_s_YEH 0xfef1 #define a_f_YEH 0xfef2 #define a_i_YEH 0xfef3 #define a_m_YEH 0xfef4 #define a_s_LAM_ALEF_MADDA_ABOVE 0xfef5 #define a_f_LAM_ALEF_MADDA_ABOVE 0xfef6 #define a_s_LAM_ALEF_HAMZA_ABOVE 0xfef7 #define a_f_LAM_ALEF_HAMZA_ABOVE 0xfef8 #define a_s_LAM_ALEF_HAMZA_BELOW 0xfef9 #define a_f_LAM_ALEF_HAMZA_BELOW 0xfefa #define a_s_LAM_ALEF 0xfefb #define a_f_LAM_ALEF 0xfefc #define a_BYTE_ORDER_MARK 0xfeff /* Range of Arabic characters that might be shaped. */ #define ARABIC_CHAR(c) ((c) >= a_HAMZA && (c) <= a_MINI_ALEF)
zyz2011-vim
src/arabic.h
C
gpl2
6,737
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. */ /* * os_unixx.h -- include files that are only used in os_unix.c */ /* * Stuff for signals */ #if defined(HAVE_SIGSET) && !defined(signal) # define signal sigset #endif /* sun's sys/ioctl.h redefines symbols from termio world */ #if defined(HAVE_SYS_IOCTL_H) && !defined(sun) # include <sys/ioctl.h> #endif #ifndef USE_SYSTEM /* use fork/exec to start the shell */ # if defined(HAVE_SYS_WAIT_H) || defined(HAVE_UNION_WAIT) # include <sys/wait.h> # endif # ifndef WEXITSTATUS # ifdef HAVE_UNION_WAIT # define WEXITSTATUS(stat_val) ((stat_val).w_T.w_Retcode) # else # define WEXITSTATUS(stat_val) (((stat_val) >> 8) & 0377) # endif # endif # ifndef WIFEXITED # ifdef HAVE_UNION_WAIT # define WIFEXITED(stat_val) ((stat_val).w_T.w_Termsig == 0) # else # define WIFEXITED(stat_val) (((stat_val) & 255) == 0) # endif # endif #endif /* !USE_SYSTEM */ #ifdef HAVE_STROPTS_H #ifdef sinix #define buf_T __system_buf_t__ #endif # include <stropts.h> #ifdef sinix #undef buf_T #endif #endif #ifdef HAVE_STRING_H # include <string.h> #endif #ifdef HAVE_SYS_STREAM_H # include <sys/stream.h> #endif #ifdef HAVE_SYS_UTSNAME_H # include <sys/utsname.h> #endif #ifdef HAVE_SYS_SYSTEMINFO_H /* * foolish Sinix <sys/systeminfo.h> uses SYS_NMLN but doesn't include * <limits.h>, where it is defined. Perhaps other systems have the same * problem? Include it here. -- Slootman */ # if defined(HAVE_LIMITS_H) && !defined(_LIMITS_H) # include <limits.h> /* for SYS_NMLN (Sinix 5.41 / Unix SysV.4) */ # endif /* Define SYS_NMLN ourselves if it still isn't defined (for CrayT3E). */ # ifndef SYS_NMLN # define SYS_NMLN 32 # endif # include <sys/systeminfo.h> /* for sysinfo */ #endif /* * We use termios.h if both termios.h and termio.h are available. * Termios is supposed to be a superset of termio.h. Don't include them both, * it may give problems on some systems (e.g. hpux). * I don't understand why we don't want termios.h for apollo. */ #if defined(HAVE_TERMIOS_H) && !defined(apollo) # include <termios.h> #else # ifdef HAVE_TERMIO_H # include <termio.h> # else # ifdef HAVE_SGTTY_H # include <sgtty.h> # endif # endif #endif #ifdef HAVE_SYS_PTEM_H # include <sys/ptem.h> /* must be after termios.h for Sinix */ # ifndef _IO_PTEM_H /* For UnixWare that should check for _IO_PT_PTEM_H */ # define _IO_PTEM_H # endif #endif /* shared library access */ #if defined(HAVE_DLFCN_H) && defined(USE_DLOPEN) # ifdef __MVS__ /* needed to define RTLD_LAZY (Anthony Giorgio) */ # define __SUSV3 # endif # include <dlfcn.h> #else # if defined(HAVE_DL_H) && defined(HAVE_SHL_LOAD) # include <dl.h> # endif #endif
zyz2011-vim
src/os_unixx.h
C
gpl2
2,863
/* vi:set ts=8 sts=4 sw=4: */ /* * Copyright 1989 Software Research Associates, Inc., Tokyo, Japan * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose and without fee is hereby granted, provided * that the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Software Research Associates not be used * in advertising or publicity pertaining to distribution of the software * without specific, written prior permission. Software Research Associates * makes no representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * SOFTWARE RESEARCH ASSOCIATES DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, * IN NO EVENT SHALL SOFTWARE RESEARCH ASSOCIATES BE LIABLE FOR ANY SPECIAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. * * Author: Erik M. van der Poel * Software Research Associates, Inc., Tokyo, Japan * erik@sra.co.jp */ /* * Author's addresses: * erik@sra.co.jp * erik%sra.co.jp@uunet.uu.net * erik%sra.co.jp@mcvax.uucp * try junet instead of co.jp * Erik M. van der Poel * Software Research Associates, Inc. * 1-1-1 Hirakawa-cho, Chiyoda-ku * Tokyo 102 Japan. TEL +81-3-234-2692 */ /* * Heavely modified for Vim by Bram Moolenaar */ #include "vim.h" /* Only include this when using the file browser */ #ifdef FEAT_BROWSE /* Weird complication: for "make lint" Text.h doesn't combine with Xm.h */ #if defined(FEAT_GUI_MOTIF) && defined(FMT8BIT) # undef FMT8BIT #endif #ifndef FEAT_GUI_NEXTAW # include "gui_at_sb.h" #endif /***************** SFinternal.h */ #include <X11/Intrinsic.h> #include <X11/StringDefs.h> #include <X11/Xos.h> #ifdef FEAT_GUI_NEXTAW # include <X11/neXtaw/Text.h> # include <X11/neXtaw/AsciiText.h> # include <X11/neXtaw/Scrollbar.h> #else # include <X11/Xaw/Text.h> # include <X11/Xaw/AsciiText.h> #endif #define SEL_FILE_CANCEL -1 #define SEL_FILE_OK 0 #define SEL_FILE_NULL 1 #define SEL_FILE_TEXT 2 #define SF_DO_SCROLL 1 #define SF_DO_NOT_SCROLL 0 typedef struct { int statDone; char *real; char *shown; } SFEntry; typedef struct { char *dir; char *path; SFEntry *entries; int nEntries; int vOrigin; int nChars; int hOrigin; int changed; int beginSelection; int endSelection; time_t mtime; } SFDir; static char SFstartDir[MAXPATHL], SFcurrentPath[MAXPATHL], SFcurrentDir[MAXPATHL]; static Widget selFile, selFileField, selFileForm, selFileHScroll, selFileHScrolls[3], selFileLists[3], selFileOK, selFileCancel, selFilePrompt, selFileVScrolls[3]; static Display *SFdisplay; static int SFcharWidth, SFcharAscent, SFcharHeight; static SFDir *SFdirs = NULL; static int SFdirEnd; static int SFdirPtr; static Pixel SFfore, SFback; static Atom SFwmDeleteWindow; static XSegment SFsegs[2], SFcompletionSegs[2]; static XawTextPosition SFtextPos; static int SFupperX, SFlowerY, SFupperY; static int SFtextX, SFtextYoffset; static int SFentryWidth, SFentryHeight; static int SFlineToTextH = 3; static int SFlineToTextV = 3; static int SFbesideText = 3; static int SFaboveAndBelowText = 2; static int SFcharsPerEntry = 15; static int SFlistSize = 10; static int SFcurrentInvert[3] = { -1, -1, -1 }; static int SFworkProcAdded = 0; static XtAppContext SFapp; static int SFpathScrollWidth, SFvScrollHeight, SFhScrollWidth; #ifdef FEAT_XFONTSET static char SFtextBuffer[MAXPATHL*sizeof(wchar_t)]; #else static char SFtextBuffer[MAXPATHL]; #endif static int SFbuttonPressed = 0; static XtIntervalId SFdirModTimerId; static int (*SFfunc)(); static int SFstatus = SEL_FILE_NULL; /***************** static functions */ static void SFsetText __ARGS((char *path)); static void SFtextChanged __ARGS((void)); static char *SFgetText __ARGS((void)); static void SFupdatePath __ARGS((void)); static int SFgetDir __ARGS((SFDir *dir)); static void SFdrawLists __ARGS((int doScroll)); static void SFdrawList __ARGS((int n, int doScroll)); static void SFclearList __ARGS((int n, int doScroll)); static void SFbuttonPressList __ARGS((Widget w, int n, XButtonPressedEvent *event)); static void SFbuttonReleaseList __ARGS((Widget w, int n, XButtonReleasedEvent *event)); static void SFdirModTimer __ARGS((XtPointer cl, XtIntervalId *id)); static char SFstatChar __ARGS((struct stat *statBuf)); static void SFdrawStrings __ARGS((Window w, SFDir *dir, int from, int to)); static int SFnewInvertEntry __ARGS((int n, XMotionEvent *event)); static void SFinvertEntry __ARGS((int n)); static void SFenterList __ARGS((Widget w, int n, XEnterWindowEvent *event)); static void SFleaveList __ARGS((Widget w, int n, XEvent *event)); static void SFmotionList __ARGS((Widget w, int n, XMotionEvent *event)); static void SFvFloatSliderMovedCallback __ARGS((Widget w, XtPointer n, XtPointer fnew)); static void SFvSliderMovedCallback __ARGS((Widget w, int n, int nw)); static void SFvAreaSelectedCallback __ARGS((Widget w, XtPointer n, XtPointer pnew)); static void SFhSliderMovedCallback __ARGS((Widget w, XtPointer n, XtPointer nw)); static void SFhAreaSelectedCallback __ARGS((Widget w, XtPointer n, XtPointer pnew)); static void SFpathSliderMovedCallback __ARGS((Widget w, XtPointer client_data, XtPointer nw)); static void SFpathAreaSelectedCallback __ARGS((Widget w, XtPointer client_data, XtPointer pnew)); static Boolean SFworkProc __ARGS((void)); static int SFcompareEntries __ARGS((const void *p, const void *q)); static void SFprepareToReturn __ARGS((void)); static void SFcreateWidgets __ARGS((Widget toplevel, char *prompt, char *ok, char *cancel)); static void SFsetColors __ARGS((guicolor_T bg, guicolor_T fg, guicolor_T scroll_bg, guicolor_T scrollfg)); /***************** xstat.h */ #ifndef S_IXUSR # define S_IXUSR 0100 #endif #ifndef S_IXGRP # define S_IXGRP 0010 #endif #ifndef S_IXOTH # define S_IXOTH 0001 #endif #define S_ISXXX(m) ((m) & (S_IXUSR | S_IXGRP | S_IXOTH)) /***************** Path.c */ #include <pwd.h> typedef struct { char *name; char *dir; } SFLogin; static int SFdoNotTouchDirPtr = 0; static int SFdoNotTouchVorigin = 0; static SFDir SFrootDir, SFhomeDir; static SFLogin *SFlogins; static int SFtwiddle = 0; static int SFchdir __ARGS((char *path)); static int SFchdir(path) char *path; { int result; result = 0; if (strcmp(path, SFcurrentDir)) { result = mch_chdir(path); if (!result) (void) strcpy(SFcurrentDir, path); } return result; } static void SFfree __ARGS((int i)); static void SFfree(i) int i; { SFDir *dir; int j; dir = &(SFdirs[i]); for (j = dir->nEntries - 1; j >= 0; j--) { if (dir->entries[j].shown != dir->entries[j].real) XtFree(dir->entries[j].shown); XtFree(dir->entries[j].real); } XtFree((char *)dir->entries); XtFree(dir->dir); dir->dir = NULL; } static void SFstrdup __ARGS((char **s1, char *s2)); static void SFstrdup(s1, s2) char **s1; char *s2; { *s1 = strcpy(XtMalloc((unsigned)(strlen(s2) + 1)), s2); } static void SFunreadableDir __ARGS((SFDir *dir)); static void SFunreadableDir(dir) SFDir *dir; { char *cannotOpen = _("<cannot open> "); dir->entries = (SFEntry *) XtMalloc(sizeof(SFEntry)); dir->entries[0].statDone = 1; SFstrdup(&dir->entries[0].real, cannotOpen); dir->entries[0].shown = dir->entries[0].real; dir->nEntries = 1; dir->nChars = strlen(cannotOpen); } static void SFreplaceText __ARGS((SFDir *dir, char *str)); static void SFreplaceText(dir, str) SFDir *dir; char *str; { int len; *(dir->path) = 0; len = strlen(str); if (str[len - 1] == '/') (void) strcat(SFcurrentPath, str); else (void) strncat(SFcurrentPath, str, len - 1); if (strncmp(SFcurrentPath, SFstartDir, strlen(SFstartDir))) SFsetText(SFcurrentPath); else SFsetText(&(SFcurrentPath[strlen(SFstartDir)])); SFtextChanged(); } static void SFexpand __ARGS((char *str)); static void SFexpand(str) char *str; { int len; int cmp; char *name, *growing; SFDir *dir; SFEntry *entry, *max; len = strlen(str); dir = &(SFdirs[SFdirEnd - 1]); if (dir->beginSelection == -1) { SFstrdup(&str, str); SFreplaceText(dir, str); XtFree(str); return; } else if (dir->beginSelection == dir->endSelection) { SFreplaceText(dir, dir->entries[dir->beginSelection].shown); return; } max = &(dir->entries[dir->endSelection + 1]); name = dir->entries[dir->beginSelection].shown; SFstrdup(&growing, name); cmp = 0; while (!cmp) { entry = &(dir->entries[dir->beginSelection]); while (entry < max) { if ((cmp = strncmp(growing, entry->shown, len))) break; entry++; } len++; } /* * SFreplaceText() expects filename */ growing[len - 2] = ' '; growing[len - 1] = 0; SFreplaceText(dir, growing); XtFree(growing); } static int SFfindFile __ARGS((SFDir *dir, char *str)); static int SFfindFile(dir, str) SFDir *dir; char *str; { int i, last, max; char *name, save; SFEntry *entries; int len; int begin, end; int result; len = strlen(str); if (str[len - 1] == ' ') { SFexpand(str); return 1; } else if (str[len - 1] == '/') len--; max = dir->nEntries; entries = dir->entries; i = 0; while (i < max) { name = entries[i].shown; last = strlen(name) - 1; save = name[last]; name[last] = 0; result = strncmp(str, name, len); name[last] = save; if (result <= 0) break; i++; } begin = i; while (i < max) { name = entries[i].shown; last = strlen(name) - 1; save = name[last]; name[last] = 0; result = strncmp(str, name, len); name[last] = save; if (result) break; i++; } end = i; if (begin != end) { if ((dir->beginSelection != begin) || (dir->endSelection != end - 1)) { dir->changed = 1; dir->beginSelection = begin; if (str[strlen(str) - 1] == '/') dir->endSelection = begin; else dir->endSelection = end - 1; } } else if (dir->beginSelection != -1) { dir->changed = 1; dir->beginSelection = -1; dir->endSelection = -1; } if (SFdoNotTouchVorigin || ((begin > dir->vOrigin) && (end < dir->vOrigin + SFlistSize))) { SFdoNotTouchVorigin = 0; return 0; } i = begin - 1; if (i > max - SFlistSize) i = max - SFlistSize; if (i < 0) i = 0; if (dir->vOrigin != i) { dir->vOrigin = i; dir->changed = 1; } return 0; } static void SFunselect __ARGS((void)); static void SFunselect() { SFDir *dir; dir = &(SFdirs[SFdirEnd - 1]); if (dir->beginSelection != -1) dir->changed = 1; dir->beginSelection = -1; dir->endSelection = -1; } static int SFcompareLogins __ARGS((const void *p, const void *q)); static int SFcompareLogins(p, q) const void *p, *q; { return strcmp(((SFLogin *)p)->name, ((SFLogin *)q)->name); } static void SFgetHomeDirs __ARGS((void)); static void SFgetHomeDirs() { struct passwd *pw; int Alloc; int i; SFEntry *entries = NULL; int len; int maxChars; Alloc = 1; i = 1; entries = (SFEntry *)XtMalloc(sizeof(SFEntry)); SFlogins = (SFLogin *)XtMalloc(sizeof(SFLogin)); entries[0].real = XtMalloc(3); (void) strcpy(entries[0].real, "~"); entries[0].shown = entries[0].real; entries[0].statDone = 1; SFlogins[0].name = ""; pw = getpwuid((int) getuid()); SFstrdup(&SFlogins[0].dir, pw ? pw->pw_dir : "/"); maxChars = 0; (void) setpwent(); while ((pw = getpwent()) && (*(pw->pw_name))) { if (i >= Alloc) { Alloc *= 2; entries = (SFEntry *) XtRealloc((char *)entries, (unsigned)(Alloc * sizeof(SFEntry))); SFlogins = (SFLogin *) XtRealloc((char *)SFlogins, (unsigned)(Alloc * sizeof(SFLogin))); } len = strlen(pw->pw_name); entries[i].real = XtMalloc((unsigned) (len + 3)); (void) strcat(strcpy(entries[i].real, "~"), pw->pw_name); entries[i].shown = entries[i].real; entries[i].statDone = 1; if (len > maxChars) maxChars = len; SFstrdup(&SFlogins[i].name, pw->pw_name); SFstrdup(&SFlogins[i].dir, pw->pw_dir); i++; } SFhomeDir.dir = XtMalloc(1); SFhomeDir.dir[0] = 0; SFhomeDir.path = SFcurrentPath; SFhomeDir.entries = entries; SFhomeDir.nEntries = i; SFhomeDir.vOrigin = 0; /* :-) */ SFhomeDir.nChars = maxChars + 2; SFhomeDir.hOrigin = 0; SFhomeDir.changed = 1; SFhomeDir.beginSelection = -1; SFhomeDir.endSelection = -1; qsort((char *)entries, (size_t)i, sizeof(SFEntry), SFcompareEntries); qsort((char *)SFlogins, (size_t)i, sizeof(SFLogin), SFcompareLogins); for (i--; i >= 0; i--) (void)strcat(entries[i].real, "/"); } static int SFfindHomeDir __ARGS((char *begin, char *end)); static int SFfindHomeDir(begin, end) char *begin, *end; { char save; char *theRest; int i; save = *end; *end = 0; for (i = SFhomeDir.nEntries - 1; i >= 0; i--) { if (!strcmp(SFhomeDir.entries[i].real, begin)) { *end = save; SFstrdup(&theRest, end); (void) strcat(strcat(strcpy(SFcurrentPath, SFlogins[i].dir), "/"), theRest); XtFree(theRest); SFsetText(SFcurrentPath); SFtextChanged(); return 1; } } *end = save; return 0; } static void SFupdatePath() { static int Alloc; static int wasTwiddle = 0; char *begin, *end; int i, j; int prevChange; int SFdirPtrSave, SFdirEndSave; SFDir *dir; if (!SFdirs) { SFdirs = (SFDir *) XtMalloc((Alloc = 10) * sizeof(SFDir)); dir = &(SFdirs[0]); SFstrdup(&dir->dir, "/"); (void) SFchdir("/"); (void) SFgetDir(dir); for (j = 1; j < Alloc; j++) SFdirs[j].dir = NULL; dir->path = SFcurrentPath + 1; dir->vOrigin = 0; dir->hOrigin = 0; dir->changed = 1; dir->beginSelection = -1; dir->endSelection = -1; SFhomeDir.dir = NULL; } SFdirEndSave = SFdirEnd; SFdirEnd = 1; SFdirPtrSave = SFdirPtr; SFdirPtr = 0; begin = NULL; if (SFcurrentPath[0] == '~') { if (!SFtwiddle) { SFtwiddle = 1; dir = &(SFdirs[0]); SFrootDir = *dir; if (!SFhomeDir.dir) SFgetHomeDirs(); *dir = SFhomeDir; dir->changed = 1; } end = SFcurrentPath; SFdoNotTouchDirPtr = 1; wasTwiddle = 1; } else { if (SFtwiddle) { SFtwiddle = 0; dir = &(SFdirs[0]); *dir = SFrootDir; dir->changed = 1; } end = SFcurrentPath + 1; } i = 0; prevChange = 0; while (*end) { while (*end++ == '/') ; end--; begin = end; while ((*end) && (*end++ != '/')) ; if ((end - SFcurrentPath <= SFtextPos) && (*(end - 1) == '/')) { SFdirPtr = i - 1; if (SFdirPtr < 0) SFdirPtr = 0; } if (*begin) { if (*(end - 1) == '/') { char save = *end; if (SFtwiddle) { if (SFfindHomeDir(begin, end)) return; } *end = 0; i++; SFdirEnd++; if (i >= Alloc) { SFdirs = (SFDir *) XtRealloc((char *) SFdirs, (unsigned)((Alloc *= 2) * sizeof(SFDir))); for (j = Alloc / 2; j < Alloc; j++) SFdirs[j].dir = NULL; } dir = &(SFdirs[i]); if ((!(dir->dir)) || prevChange || strcmp(dir->dir, begin)) { if (dir->dir) SFfree(i); prevChange = 1; SFstrdup(&dir->dir, begin); dir->path = end; dir->vOrigin = 0; dir->hOrigin = 0; dir->changed = 1; dir->beginSelection = -1; dir->endSelection = -1; (void)SFfindFile(dir - 1, begin); if (SFchdir(SFcurrentPath) || SFgetDir(dir)) { SFunreadableDir(dir); break; } } *end = save; if (!save) SFunselect(); } else { if (SFfindFile(&(SFdirs[SFdirEnd-1]), begin)) return; } } else SFunselect(); } if ((end == SFcurrentPath + 1) && (!SFtwiddle)) SFunselect(); for (i = SFdirEnd; i < Alloc; i++) if (SFdirs[i].dir) SFfree(i); if (SFdoNotTouchDirPtr) { if (wasTwiddle) { wasTwiddle = 0; SFdirPtr = SFdirEnd - 2; if (SFdirPtr < 0) SFdirPtr = 0; } else SFdirPtr = SFdirPtrSave; SFdoNotTouchDirPtr = 0; } if ((SFdirPtr != SFdirPtrSave) || (SFdirEnd != SFdirEndSave)) { #ifdef FEAT_GUI_NEXTAW XawScrollbarSetThumb( selFileHScroll, (float) (((double) SFdirPtr) / SFdirEnd), (float) (((double) ((SFdirEnd < 3) ? SFdirEnd : 3)) / SFdirEnd)); #else vim_XawScrollbarSetThumb( selFileHScroll, (float) (((double) SFdirPtr) / SFdirEnd), (float) (((double) ((SFdirEnd < 3) ? SFdirEnd : 3)) / SFdirEnd), (double)SFdirEnd); #endif } if (SFdirPtr != SFdirPtrSave) SFdrawLists(SF_DO_SCROLL); else for (i = 0; i < 3; i++) { if (SFdirPtr + i < SFdirEnd) { if (SFdirs[SFdirPtr + i].changed) { SFdirs[SFdirPtr + i].changed = 0; SFdrawList(i, SF_DO_SCROLL); } } else SFclearList(i, SF_DO_SCROLL); } } #ifdef XtNinternational static int WcsLen(p) wchar_t *p; { int i = 0; while (*p++ != 0) i++; return i; } #endif static void SFsetText(path) char *path; { XawTextBlock text; text.firstPos = 0; text.length = strlen(path); text.ptr = path; text.format = FMT8BIT; #ifdef XtNinternational if ((unsigned long)_XawTextFormat((TextWidget)selFileField) == XawFmtWide) { XawTextReplace(selFileField, (XawTextPosition)0, (XawTextPosition)WcsLen((wchar_t *)&SFtextBuffer[0]), &text); XawTextSetInsertionPoint(selFileField, (XawTextPosition)WcsLen((wchar_t *)&SFtextBuffer[0])); } else { XawTextReplace(selFileField, (XawTextPosition)0, (XawTextPosition)strlen(SFtextBuffer), &text); XawTextSetInsertionPoint(selFileField, (XawTextPosition)strlen(SFtextBuffer)); } #else XawTextReplace(selFileField, (XawTextPosition)0, (XawTextPosition)strlen(SFtextBuffer), &text); XawTextSetInsertionPoint(selFileField, (XawTextPosition)strlen(SFtextBuffer)); #endif } static void SFbuttonPressList(w, n, event) Widget w UNUSED; int n UNUSED; XButtonPressedEvent *event UNUSED; { SFbuttonPressed = 1; } static void SFbuttonReleaseList(w, n, event) Widget w; int n; XButtonReleasedEvent *event; { SFDir *dir; SFbuttonPressed = 0; if (SFcurrentInvert[n] != -1) { if (n < 2) SFdoNotTouchDirPtr = 1; SFdoNotTouchVorigin = 1; dir = &(SFdirs[SFdirPtr + n]); SFreplaceText(dir, dir->entries[dir->vOrigin + SFcurrentInvert[n]].shown); SFmotionList(w, n, (XMotionEvent *) event); } } static int SFcheckDir __ARGS((int n, SFDir *dir)); static int SFcheckDir(n, dir) int n; SFDir *dir; { struct stat statBuf; int i; if ((!mch_stat(".", &statBuf)) && (statBuf.st_mtime != dir->mtime)) { /* * If the pointer is currently in the window that we are about * to update, we must warp it to prevent the user from * accidentally selecting the wrong file. */ if (SFcurrentInvert[n] != -1) { XWarpPointer( SFdisplay, None, XtWindow(selFileLists[n]), 0, 0, 0, 0, 0, 0); } for (i = dir->nEntries - 1; i >= 0; i--) { if (dir->entries[i].shown != dir->entries[i].real) XtFree(dir->entries[i].shown); XtFree(dir->entries[i].real); } XtFree((char *) dir->entries); if (SFgetDir(dir)) SFunreadableDir(dir); if (dir->vOrigin > dir->nEntries - SFlistSize) dir->vOrigin = dir->nEntries - SFlistSize; if (dir->vOrigin < 0) dir->vOrigin = 0; if (dir->hOrigin > dir->nChars - SFcharsPerEntry) dir->hOrigin = dir->nChars - SFcharsPerEntry; if (dir->hOrigin < 0) dir->hOrigin = 0; dir->beginSelection = -1; dir->endSelection = -1; SFdoNotTouchVorigin = 1; if ((dir + 1)->dir) (void) SFfindFile(dir, (dir + 1)->dir); else (void) SFfindFile(dir, dir->path); if (!SFworkProcAdded) { (void) XtAppAddWorkProc(SFapp, (XtWorkProc)SFworkProc, NULL); SFworkProcAdded = 1; } return 1; } return 0; } static int SFcheckFiles __ARGS((SFDir *dir)); static int SFcheckFiles(dir) SFDir *dir; { int from, to; int result; char oldc, newc; int i; char *str; int last; struct stat statBuf; result = 0; from = dir->vOrigin; to = dir->vOrigin + SFlistSize; if (to > dir->nEntries) to = dir->nEntries; for (i = from; i < to; i++) { str = dir->entries[i].real; last = strlen(str) - 1; oldc = str[last]; str[last] = 0; if (mch_stat(str, &statBuf)) newc = ' '; else newc = SFstatChar(&statBuf); str[last] = newc; if (newc != oldc) result = 1; } return result; } static void SFdirModTimer(cl, id) XtPointer cl UNUSED; XtIntervalId *id UNUSED; { static int n = -1; static int f = 0; char save; SFDir *dir; if ((!SFtwiddle) && (SFdirPtr < SFdirEnd)) { n++; if ((n > 2) || (SFdirPtr + n >= SFdirEnd)) { n = 0; f++; if ((f > 2) || (SFdirPtr + f >= SFdirEnd)) f = 0; } dir = &(SFdirs[SFdirPtr + n]); save = *(dir->path); *(dir->path) = 0; if (SFchdir(SFcurrentPath)) { *(dir->path) = save; /* * force a re-read */ *(dir->dir) = 0; SFupdatePath(); } else { *(dir->path) = save; if (SFcheckDir(n, dir) || ((f == n) && SFcheckFiles(dir))) SFdrawList(n, SF_DO_SCROLL); } } SFdirModTimerId = XtAppAddTimeOut(SFapp, (unsigned long) 1000, SFdirModTimer, (XtPointer) NULL); } /* Return a single character describing what kind of file STATBUF is. */ static char SFstatChar(statBuf) struct stat *statBuf; { if (S_ISDIR (statBuf->st_mode)) return '/'; if (S_ISREG (statBuf->st_mode)) return S_ISXXX (statBuf->st_mode) ? '*' : ' '; #ifdef S_ISSOCK if (S_ISSOCK (statBuf->st_mode)) return '='; #endif /* S_ISSOCK */ return ' '; } /***************** Draw.c */ #ifdef FEAT_GUI_NEXTAW # include <X11/neXtaw/Cardinals.h> #else # include <X11/Xaw/Cardinals.h> #endif #ifdef FEAT_XFONTSET # define SF_DEFAULT_FONT "-misc-fixed-medium-r-normal--14-*" #else # define SF_DEFAULT_FONT "9x15" #endif #ifdef ABS # undef ABS #endif #define ABS(x) (((x) < 0) ? (-(x)) : (x)) typedef struct { char *fontname; } TextData; static GC SFlineGC, SFscrollGC, SFinvertGC, SFtextGC; static XtResource textResources[] = { #ifdef FEAT_XFONTSET {XtNfontSet, XtCFontSet, XtRString, sizeof (char *), XtOffsetOf(TextData, fontname), XtRString, SF_DEFAULT_FONT}, #else {XtNfont, XtCFont, XtRString, sizeof (char *), XtOffsetOf(TextData, fontname), XtRString, SF_DEFAULT_FONT}, #endif }; #ifdef FEAT_XFONTSET static XFontSet SFfont; #else static XFontStruct *SFfont; #endif static int SFcurrentListY; static XtIntervalId SFscrollTimerId; static void SFinitFont __ARGS((void)); static void SFinitFont() { TextData *data; #ifdef FEAT_XFONTSET XFontSetExtents *extents; char **missing, *def_str; int num_missing; #endif data = XtNew(TextData); XtGetApplicationResources(selFileForm, (XtPointer) data, textResources, XtNumber(textResources), (Arg *) NULL, ZERO); #ifdef FEAT_XFONTSET SFfont = XCreateFontSet(SFdisplay, data->fontname, &missing, &num_missing, &def_str); #else SFfont = XLoadQueryFont(SFdisplay, data->fontname); #endif if (!SFfont) { #ifdef FEAT_XFONTSET SFfont = XCreateFontSet(SFdisplay, SF_DEFAULT_FONT, &missing, &num_missing, &def_str); #else SFfont = XLoadQueryFont(SFdisplay, SF_DEFAULT_FONT); #endif if (!SFfont) { EMSG2(_("E616: vim_SelFile: can't get font %s"), SF_DEFAULT_FONT); SFstatus = SEL_FILE_CANCEL; return; } } #ifdef FEAT_XFONTSET extents = XExtentsOfFontSet(SFfont); SFcharWidth = extents->max_logical_extent.width; SFcharAscent = -extents->max_logical_extent.y; SFcharHeight = extents->max_logical_extent.height; #else SFcharWidth = (SFfont->max_bounds.width + SFfont->min_bounds.width) / 2; SFcharAscent = SFfont->max_bounds.ascent; SFcharHeight = SFcharAscent + SFfont->max_bounds.descent; #endif } static void SFcreateGC __ARGS((void)); static void SFcreateGC() { XGCValues gcValues; XRectangle rectangles[1]; gcValues.foreground = SFfore; SFlineGC = XtGetGC( selFileLists[0], (XtGCMask)GCForeground, &gcValues); SFscrollGC = XtGetGC( selFileLists[0], (XtGCMask)0, &gcValues); gcValues.function = GXxor; gcValues.foreground = SFfore ^ SFback; gcValues.background = SFfore ^ SFback; SFinvertGC = XtGetGC( selFileLists[0], (XtGCMask)GCFunction | GCForeground | GCBackground, &gcValues); gcValues.foreground = SFfore; gcValues.background = SFback; #ifndef FEAT_XFONTSET gcValues.font = SFfont->fid; #endif SFtextGC = XCreateGC( SFdisplay, XtWindow(selFileLists[0]), #ifdef FEAT_XFONTSET (unsigned long)GCForeground | GCBackground, #else (unsigned long)GCForeground | GCBackground | GCFont, #endif &gcValues); rectangles[0].x = SFlineToTextH + SFbesideText; rectangles[0].y = 0; rectangles[0].width = SFcharsPerEntry * SFcharWidth; rectangles[0].height = SFupperY + 1; XSetClipRectangles( SFdisplay, SFtextGC, 0, 0, rectangles, 1, Unsorted); } static void SFclearList(n, doScroll) int n; int doScroll; { SFDir *dir; SFcurrentInvert[n] = -1; XClearWindow(SFdisplay, XtWindow(selFileLists[n])); XDrawSegments(SFdisplay, XtWindow(selFileLists[n]), SFlineGC, SFsegs, 2); if (doScroll) { dir = &(SFdirs[SFdirPtr + n]); if ((SFdirPtr + n < SFdirEnd) && dir->nEntries && dir->nChars) { #ifdef FEAT_GUI_NEXTAW XawScrollbarSetThumb( selFileVScrolls[n], (float) (((double) dir->vOrigin) / dir->nEntries), (float) (((double) ((dir->nEntries < SFlistSize) ? dir->nEntries : SFlistSize)) / dir->nEntries)); #else vim_XawScrollbarSetThumb( selFileVScrolls[n], (float) (((double) dir->vOrigin) / dir->nEntries), (float) (((double) ((dir->nEntries < SFlistSize) ? dir->nEntries : SFlistSize)) / dir->nEntries), (double)dir->nEntries); #endif #ifdef FEAT_GUI_NEXTAW XawScrollbarSetThumb( selFileHScrolls[n], (float) (((double) dir->hOrigin) / dir->nChars), (float) (((double) ((dir->nChars < SFcharsPerEntry) ? dir->nChars : SFcharsPerEntry)) / dir->nChars)); #else vim_XawScrollbarSetThumb( selFileHScrolls[n], (float) (((double) dir->hOrigin) / dir->nChars), (float) (((double) ((dir->nChars < SFcharsPerEntry) ? dir->nChars : SFcharsPerEntry)) / dir->nChars), (double)dir->nChars); #endif } else { #ifdef FEAT_GUI_NEXTAW XawScrollbarSetThumb(selFileVScrolls[n], (float) 0.0, (float) 1.0); #else vim_XawScrollbarSetThumb(selFileVScrolls[n], (float) 0.0, (float) 1.0, 1.0); #endif #ifdef FEAT_GUI_NEXTAW XawScrollbarSetThumb(selFileHScrolls[n], (float) 0.0, (float) 1.0); #else vim_XawScrollbarSetThumb(selFileHScrolls[n], (float) 0.0, (float) 1.0, 1.0); #endif } } } static void SFdeleteEntry __ARGS((SFDir *dir, SFEntry *entry)); static void SFdeleteEntry(dir, entry) SFDir *dir; SFEntry *entry; { SFEntry *e; SFEntry *end; int n; int idx; idx = entry - dir->entries; if (idx < dir->beginSelection) dir->beginSelection--; if (idx <= dir->endSelection) dir->endSelection--; if (dir->beginSelection > dir->endSelection) dir->beginSelection = dir->endSelection = -1; if (idx < dir->vOrigin) dir->vOrigin--; XtFree(entry->real); end = &(dir->entries[dir->nEntries - 1]); for (e = entry; e < end; e++) *e = *(e + 1); if (!(--dir->nEntries)) return; n = dir - &(SFdirs[SFdirPtr]); if ((n < 0) || (n > 2)) return; #ifdef FEAT_GUI_NEXTAW XawScrollbarSetThumb( selFileVScrolls[n], (float) (((double) dir->vOrigin) / dir->nEntries), (float) (((double) ((dir->nEntries < SFlistSize) ? dir->nEntries : SFlistSize)) / dir->nEntries)); #else vim_XawScrollbarSetThumb( selFileVScrolls[n], (float) (((double) dir->vOrigin) / dir->nEntries), (float) (((double) ((dir->nEntries < SFlistSize) ? dir->nEntries : SFlistSize)) / dir->nEntries), (double)dir->nEntries); #endif } static void SFwriteStatChar __ARGS((char *name, int last, struct stat *statBuf)); static void SFwriteStatChar(name, last, statBuf) char *name; int last; struct stat *statBuf; { name[last] = SFstatChar(statBuf); } static int SFstatAndCheck __ARGS((SFDir *dir, SFEntry *entry)); static int SFstatAndCheck(dir, entry) SFDir *dir; SFEntry *entry; { struct stat statBuf; char save; int last; /* * must be restored before returning */ save = *(dir->path); *(dir->path) = 0; if (!SFchdir(SFcurrentPath)) { last = strlen(entry->real) - 1; entry->real[last] = 0; entry->statDone = 1; if ((!mch_stat(entry->real, &statBuf)) #ifdef S_IFLNK || (!mch_lstat(entry->real, &statBuf)) #endif ) { if (SFfunc) { char *shown; shown = NULL; if (SFfunc(entry->real, &shown, &statBuf)) { if (shown) { int len; len = strlen(shown); entry->shown = XtMalloc((unsigned) (len + 2)); (void) strcpy(entry->shown, shown); SFwriteStatChar(entry->shown, len, &statBuf); entry->shown[len + 1] = 0; } } else { SFdeleteEntry(dir, entry); *(dir->path) = save; return 1; } } SFwriteStatChar(entry->real, last, &statBuf); } else entry->real[last] = ' '; } *(dir->path) = save; return 0; } static void SFdrawStrings(w, dir, from, to) Window w; SFDir *dir; int from; int to; { int i; SFEntry *entry; int x; x = SFtextX - dir->hOrigin * SFcharWidth; if (dir->vOrigin + to >= dir->nEntries) to = dir->nEntries - dir->vOrigin - 1; for (i = from; i <= to; i++) { entry = &(dir->entries[dir->vOrigin + i]); if (!(entry->statDone)) { if (SFstatAndCheck(dir, entry)) { if (dir->vOrigin + to >= dir->nEntries) to = dir->nEntries - dir->vOrigin - 1; i--; continue; } } #ifdef FEAT_XFONTSET XmbDrawImageString( SFdisplay, w, SFfont, SFtextGC, x, SFtextYoffset + i * SFentryHeight, entry->shown, strlen(entry->shown)); #else XDrawImageString( SFdisplay, w, SFtextGC, x, SFtextYoffset + i * SFentryHeight, entry->shown, strlen(entry->shown)); #endif if (dir->vOrigin + i == dir->beginSelection) { XDrawLine( SFdisplay, w, SFlineGC, SFlineToTextH + 1, SFlowerY + i * SFentryHeight, SFlineToTextH + SFentryWidth - 2, SFlowerY + i * SFentryHeight); } if ((dir->vOrigin + i >= dir->beginSelection) && (dir->vOrigin + i <= dir->endSelection)) { SFcompletionSegs[0].y1 = SFcompletionSegs[1].y1 = SFlowerY + i * SFentryHeight; SFcompletionSegs[0].y2 = SFcompletionSegs[1].y2 = SFlowerY + (i + 1) * SFentryHeight - 1; XDrawSegments( SFdisplay, w, SFlineGC, SFcompletionSegs, 2); } if (dir->vOrigin + i == dir->endSelection) { XDrawLine( SFdisplay, w, SFlineGC, SFlineToTextH + 1, SFlowerY + (i + 1) * SFentryHeight - 1, SFlineToTextH + SFentryWidth - 2, SFlowerY + (i + 1) * SFentryHeight - 1); } } } static void SFdrawList(n, doScroll) int n; int doScroll; { SFDir *dir; Window w; SFclearList(n, doScroll); if (SFdirPtr + n < SFdirEnd) { dir = &(SFdirs[SFdirPtr + n]); w = XtWindow(selFileLists[n]); #ifdef FEAT_XFONTSET XmbDrawImageString( SFdisplay, w, SFfont, SFtextGC, SFtextX - dir->hOrigin * SFcharWidth, SFlineToTextV + SFaboveAndBelowText + SFcharAscent, dir->dir, strlen(dir->dir)); #else XDrawImageString( SFdisplay, w, SFtextGC, SFtextX - dir->hOrigin * SFcharWidth, SFlineToTextV + SFaboveAndBelowText + SFcharAscent, dir->dir, strlen(dir->dir)); #endif SFdrawStrings(w, dir, 0, SFlistSize - 1); } } static void SFdrawLists(doScroll) int doScroll; { int i; for (i = 0; i < 3; i++) SFdrawList(i, doScroll); } static void SFinvertEntry(n) int n; { XFillRectangle( SFdisplay, XtWindow(selFileLists[n]), SFinvertGC, SFlineToTextH, SFcurrentInvert[n] * SFentryHeight + SFlowerY, SFentryWidth, SFentryHeight); } static unsigned long SFscrollTimerInterval __ARGS((void)); static unsigned long SFscrollTimerInterval() { static int maxVal = 200; static int varyDist = 50; static int minDist = 50; int t; int dist; if (SFcurrentListY < SFlowerY) dist = SFlowerY - SFcurrentListY; else if (SFcurrentListY > SFupperY) dist = SFcurrentListY - SFupperY; else return (unsigned long) 1; t = maxVal - ((maxVal / varyDist) * (dist - minDist)); if (t < 1) t = 1; if (t > maxVal) t = maxVal; return (unsigned long)t; } static void SFscrollTimer __ARGS((XtPointer p, XtIntervalId *id)); static void SFscrollTimer(p, id) XtPointer p; XtIntervalId *id UNUSED; { SFDir *dir; int save; int n; n = (long)p; dir = &(SFdirs[SFdirPtr + n]); save = dir->vOrigin; if (SFcurrentListY < SFlowerY) { if (dir->vOrigin > 0) SFvSliderMovedCallback(selFileVScrolls[n], n, dir->vOrigin - 1); } else if (SFcurrentListY > SFupperY) { if (dir->vOrigin < dir->nEntries - SFlistSize) SFvSliderMovedCallback(selFileVScrolls[n], n, dir->vOrigin + 1); } if (dir->vOrigin != save) { if (dir->nEntries) { #ifdef FEAT_GUI_NEXTAW XawScrollbarSetThumb( selFileVScrolls[n], (float) (((double) dir->vOrigin) / dir->nEntries), (float) (((double) ((dir->nEntries < SFlistSize) ? dir->nEntries : SFlistSize)) / dir->nEntries)); #else vim_XawScrollbarSetThumb( selFileVScrolls[n], (float) (((double) dir->vOrigin) / dir->nEntries), (float) (((double) ((dir->nEntries < SFlistSize) ? dir->nEntries : SFlistSize)) / dir->nEntries), (double)dir->nEntries); #endif } } if (SFbuttonPressed) SFscrollTimerId = XtAppAddTimeOut(SFapp, SFscrollTimerInterval(), SFscrollTimer, (XtPointer)(long_u)n); } static int SFnewInvertEntry(n, event) int n; XMotionEvent *event; { int x, y; int nw; static int SFscrollTimerAdded = 0; x = event->x; y = event->y; if (SFdirPtr + n >= SFdirEnd) return -1; if ((x >= 0) && (x <= SFupperX) && (y >= SFlowerY) && (y <= SFupperY)) { SFDir *dir = &(SFdirs[SFdirPtr + n]); if (SFscrollTimerAdded) { SFscrollTimerAdded = 0; XtRemoveTimeOut(SFscrollTimerId); } nw = (y - SFlowerY) / SFentryHeight; if (dir->vOrigin + nw >= dir->nEntries) return -1; return nw; } else { if (SFbuttonPressed) { SFcurrentListY = y; if (!SFscrollTimerAdded) { SFscrollTimerAdded = 1; SFscrollTimerId = XtAppAddTimeOut(SFapp, SFscrollTimerInterval(), SFscrollTimer, (XtPointer)(long_u)n); } } return -1; } } static void SFenterList(w, n, event) Widget w UNUSED; int n; XEnterWindowEvent *event; { int nw; /* sanity */ if (SFcurrentInvert[n] != -1) { SFinvertEntry(n); SFcurrentInvert[n] = -1; } nw = SFnewInvertEntry(n, (XMotionEvent *) event); if (nw != -1) { SFcurrentInvert[n] = nw; SFinvertEntry(n); } } static void SFleaveList(w, n, event) Widget w UNUSED; int n; XEvent *event UNUSED; { if (SFcurrentInvert[n] != -1) { SFinvertEntry(n); SFcurrentInvert[n] = -1; } } static void SFmotionList(w, n, event) Widget w UNUSED; int n; XMotionEvent *event; { int nw; nw = SFnewInvertEntry(n, event); if (nw != SFcurrentInvert[n]) { if (SFcurrentInvert[n] != -1) SFinvertEntry(n); SFcurrentInvert[n] = nw; if (nw != -1) SFinvertEntry(n); } } static void SFvFloatSliderMovedCallback(w, n, fnew) Widget w; XtPointer n; XtPointer fnew; { int nw; nw = (*(float *)fnew) * SFdirs[SFdirPtr + (int)(long)n].nEntries; SFvSliderMovedCallback(w, (int)(long)n, nw); } static void SFvSliderMovedCallback(w, n, nw) Widget w UNUSED; int n; int nw; { int old; Window win; SFDir *dir; dir = &(SFdirs[SFdirPtr + n]); old = dir->vOrigin; dir->vOrigin = nw; if (old == nw) return; win = XtWindow(selFileLists[n]); if (ABS(nw - old) < SFlistSize) { if (nw > old) { XCopyArea( SFdisplay, win, win, SFscrollGC, SFlineToTextH, SFlowerY + (nw - old) * SFentryHeight, SFentryWidth + SFlineToTextH, (SFlistSize - (nw - old)) * SFentryHeight, SFlineToTextH, SFlowerY); XClearArea( SFdisplay, win, SFlineToTextH, SFlowerY + (SFlistSize - (nw - old)) * SFentryHeight, SFentryWidth + SFlineToTextH, (nw - old) * SFentryHeight, False); SFdrawStrings(win, dir, SFlistSize - (nw - old), SFlistSize - 1); } else { XCopyArea( SFdisplay, win, win, SFscrollGC, SFlineToTextH, SFlowerY, SFentryWidth + SFlineToTextH, (SFlistSize - (old - nw)) * SFentryHeight, SFlineToTextH, SFlowerY + (old - nw) * SFentryHeight); XClearArea( SFdisplay, win, SFlineToTextH, SFlowerY, SFentryWidth + SFlineToTextH, (old - nw) * SFentryHeight, False); SFdrawStrings(win, dir, 0, old - nw); } } else { XClearArea( SFdisplay, win, SFlineToTextH, SFlowerY, SFentryWidth + SFlineToTextH, SFlistSize * SFentryHeight, False); SFdrawStrings(win, dir, 0, SFlistSize - 1); } } static void SFvAreaSelectedCallback(w, n, pnew) Widget w; XtPointer n; XtPointer pnew; { SFDir *dir; int nw = (int)(long)pnew; dir = &(SFdirs[SFdirPtr + (int)(long)n]); #ifdef FEAT_GUI_NEXTAW if (nw < 0) { if (nw > -SFvScrollHeight) nw = -1; else nw = -SFlistSize; } else if (nw > 0) { if (nw < SFvScrollHeight) nw = 1; else nw = SFlistSize; } #endif nw += dir->vOrigin; if (nw > dir->nEntries - SFlistSize) nw = dir->nEntries - SFlistSize; if (nw < 0) nw = 0; if (dir->nEntries) { float f; f = ((double) nw) / dir->nEntries; #ifdef FEAT_GUI_NEXTAW XawScrollbarSetThumb( w, f, (float) (((double) ((dir->nEntries < SFlistSize) ? dir->nEntries : SFlistSize)) / dir->nEntries)); #else vim_XawScrollbarSetThumb( w, f, (float) (((double) ((dir->nEntries < SFlistSize) ? dir->nEntries : SFlistSize)) / dir->nEntries), (double)dir->nEntries); #endif } SFvSliderMovedCallback(w, (int)(long)n, nw); } static void SFhSliderMovedCallback(w, n, nw) Widget w UNUSED; XtPointer n; XtPointer nw; { SFDir *dir; int save; dir = &(SFdirs[SFdirPtr + (int)(long)n]); save = dir->hOrigin; dir->hOrigin = (*(float *)nw) * dir->nChars; if (dir->hOrigin == save) return; SFdrawList((int)(long)n, SF_DO_NOT_SCROLL); } static void SFhAreaSelectedCallback(w, n, pnew) Widget w; XtPointer n; XtPointer pnew; { SFDir *dir; int nw = (int)(long)pnew; dir = &(SFdirs[SFdirPtr + (int)(long)n]); #ifdef FEAT_GUI_NEXTAW if (nw < 0) { if (nw > -SFhScrollWidth) nw = -1; else nw = -SFcharsPerEntry; } else if (nw > 0) { if (nw < SFhScrollWidth) nw = 1; else nw = SFcharsPerEntry; } #endif nw += dir->hOrigin; if (nw > dir->nChars - SFcharsPerEntry) nw = dir->nChars - SFcharsPerEntry; if (nw < 0) nw = 0; if (dir->nChars) { float f; f = ((double) nw) / dir->nChars; #ifdef FEAT_GUI_NEXTAW XawScrollbarSetThumb( w, f, (float) (((double) ((dir->nChars < SFcharsPerEntry) ? dir->nChars : SFcharsPerEntry)) / dir->nChars)); #else vim_XawScrollbarSetThumb( w, f, (float) (((double) ((dir->nChars < SFcharsPerEntry) ? dir->nChars : SFcharsPerEntry)) / dir->nChars), (double)dir->nChars); #endif SFhSliderMovedCallback(w, n, (XtPointer)&f); } } static void SFpathSliderMovedCallback(w, client_data, nw) Widget w UNUSED; XtPointer client_data UNUSED; XtPointer nw; { SFDir *dir; int n; XawTextPosition pos; int SFdirPtrSave; SFdirPtrSave = SFdirPtr; SFdirPtr = (*(float *)nw) * SFdirEnd; if (SFdirPtr == SFdirPtrSave) return; SFdrawLists(SF_DO_SCROLL); n = 2; while (SFdirPtr + n >= SFdirEnd) n--; dir = &(SFdirs[SFdirPtr + n]); pos = dir->path - SFcurrentPath; if (!strncmp(SFcurrentPath, SFstartDir, strlen(SFstartDir))) { pos -= strlen(SFstartDir); if (pos < 0) pos = 0; } XawTextSetInsertionPoint(selFileField, pos); } static void SFpathAreaSelectedCallback(w, client_data, pnew) Widget w; XtPointer client_data UNUSED; XtPointer pnew; { int nw = (int)(long)pnew; float f; #ifdef FEAT_GUI_NEXTAW if (nw < 0) { if (nw > -SFpathScrollWidth) nw = -1; else nw = -3; } else if (nw > 0) { if (nw < SFpathScrollWidth) nw = 1; else nw = 3; } #endif nw += SFdirPtr; if (nw > SFdirEnd - 3) nw = SFdirEnd - 3; if (nw < 0) nw = 0; f = ((double) nw) / SFdirEnd; #ifdef FEAT_GUI_NEXTAW XawScrollbarSetThumb( w, f, (float) (((double) ((SFdirEnd < 3) ? SFdirEnd : 3)) / SFdirEnd)); #else vim_XawScrollbarSetThumb( w, f, (float) (((double) ((SFdirEnd < 3) ? SFdirEnd : 3)) / SFdirEnd), (double)SFdirEnd); #endif SFpathSliderMovedCallback(w, (XtPointer) NULL, (XtPointer)&f); } static Boolean SFworkProc() { SFDir *dir; SFEntry *entry; for (dir = &(SFdirs[SFdirEnd - 1]); dir >= SFdirs; dir--) { if (!(dir->nEntries)) continue; for (entry = &(dir->entries[dir->nEntries - 1]); entry >= dir->entries; entry--) { if (!(entry->statDone)) { (void)SFstatAndCheck(dir, entry); return False; } } } SFworkProcAdded = 0; return True; } /***************** Dir.c */ static int SFcompareEntries(p, q) const void *p; const void *q; { return strcmp(((SFEntry *)p)->real, ((SFEntry *)q)->real); } static int SFgetDir(dir) SFDir *dir; { SFEntry *result = NULL; int Alloc = 0; int i; DIR *dirp; struct dirent *dp; char *str; int len; int maxChars; struct stat statBuf; maxChars = strlen(dir->dir) - 1; dir->entries = NULL; dir->nEntries = 0; dir->nChars = 0; result = NULL; i = 0; dirp = opendir("."); if (!dirp) return 1; (void)mch_stat(".", &statBuf); dir->mtime = statBuf.st_mtime; while ((dp = readdir(dirp))) { /* Ignore "." and ".." */ if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0) continue; if (i >= Alloc) { Alloc = 2 * (Alloc + 1); result = (SFEntry *) XtRealloc((char *) result, (unsigned) (Alloc * sizeof(SFEntry))); } result[i].statDone = 0; str = dp->d_name; len = strlen(str); result[i].real = XtMalloc((unsigned) (len + 2)); (void) strcat(strcpy(result[i].real, str), " "); if (len > maxChars) maxChars = len; result[i].shown = result[i].real; i++; } qsort((char *) result, (size_t) i, sizeof(SFEntry), SFcompareEntries); dir->entries = result; dir->nEntries = i; dir->nChars = maxChars + 1; closedir(dirp); return 0; } /***************** SFinternal.h */ #include <sys/param.h> #include <X11/cursorfont.h> #include <X11/Composite.h> #include <X11/Shell.h> #ifdef FEAT_GUI_NEXTAW # include <X11/neXtaw/Form.h> # include <X11/neXtaw/Command.h> # include <X11/neXtaw/Label.h> #else #include <X11/Xaw/Form.h> #include <X11/Xaw/Command.h> #include <X11/Xaw/Label.h> #endif static char *oneLineTextEditTranslations = "\ <Key>Return: redraw-display()\n\ Ctrl<Key>M: redraw-display()\n\ "; static void SFexposeList __ARGS((Widget w, XtPointer n, XEvent *event, Boolean *cont)); static void SFexposeList(w, n, event, cont) Widget w UNUSED; XtPointer n; XEvent *event; Boolean *cont UNUSED; { if ((event->type == NoExpose) || event->xexpose.count) return; SFdrawList((int)(long)n, SF_DO_NOT_SCROLL); } static void SFmodVerifyCallback __ARGS((Widget w, XtPointer client_data, XEvent *event, Boolean *cont)); static void SFmodVerifyCallback(w, client_data, event, cont) Widget w UNUSED; XtPointer client_data UNUSED; XEvent *event; Boolean *cont UNUSED; { char buf[2]; if ((XLookupString(&(event->xkey), buf, 2, NULL, NULL) == 1) && ((*buf) == '\r')) SFstatus = SEL_FILE_OK; else SFstatus = SEL_FILE_TEXT; } static void SFokCallback __ARGS((Widget w, XtPointer cl, XtPointer cd)); static void SFokCallback(w, cl, cd) Widget w UNUSED; XtPointer cl UNUSED; XtPointer cd UNUSED; { SFstatus = SEL_FILE_OK; } static XtCallbackRec SFokSelect[] = { { SFokCallback, (XtPointer) NULL }, { NULL, (XtPointer) NULL }, }; static void SFcancelCallback __ARGS((Widget w, XtPointer cl, XtPointer cd)); static void SFcancelCallback(w, cl, cd) Widget w UNUSED; XtPointer cl UNUSED; XtPointer cd UNUSED; { SFstatus = SEL_FILE_CANCEL; } static XtCallbackRec SFcancelSelect[] = { { SFcancelCallback, (XtPointer) NULL }, { NULL, (XtPointer) NULL }, }; static void SFdismissAction __ARGS((Widget w, XEvent *event, String *params, Cardinal *num_params)); static void SFdismissAction(w, event, params, num_params) Widget w UNUSED; XEvent *event; String *params UNUSED; Cardinal *num_params UNUSED; { if (event->type == ClientMessage && (Atom)event->xclient.data.l[0] != SFwmDeleteWindow) return; SFstatus = SEL_FILE_CANCEL; } static char *wmDeleteWindowTranslation = "\ <Message>WM_PROTOCOLS: SelFileDismiss()\n\ "; static XtActionsRec actions[] = { {"SelFileDismiss", SFdismissAction}, }; static void SFsetColors(bg, fg, scroll_bg, scroll_fg) guicolor_T bg; guicolor_T fg; guicolor_T scroll_bg; guicolor_T scroll_fg; { if (selFileForm) { XtVaSetValues(selFileForm, XtNbackground, bg, XtNforeground, fg, XtNborderColor, bg, NULL); } { int i; for (i = 0; i < 3; ++i) { if (selFileLists[i]) { XtVaSetValues(selFileLists[i], XtNbackground, bg, XtNforeground, fg, XtNborderColor, fg, NULL); } } } if (selFileOK) { XtVaSetValues(selFileOK, XtNbackground, bg, XtNforeground, fg, XtNborderColor, fg, NULL); } if (selFileCancel) { XtVaSetValues(selFileCancel, XtNbackground, bg, XtNforeground, fg, XtNborderColor, fg, NULL); } if (selFilePrompt) { XtVaSetValues(selFilePrompt, XtNbackground, bg, XtNforeground, fg, NULL); } if (gui.dpy) { XSetBackground(gui.dpy, SFtextGC, bg); XSetForeground(gui.dpy, SFtextGC, fg); XSetForeground(gui.dpy, SFlineGC, fg); /* This is an xor GC, so combine the fg and background */ XSetBackground(gui.dpy, SFinvertGC, fg ^ bg); XSetForeground(gui.dpy, SFinvertGC, fg ^ bg); } if (selFileHScroll) { XtVaSetValues(selFileHScroll, XtNbackground, scroll_bg, XtNforeground, scroll_fg, XtNborderColor, fg, NULL); } { int i; for (i = 0; i < 3; i++) { XtVaSetValues(selFileVScrolls[i], XtNbackground, scroll_bg, XtNforeground, scroll_fg, XtNborderColor, fg, NULL); XtVaSetValues(selFileHScrolls[i], XtNbackground, scroll_bg, XtNforeground, scroll_fg, XtNborderColor, fg, NULL); } } } static void SFcreateWidgets(toplevel, prompt, ok, cancel) Widget toplevel; char *prompt; char *ok; char *cancel; { Cardinal n; int listWidth, listHeight; int listSpacing = 10; int scrollThickness = 15; int hScrollX, hScrollY; int vScrollX, vScrollY; selFile = XtVaAppCreateShell("selFile", "SelFile", transientShellWidgetClass, SFdisplay, XtNtransientFor, toplevel, XtNtitle, prompt, NULL); /* Add WM_DELETE_WINDOW protocol */ XtAppAddActions(XtWidgetToApplicationContext(selFile), actions, XtNumber(actions)); XtOverrideTranslations(selFile, XtParseTranslationTable(wmDeleteWindowTranslation)); selFileForm = XtVaCreateManagedWidget("selFileForm", formWidgetClass, selFile, XtNdefaultDistance, 30, XtNforeground, SFfore, XtNbackground, SFback, XtNborderColor, SFback, NULL); selFilePrompt = XtVaCreateManagedWidget("selFilePrompt", labelWidgetClass, selFileForm, XtNlabel, prompt, XtNresizable, True, XtNtop, XtChainTop, XtNbottom, XtChainTop, XtNleft, XtChainLeft, XtNright, XtChainLeft, XtNborderWidth, 0, XtNforeground, SFfore, XtNbackground, SFback, NULL); /* XtVaGetValues(selFilePrompt, XtNforeground, &SFfore, XtNbackground, &SFback, NULL); */ SFinitFont(); SFentryWidth = SFbesideText + SFcharsPerEntry * SFcharWidth + SFbesideText; SFentryHeight = SFaboveAndBelowText + SFcharHeight + SFaboveAndBelowText; listWidth = SFlineToTextH + SFentryWidth + SFlineToTextH + 1 + scrollThickness; listHeight = SFlineToTextV + SFentryHeight + SFlineToTextV + 1 + SFlineToTextV + SFlistSize * SFentryHeight + SFlineToTextV + 1 + scrollThickness; SFpathScrollWidth = 3 * listWidth + 2 * listSpacing + 4; hScrollX = -1; hScrollY = SFlineToTextV + SFentryHeight + SFlineToTextV + 1 + SFlineToTextV + SFlistSize * SFentryHeight + SFlineToTextV; SFhScrollWidth = SFlineToTextH + SFentryWidth + SFlineToTextH; vScrollX = SFlineToTextH + SFentryWidth + SFlineToTextH; vScrollY = SFlineToTextV + SFentryHeight + SFlineToTextV; SFvScrollHeight = SFlineToTextV + SFlistSize * SFentryHeight + SFlineToTextV; SFupperX = SFlineToTextH + SFentryWidth + SFlineToTextH - 1; SFlowerY = SFlineToTextV + SFentryHeight + SFlineToTextV + 1 + SFlineToTextV; SFupperY = SFlineToTextV + SFentryHeight + SFlineToTextV + 1 + SFlineToTextV + SFlistSize * SFentryHeight - 1; SFtextX = SFlineToTextH + SFbesideText; SFtextYoffset = SFlowerY + SFaboveAndBelowText + SFcharAscent; SFsegs[0].x1 = 0; SFsegs[0].y1 = vScrollY; SFsegs[0].x2 = vScrollX - 1; SFsegs[0].y2 = vScrollY; SFsegs[1].x1 = vScrollX; SFsegs[1].y1 = 0; SFsegs[1].x2 = vScrollX; SFsegs[1].y2 = vScrollY - 1; SFcompletionSegs[0].x1 = SFcompletionSegs[0].x2 = SFlineToTextH; SFcompletionSegs[1].x1 = SFcompletionSegs[1].x2 = SFlineToTextH + SFentryWidth - 1; selFileField = XtVaCreateManagedWidget("selFileField", asciiTextWidgetClass, selFileForm, XtNwidth, 3 * listWidth + 2 * listSpacing + 4, XtNborderColor, SFfore, XtNfromVert, selFilePrompt, XtNvertDistance, 10, XtNresizable, True, XtNtop, XtChainTop, XtNbottom, XtChainTop, XtNleft, XtChainLeft, XtNright, XtChainLeft, XtNstring, SFtextBuffer, XtNlength, MAXPATHL, XtNeditType, XawtextEdit, XtNwrap, XawtextWrapWord, XtNresize, XawtextResizeHeight, XtNuseStringInPlace, True, NULL); XtOverrideTranslations(selFileField, XtParseTranslationTable(oneLineTextEditTranslations)); XtSetKeyboardFocus(selFileForm, selFileField); selFileHScroll = XtVaCreateManagedWidget("selFileHScroll", #ifdef FEAT_GUI_NEXTAW scrollbarWidgetClass, selFileForm, #else vim_scrollbarWidgetClass, selFileForm, #endif XtNorientation, XtorientHorizontal, XtNwidth, SFpathScrollWidth, XtNheight, scrollThickness, XtNborderColor, SFfore, XtNfromVert, selFileField, XtNvertDistance, 30, XtNtop, XtChainTop, XtNbottom, XtChainTop, XtNleft, XtChainLeft, XtNright, XtChainLeft, XtNforeground, gui.scroll_fg_pixel, XtNbackground, gui.scroll_bg_pixel, #ifndef FEAT_GUI_NEXTAW XtNlimitThumb, 1, #endif NULL); XtAddCallback(selFileHScroll, XtNjumpProc, (XtCallbackProc) SFpathSliderMovedCallback, (XtPointer)NULL); XtAddCallback(selFileHScroll, XtNscrollProc, (XtCallbackProc) SFpathAreaSelectedCallback, (XtPointer)NULL); selFileLists[0] = XtVaCreateManagedWidget("selFileList1", compositeWidgetClass, selFileForm, XtNwidth, listWidth, XtNheight, listHeight, XtNforeground, SFfore, XtNbackground, SFback, XtNborderColor, SFfore, XtNfromVert, selFileHScroll, XtNvertDistance, 10, XtNtop, XtChainTop, XtNbottom, XtChainTop, XtNleft, XtChainLeft, XtNright, XtChainLeft, NULL); selFileLists[1] = XtVaCreateManagedWidget("selFileList2", compositeWidgetClass, selFileForm, XtNwidth, listWidth, XtNheight, listHeight, XtNforeground, SFfore, XtNbackground, SFback, XtNborderColor, SFfore, XtNfromHoriz, selFileLists[0], XtNfromVert, selFileHScroll, XtNhorizDistance, listSpacing, XtNvertDistance, 10, XtNtop, XtChainTop, XtNbottom, XtChainTop, XtNleft, XtChainLeft, XtNright, XtChainLeft, NULL); selFileLists[2] = XtVaCreateManagedWidget("selFileList3", compositeWidgetClass, selFileForm, XtNwidth, listWidth, XtNheight, listHeight, XtNforeground, SFfore, XtNbackground, SFback, XtNborderColor, SFfore, XtNfromHoriz, selFileLists[1], XtNfromVert, selFileHScroll, XtNhorizDistance, listSpacing, XtNvertDistance, 10, XtNtop, XtChainTop, XtNbottom, XtChainTop, XtNleft, XtChainLeft, XtNright, XtChainLeft, NULL); for (n = 0; n < 3; n++) { selFileVScrolls[n] = XtVaCreateManagedWidget("selFileVScroll", #ifdef FEAT_GUI_NEXTAW scrollbarWidgetClass, selFileLists[n], #else vim_scrollbarWidgetClass, selFileLists[n], #endif XtNx, vScrollX, XtNy, vScrollY, XtNwidth, scrollThickness, XtNheight, SFvScrollHeight, XtNborderColor, SFfore, XtNforeground, gui.scroll_fg_pixel, XtNbackground, gui.scroll_bg_pixel, #ifndef FEAT_GUI_NEXTAW XtNlimitThumb, 1, #endif NULL); XtAddCallback(selFileVScrolls[n], XtNjumpProc, (XtCallbackProc)SFvFloatSliderMovedCallback, (XtPointer)(long_u)n); XtAddCallback(selFileVScrolls[n], XtNscrollProc, (XtCallbackProc)SFvAreaSelectedCallback, (XtPointer)n); selFileHScrolls[n] = XtVaCreateManagedWidget("selFileHScroll", #ifdef FEAT_GUI_NEXTAW scrollbarWidgetClass, selFileLists[n], #else vim_scrollbarWidgetClass, selFileLists[n], #endif XtNorientation, XtorientHorizontal, XtNx, hScrollX, XtNy, hScrollY, XtNwidth, SFhScrollWidth, XtNheight, scrollThickness, XtNborderColor, SFfore, XtNforeground, gui.scroll_fg_pixel, XtNbackground, gui.scroll_bg_pixel, #ifndef FEAT_GUI_NEXTAW XtNlimitThumb, 1, #endif NULL); XtAddCallback(selFileHScrolls[n], XtNjumpProc, (XtCallbackProc)SFhSliderMovedCallback, (XtPointer)(long_u)n); XtAddCallback(selFileHScrolls[n], XtNscrollProc, (XtCallbackProc)SFhAreaSelectedCallback, (XtPointer)n); } selFileOK = XtVaCreateManagedWidget("selFileOK", commandWidgetClass, selFileForm, XtNlabel, ok, XtNresizable, True, XtNcallback, SFokSelect, XtNforeground, SFfore, XtNbackground, SFback, XtNborderColor, SFfore, XtNfromHoriz, selFileLists[0], XtNfromVert, selFileLists[0], XtNvertDistance, 30, XtNtop, XtChainTop, XtNbottom, XtChainTop, XtNleft, XtChainLeft, XtNright, XtChainLeft, NULL); selFileCancel = XtVaCreateManagedWidget("selFileCancel", commandWidgetClass, selFileForm, XtNlabel, cancel, XtNresizable, True, XtNcallback, SFcancelSelect, XtNforeground, SFfore, XtNbackground, SFback, XtNborderColor, SFfore, XtNfromHoriz, selFileOK, XtNfromVert, selFileLists[0], XtNhorizDistance, 30, XtNvertDistance, 30, XtNtop, XtChainTop, XtNbottom, XtChainTop, XtNleft, XtChainLeft, XtNright, XtChainLeft, NULL); XtSetMappedWhenManaged(selFile, False); XtRealizeWidget(selFile); /* Add WM_DELETE_WINDOW protocol */ SFwmDeleteWindow = XInternAtom(SFdisplay, "WM_DELETE_WINDOW", False); XSetWMProtocols(SFdisplay, XtWindow(selFile), &SFwmDeleteWindow, 1); SFcreateGC(); for (n = 0; n < 3; n++) { XtAddEventHandler(selFileLists[n], ExposureMask, True, (XtEventHandler)SFexposeList, (XtPointer)(long_u)n); XtAddEventHandler(selFileLists[n], EnterWindowMask, False, (XtEventHandler)SFenterList, (XtPointer)(long_u)n); XtAddEventHandler(selFileLists[n], LeaveWindowMask, False, (XtEventHandler)SFleaveList, (XtPointer)(long_u)n); XtAddEventHandler(selFileLists[n], PointerMotionMask, False, (XtEventHandler)SFmotionList, (XtPointer)(long_u)n); XtAddEventHandler(selFileLists[n], ButtonPressMask, False, (XtEventHandler)SFbuttonPressList, (XtPointer)(long_u)n); XtAddEventHandler(selFileLists[n], ButtonReleaseMask, False, (XtEventHandler)SFbuttonReleaseList, (XtPointer)(long_u)n); } XtAddEventHandler(selFileField, KeyPressMask, False, SFmodVerifyCallback, (XtPointer)NULL); SFapp = XtWidgetToApplicationContext(selFile); } static void SFtextChanged() { #if defined(FEAT_XFONTSET) && defined(XtNinternational) if ((unsigned long)_XawTextFormat((TextWidget)selFileField) == XawFmtWide) { wchar_t *wcbuf=(wchar_t *)SFtextBuffer; if ((wcbuf[0] == L'/') || (wcbuf[0] == L'~')) { (void) wcstombs(SFcurrentPath, wcbuf, MAXPATHL); SFtextPos = XawTextGetInsertionPoint(selFileField); } else { strcpy(SFcurrentPath, SFstartDir); (void) wcstombs(SFcurrentPath + strlen(SFcurrentPath), wcbuf, MAXPATHL); SFtextPos = XawTextGetInsertionPoint(selFileField) + strlen(SFstartDir); } } else #endif if ((SFtextBuffer[0] == '/') || (SFtextBuffer[0] == '~')) { (void) strcpy(SFcurrentPath, SFtextBuffer); SFtextPos = XawTextGetInsertionPoint(selFileField); } else { (void) strcat(strcpy(SFcurrentPath, SFstartDir), SFtextBuffer); SFtextPos = XawTextGetInsertionPoint(selFileField) + strlen(SFstartDir); } if (!SFworkProcAdded) { (void) XtAppAddWorkProc(SFapp, (XtWorkProc)SFworkProc, NULL); SFworkProcAdded = 1; } SFupdatePath(); } static char * SFgetText() { #if defined(FEAT_XFONTSET) && defined(XtNinternational) char *buf; if ((unsigned long)_XawTextFormat((TextWidget)selFileField) == XawFmtWide) { wchar_t *wcbuf; int mbslength; XtVaGetValues(selFileField, XtNstring, &wcbuf, NULL); mbslength = wcstombs(NULL, wcbuf, 0); /* Hack: some broken wcstombs() returns zero, just get a large buffer */ if (mbslength == 0 && wcbuf != NULL && wcbuf[0] != 0) mbslength = MAXPATHL; buf=(char *)XtMalloc(mbslength + 1); wcstombs(buf, wcbuf, mbslength +1); return buf; } #endif return (char *)vim_strsave((char_u *)SFtextBuffer); } static void SFprepareToReturn() { SFstatus = SEL_FILE_NULL; XtRemoveGrab(selFile); XtUnmapWidget(selFile); XtRemoveTimeOut(SFdirModTimerId); if (SFchdir(SFstartDir)) { EMSG(_("E614: vim_SelFile: can't return to current directory")); SFstatus = SEL_FILE_CANCEL; } } char * vim_SelFile(toplevel, prompt, init_path, show_entry, x, y, fg, bg, scroll_fg, scroll_bg) Widget toplevel; char *prompt; char *init_path; int (*show_entry)(); int x, y; guicolor_T fg, bg; guicolor_T scroll_fg, scroll_bg; /* The "Scrollbar" group colors */ { static int firstTime = 1; XEvent event; char *name_return; if (prompt == NULL) prompt = _("Pathname:"); SFfore = fg; SFback = bg; if (mch_dirname((char_u *)SFstartDir, MAXPATHL) == FAIL) { EMSG(_("E615: vim_SelFile: can't get current directory")); return NULL; } if (firstTime) { firstTime = 0; SFdisplay = XtDisplay(toplevel); SFcreateWidgets(toplevel, prompt, _("OK"), _("Cancel")); } else { XtVaSetValues(selFilePrompt, XtNlabel, prompt, NULL); XtVaSetValues(selFile, XtNtitle, prompt, NULL); SFsetColors(bg, fg, scroll_bg, scroll_fg); } XtVaSetValues(selFile, XtNx, x, XtNy, y, NULL); XtMapWidget(selFile); (void)strcat(SFstartDir, "/"); (void)strcpy(SFcurrentDir, SFstartDir); if (init_path) { if (init_path[0] == '/') { (void)strcpy(SFcurrentPath, init_path); if (strncmp(SFcurrentPath, SFstartDir, strlen(SFstartDir))) SFsetText(SFcurrentPath); else SFsetText(&(SFcurrentPath[strlen(SFstartDir)])); } else { (void)strcat(strcpy(SFcurrentPath, SFstartDir), init_path); SFsetText(&(SFcurrentPath[strlen(SFstartDir)])); } } else (void)strcpy(SFcurrentPath, SFstartDir); SFfunc = show_entry; SFtextChanged(); XtAddGrab(selFile, True, True); SFdirModTimerId = XtAppAddTimeOut(SFapp, (unsigned long) 1000, SFdirModTimer, (XtPointer) NULL); for (;;) { XtAppNextEvent(SFapp, &event); XtDispatchEvent(&event); switch (SFstatus) { case SEL_FILE_TEXT: SFstatus = SEL_FILE_NULL; SFtextChanged(); break; case SEL_FILE_OK: name_return = SFgetText(); SFprepareToReturn(); return name_return; case SEL_FILE_CANCEL: SFprepareToReturn(); return NULL; case SEL_FILE_NULL: break; } } } #endif /* FEAT_BROWSE */
zyz2011-vim
src/gui_at_fs.c
C
gpl2
62,315
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. */ /* * Win32 (Windows NT and Windows 95) machine-dependent things. */ #include "os_dos.h" /* common MS-DOS and Win32 stuff */ #ifndef __CYGWIN__ #include <direct.h> /* for _mkdir() */ #endif /* Stop the VC2005 compiler from nagging. */ #if _MSC_VER >= 1400 # define _CRT_SECURE_NO_DEPRECATE # define _CRT_NONSTDC_NO_DEPRECATE #endif #define BINARY_FILE_IO #define USE_EXE_NAME /* use argv[0] for $VIM */ #define SYNC_DUP_CLOSE /* sync() a file with dup() and close() */ #define USE_TERM_CONSOLE #ifndef HAVE_STRING_H # define HAVE_STRING_H #endif #ifndef HAVE_MATH_H # define HAVE_MATH_H #endif #define HAVE_STRCSPN #ifndef __GNUC__ #define HAVE_STRICMP #define HAVE_STRNICMP #endif #ifndef HAVE_STRFTIME # define HAVE_STRFTIME /* guessed */ #endif #define HAVE_MEMSET #ifndef HAVE_LOCALE_H # define HAVE_LOCALE_H 1 #endif #ifndef HAVE_FCNTL_H # define HAVE_FCNTL_H #endif #ifndef HAVE_STDARG_H # define HAVE_STDARG_H #endif #define HAVE_QSORT #define HAVE_ST_MODE /* have stat.st_mode */ #define FEAT_SHORTCUT /* resolve shortcuts */ #if !defined(__MINGW32__) \ && !defined(__CYGWIN__) \ && (!defined(__BORLANDC__) || __BORLANDC__ >= 0x550) \ && (!defined(_MSC_VER) || _MSC_VER > 1020) /* * Access Control List (actually security info). * Mingw and Cygwin don't have the acl stuff. * Borland only in version 5.5 and later. * MSVC in 5.0, not in 4.2, don't know about 4.3. */ # define HAVE_ACL #endif #define USE_FNAME_CASE /* adjust case of file names */ #if !defined(FEAT_CLIPBOARD) && defined(FEAT_VISUAL) && defined(FEAT_MOUSE) # define FEAT_CLIPBOARD /* include clipboard support */ #endif #if defined(__DATE__) && defined(__TIME__) # define HAVE_DATE_TIME #endif #ifndef FEAT_GUI_W32 /* GUI works different */ # define BREAKCHECK_SKIP 1 /* call mch_breakcheck() each time, it's fast */ #endif #define HAVE_AVAIL_MEM #define HAVE_PUTENV /* at least Bcc 5.2 and MSC have it */ #ifdef FEAT_GUI_W32 # define NO_CONSOLE /* don't included console-only code */ #endif /* toupper() is not really broken, but it's very slow. Probably because of * using Unicode characters on Windows NT */ #define BROKEN_TOUPPER #define FNAME_ILLEGAL "\"*?><|" /* illegal characters in a file name */ #include <stdlib.h> #include <time.h> #include <sys/types.h> #ifndef STRICT # define STRICT #endif #ifndef COBJMACROS # define COBJMACROS /* For OLE: Enable "friendlier" access to objects */ #endif #include <windows.h> /* * Win32 has plenty of memory, use large buffers */ #define CMDBUFFSIZE 1024 /* size of the command processing buffer */ /* _MAX_PATH is only 256 (stdlib.h), but we want more for the 'path' option, * thus use a larger number. */ #define MAXPATHL 1024 #ifndef BASENAMELEN # define BASENAMELEN (_MAX_PATH - 5) /* length of base of file name */ #endif #define TEMPNAMELEN _MAX_PATH /* length of temp file name path */ #ifndef DFLT_MAXMEM # define DFLT_MAXMEM (2*1024) /* use up to 2 Mbyte for a buffer */ #endif #ifndef DFLT_MAXMEMTOT # define DFLT_MAXMEMTOT (5*1024) /* use up to 5 Mbyte for Vim */ #endif #if defined(_MSC_VER) || defined(__BORLANDC__) /* Support for __try / __except. All versions of MSVC and Borland C are * expected to have this. Any other compilers that support it? */ # define HAVE_TRY_EXCEPT 1 # include <malloc.h> /* for _resetstkoflw() */ # if defined(_MSC_VER) && (_MSC_VER >= 1300) # define RESETSTKOFLW _resetstkoflw # else # define RESETSTKOFLW myresetstkoflw # define MYRESETSTKOFLW # endif #endif /* * Some simple debugging macros that look and behave a lot like their * namesakes in MFC. */ #ifdef _DEBUG # if defined(_MSC_VER) && (_MSC_VER >= 1000) /* Use the new debugging tools in Visual C++ 4.x */ # include <crtdbg.h> # define ASSERT(f) _ASSERT(f) # else # include <assert.h> # define ASSERT(f) assert(f) # endif # define TRACE Trace # define TRACE0(sz) Trace(_T("%s"), _T(sz)) # define TRACE1(sz, p1) Trace(_T(sz), p1) # define TRACE2(sz, p1, p2) Trace(_T(sz), p1, p2) # define TRACE3(sz, p1, p2, p3) Trace(_T(sz), p1, p2, p3) # define TRACE4(sz, p1, p2, p3, p4) Trace(_T(sz), p1, p2, p3, p4) /* In debug version, writes trace messages to debug stream */ void __cdecl Trace(char *pszFormat, ...); #else /* !_DEBUG */ /* These macros should all compile away to nothing */ # define ASSERT(f) ((void)0) # define TRACE 1 ? (void)0 : printf # define TRACE0(sz) # define TRACE1(sz, p1) # define TRACE2(sz, p1, p2) # define TRACE3(sz, p1, p2, p3) # define TRACE4(sz, p1, p2, p3, p4) #endif /* !_DEBUG */ #define ASSERT_POINTER(p, type) \ ASSERT(((p) != NULL) && IsValidAddress((p), sizeof(type), FALSE)) #define ASSERT_NULL_OR_POINTER(p, type) \ ASSERT(((p) == NULL) || IsValidAddress((p), sizeof(type), FALSE)) #define mch_setenv(name, val, x) setenv(name, val, x) #define mch_getenv(x) (char_u *)getenv((char *)(x)) #ifdef __BORLANDC__ # define vim_mkdir(x, y) mkdir(x) #else # define vim_mkdir(x, y) mch_mkdir(x) #endif /* Enable common dialogs input unicode from IME if posible. */ #ifdef FEAT_MBYTE /* The variables are defined in os_win32.c. */ extern LRESULT (WINAPI *pDispatchMessage)(LPMSG); extern BOOL (WINAPI *pGetMessage)(LPMSG, HWND, UINT, UINT); extern BOOL (WINAPI *pIsDialogMessage)(HWND, LPMSG); extern BOOL (WINAPI *pPeekMessage)(LPMSG, HWND, UINT, UINT, UINT); #else # define pDispatchMessage DispatchMessage # define pGetMessage GetMessage # define pIsDialogMessage IsDialogMessage # define pPeekMessage PeekMessage #endif
zyz2011-vim
src/os_win32.h
C
gpl2
5,705
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * os_mswin.c * * Routines common to both Win16 and Win32. */ #ifdef WIN16 # ifdef __BORLANDC__ # pragma warn -par # pragma warn -ucp # pragma warn -use # pragma warn -aus # endif #endif #include "vim.h" #ifdef WIN16 # define SHORT_FNAME /* always 8.3 file name */ # include <dos.h> # include <string.h> #endif #include <sys/types.h> #include <signal.h> #include <limits.h> #include <process.h> #undef chdir #ifdef __GNUC__ # ifndef __MINGW32__ # include <dirent.h> # endif #else # include <direct.h> #endif #if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32) # include <shellapi.h> #endif #if defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT) # include <dlgs.h> # ifdef WIN3264 # include <winspool.h> # else # include <print.h> # endif # include <commdlg.h> #endif #ifdef __MINGW32__ # ifndef FROM_LEFT_1ST_BUTTON_PRESSED # define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001 # endif # ifndef RIGHTMOST_BUTTON_PRESSED # define RIGHTMOST_BUTTON_PRESSED 0x0002 # endif # ifndef FROM_LEFT_2ND_BUTTON_PRESSED # define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004 # endif # ifndef FROM_LEFT_3RD_BUTTON_PRESSED # define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008 # endif # ifndef FROM_LEFT_4TH_BUTTON_PRESSED # define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010 # endif /* * EventFlags */ # ifndef MOUSE_MOVED # define MOUSE_MOVED 0x0001 # endif # ifndef DOUBLE_CLICK # define DOUBLE_CLICK 0x0002 # endif #endif /* * When generating prototypes for Win32 on Unix, these lines make the syntax * errors disappear. They do not need to be correct. */ #ifdef PROTO #define WINAPI #define WINBASEAPI typedef int BOOL; typedef int CALLBACK; typedef int COLORREF; typedef int CONSOLE_CURSOR_INFO; typedef int COORD; typedef int DWORD; typedef int ENUMLOGFONT; typedef int HANDLE; typedef int HDC; typedef int HFONT; typedef int HICON; typedef int HWND; typedef int INPUT_RECORD; typedef int KEY_EVENT_RECORD; typedef int LOGFONT; typedef int LPARAM; typedef int LPBOOL; typedef int LPCSTR; typedef int LPCWSTR; typedef int LPSTR; typedef int LPTSTR; typedef int LPWSTR; typedef int LRESULT; typedef int MOUSE_EVENT_RECORD; typedef int NEWTEXTMETRIC; typedef int PACL; typedef int PRINTDLG; typedef int PSECURITY_DESCRIPTOR; typedef int PSID; typedef int SECURITY_INFORMATION; typedef int SHORT; typedef int SMALL_RECT; typedef int TEXTMETRIC; typedef int UINT; typedef int WCHAR; typedef int WORD; typedef int WPARAM; typedef void VOID; #endif /* Record all output and all keyboard & mouse input */ /* #define MCH_WRITE_DUMP */ #ifdef MCH_WRITE_DUMP FILE* fdDump = NULL; #endif #ifdef WIN3264 extern DWORD g_PlatformId; #endif #ifndef FEAT_GUI_MSWIN extern char g_szOrigTitle[]; #endif #ifdef FEAT_GUI extern HWND s_hwnd; #else static HWND s_hwnd = 0; /* console window handle, set by GetConsoleHwnd() */ #endif extern int WSInitialized; /* Don't generate prototypes here, because some systems do have these * functions. */ #if defined(__GNUC__) && !defined(PROTO) # ifndef __MINGW32__ int _stricoll(char *a, char *b) { // the ANSI-ish correct way is to use strxfrm(): char a_buff[512], b_buff[512]; // file names, so this is enough on Win32 strxfrm(a_buff, a, 512); strxfrm(b_buff, b, 512); return strcoll(a_buff, b_buff); } char * _fullpath(char *buf, char *fname, int len) { LPTSTR toss; return (char *)GetFullPathName(fname, len, buf, &toss); } # endif int _chdrive(int drive) { char temp [3] = "-:"; temp[0] = drive + 'A' - 1; return !SetCurrentDirectory(temp); } #else # ifdef __BORLANDC__ /* being a more ANSI compliant compiler, BorlandC doesn't define _stricoll: * but it does in BC 5.02! */ # if __BORLANDC__ < 0x502 int _stricoll(char *a, char *b) { # if 1 // this is fast but not correct: return stricmp(a, b); # else // the ANSI-ish correct way is to use strxfrm(): char a_buff[512], b_buff[512]; // file names, so this is enough on Win32 strxfrm(a_buff, a, 512); strxfrm(b_buff, b, 512); return strcoll(a_buff, b_buff); # endif } # endif # endif #endif #if defined(FEAT_GUI_MSWIN) || defined(PROTO) /* * GUI version of mch_exit(). * Shut down and exit with status `r' * Careful: mch_exit() may be called before mch_init()! */ void mch_exit(int r) { display_errors(); ml_close_all(TRUE); /* remove all memfiles */ # ifdef FEAT_OLE UninitOLE(); # endif # ifdef FEAT_NETBEANS_INTG if (WSInitialized) { WSInitialized = FALSE; WSACleanup(); } # endif #ifdef DYNAMIC_GETTEXT dyn_libintl_end(); #endif if (gui.in_use) gui_exit(r); #ifdef EXITFREE free_all_mem(); #endif exit(r); } #endif /* FEAT_GUI_MSWIN */ /* * Init the tables for toupper() and tolower(). */ void mch_early_init(void) { int i; #ifdef WIN3264 PlatformId(); #endif /* Init the tables for toupper() and tolower() */ for (i = 0; i < 256; ++i) toupper_tab[i] = tolower_tab[i] = i; #ifdef WIN3264 CharUpperBuff(toupper_tab, 256); CharLowerBuff(tolower_tab, 256); #else AnsiUpperBuff(toupper_tab, 256); AnsiLowerBuff(tolower_tab, 256); #endif #if defined(FEAT_MBYTE) && !defined(FEAT_GUI) (void)get_cmd_argsW(NULL); #endif } /* * Return TRUE if the input comes from a terminal, FALSE otherwise. */ int mch_input_isatty() { #ifdef FEAT_GUI_MSWIN return OK; /* GUI always has a tty */ #else if (isatty(read_cmd_fd)) return TRUE; return FALSE; #endif } #ifdef FEAT_TITLE /* * mch_settitle(): set titlebar of our window */ void mch_settitle( char_u *title, char_u *icon) { # ifdef FEAT_GUI_MSWIN gui_mch_settitle(title, icon); # else if (title != NULL) { # ifdef FEAT_MBYTE if (enc_codepage >= 0 && (int)GetACP() != enc_codepage) { /* Convert the title from 'encoding' to the active codepage. */ WCHAR *wp = enc_to_utf16(title, NULL); int n; if (wp != NULL) { n = SetConsoleTitleW(wp); vim_free(wp); if (n != 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) return; } } # endif SetConsoleTitle(title); } # endif } /* * Restore the window/icon title. * which is one of: * 1: Just restore title * 2: Just restore icon (which we don't have) * 3: Restore title and icon (which we don't have) */ /*ARGSUSED*/ void mch_restore_title( int which) { #ifndef FEAT_GUI_MSWIN mch_settitle((which & 1) ? g_szOrigTitle : NULL, NULL); #endif } /* * Return TRUE if we can restore the title (we can) */ int mch_can_restore_title() { return TRUE; } /* * Return TRUE if we can restore the icon title (we can't) */ int mch_can_restore_icon() { return FALSE; } #endif /* FEAT_TITLE */ /* * Get absolute file name into buffer "buf" of length "len" bytes, * turning all '/'s into '\\'s and getting the correct case of each component * of the file name. Append a (back)slash to a directory name. * When 'shellslash' set do it the other way around. * Return OK or FAIL. */ /*ARGSUSED*/ int mch_FullName( char_u *fname, char_u *buf, int len, int force) { int nResult = FAIL; #ifdef __BORLANDC__ if (*fname == NUL) /* Borland behaves badly here - make it consistent */ nResult = mch_dirname(buf, len); else #endif { #ifdef FEAT_MBYTE if (enc_codepage >= 0 && (int)GetACP() != enc_codepage # ifdef __BORLANDC__ /* Wide functions of Borland C 5.5 do not work on Windows 98. */ && g_PlatformId == VER_PLATFORM_WIN32_NT # endif ) { WCHAR *wname; WCHAR wbuf[MAX_PATH]; char_u *cname = NULL; /* Use the wide function: * - convert the fname from 'encoding' to UCS2. * - invoke _wfullpath() * - convert the result from UCS2 to 'encoding'. */ wname = enc_to_utf16(fname, NULL); if (wname != NULL && _wfullpath(wbuf, wname, MAX_PATH - 1) != NULL) { cname = utf16_to_enc((short_u *)wbuf, NULL); if (cname != NULL) { vim_strncpy(buf, cname, len - 1); nResult = OK; } } vim_free(wname); vim_free(cname); } if (nResult == FAIL) /* fall back to non-wide function */ #endif { if (_fullpath(buf, fname, len - 1) == NULL) { /* failed, use relative path name */ vim_strncpy(buf, fname, len - 1); } else nResult = OK; } } #ifdef USE_FNAME_CASE fname_case(buf, len); #else slash_adjust(buf); #endif return nResult; } /* * Return TRUE if "fname" does not depend on the current directory. */ int mch_isFullName(char_u *fname) { char szName[_MAX_PATH + 1]; /* A name like "d:/foo" and "//server/share" is absolute */ if ((fname[0] && fname[1] == ':' && (fname[2] == '/' || fname[2] == '\\')) || (fname[0] == fname[1] && (fname[0] == '/' || fname[0] == '\\'))) return TRUE; /* A name that can't be made absolute probably isn't absolute. */ if (mch_FullName(fname, szName, _MAX_PATH, FALSE) == FAIL) return FALSE; return pathcmp(fname, szName, -1) == 0; } /* * Replace all slashes by backslashes. * This used to be the other way around, but MS-DOS sometimes has problems * with slashes (e.g. in a command name). We can't have mixed slashes and * backslashes, because comparing file names will not work correctly. The * commands that use a file name should try to avoid the need to type a * backslash twice. * When 'shellslash' set do it the other way around. */ void slash_adjust(p) char_u *p; { while (*p) { if (*p == psepcN) *p = psepc; mb_ptr_adv(p); } } /* * stat() can't handle a trailing '/' or '\', remove it first. */ int vim_stat(const char *name, struct stat *stp) { char buf[_MAX_PATH + 1]; char *p; vim_strncpy((char_u *)buf, (char_u *)name, _MAX_PATH); p = buf + strlen(buf); if (p > buf) mb_ptr_back(buf, p); if (p > buf && (*p == '\\' || *p == '/') && p[-1] != ':') *p = NUL; #ifdef FEAT_MBYTE if (enc_codepage >= 0 && (int)GetACP() != enc_codepage # ifdef __BORLANDC__ /* Wide functions of Borland C 5.5 do not work on Windows 98. */ && g_PlatformId == VER_PLATFORM_WIN32_NT # endif ) { WCHAR *wp = enc_to_utf16(buf, NULL); int n; if (wp != NULL) { n = _wstat(wp, (struct _stat *)stp); vim_free(wp); if (n >= 0) return n; /* Retry with non-wide function (for Windows 98). Can't use * GetLastError() here and it's unclear what errno gets set to if * the _wstat() fails for missing wide functions. */ } } #endif return stat(buf, stp); } #if defined(FEAT_GUI_MSWIN) || defined(PROTO) /*ARGSUSED*/ void mch_settmode(int tmode) { /* nothing to do */ } int mch_get_shellsize(void) { /* never used */ return OK; } void mch_set_shellsize(void) { /* never used */ } /* * Rows and/or Columns has changed. */ void mch_new_shellsize(void) { /* never used */ } #endif /* * We have no job control, so fake it by starting a new shell. */ void mch_suspend() { suspend_shell(); } #if defined(USE_MCH_ERRMSG) || defined(PROTO) #ifdef display_errors # undef display_errors #endif /* * Display the saved error message(s). */ void display_errors() { char *p; if (error_ga.ga_data != NULL) { /* avoid putting up a message box with blanks only */ for (p = (char *)error_ga.ga_data; *p; ++p) if (!isspace(*p)) { (void)gui_mch_dialog( #ifdef FEAT_GUI gui.starting ? VIM_INFO : #endif VIM_ERROR, #ifdef FEAT_GUI gui.starting ? (char_u *)_("Message") : #endif (char_u *)_("Error"), p, (char_u *)_("&Ok"), 1, NULL, FALSE); break; } ga_clear(&error_ga); } } #endif /* * Return TRUE if "p" contain a wildcard that can be expanded by * dos_expandpath(). */ int mch_has_exp_wildcard(char_u *p) { for ( ; *p; mb_ptr_adv(p)) { if (vim_strchr((char_u *)"?*[", *p) != NULL || (*p == '~' && p[1] != NUL)) return TRUE; } return FALSE; } /* * Return TRUE if "p" contain a wildcard or a "~1" kind of thing (could be a * shortened file name). */ int mch_has_wildcard(char_u *p) { for ( ; *p; mb_ptr_adv(p)) { if (vim_strchr((char_u *) # ifdef VIM_BACKTICK "?*$[`" # else "?*$[" # endif , *p) != NULL || (*p == '~' && p[1] != NUL)) return TRUE; } return FALSE; } /* * The normal _chdir() does not change the default drive. This one does. * Returning 0 implies success; -1 implies failure. */ int mch_chdir(char *path) { if (path[0] == NUL) /* just checking... */ return -1; if (p_verbose >= 5) { verbose_enter(); smsg((char_u *)"chdir(%s)", path); verbose_leave(); } if (isalpha(path[0]) && path[1] == ':') /* has a drive name */ { /* If we can change to the drive, skip that part of the path. If we * can't then the current directory may be invalid, try using chdir() * with the whole path. */ if (_chdrive(TOLOWER_ASC(path[0]) - 'a' + 1) == 0) path += 2; } if (*path == NUL) /* drive name only */ return 0; #ifdef FEAT_MBYTE if (enc_codepage >= 0 && (int)GetACP() != enc_codepage) { WCHAR *p = enc_to_utf16(path, NULL); int n; if (p != NULL) { n = _wchdir(p); vim_free(p); if (n == 0) return 0; /* Retry with non-wide function (for Windows 98). */ } } #endif return chdir(path); /* let the normal chdir() do the rest */ } /* * Switching off termcap mode is only allowed when Columns is 80, otherwise a * crash may result. It's always allowed on NT or when running the GUI. */ /*ARGSUSED*/ int can_end_termcap_mode( int give_msg) { #ifdef FEAT_GUI_MSWIN return TRUE; /* GUI starts a new console anyway */ #else if (g_PlatformId == VER_PLATFORM_WIN32_NT || Columns == 80) return TRUE; if (give_msg) msg(_("'columns' is not 80, cannot execute external commands")); return FALSE; #endif } #ifdef FEAT_GUI_MSWIN /* * return non-zero if a character is available */ int mch_char_avail() { /* never used */ return TRUE; } #endif /* * set screen mode, always fails. */ /*ARGSUSED*/ int mch_screenmode( char_u *arg) { EMSG(_(e_screenmode)); return FAIL; } #if defined(FEAT_LIBCALL) || defined(PROTO) /* * Call a DLL routine which takes either a string or int param * and returns an allocated string. * Return OK if it worked, FAIL if not. */ # ifdef WIN3264 typedef LPTSTR (*MYSTRPROCSTR)(LPTSTR); typedef LPTSTR (*MYINTPROCSTR)(int); typedef int (*MYSTRPROCINT)(LPTSTR); typedef int (*MYINTPROCINT)(int); # else typedef LPSTR (*MYSTRPROCSTR)(LPSTR); typedef LPSTR (*MYINTPROCSTR)(int); typedef int (*MYSTRPROCINT)(LPSTR); typedef int (*MYINTPROCINT)(int); # endif # ifndef WIN16 /* * Check if a pointer points to a valid NUL terminated string. * Return the length of the string, including terminating NUL. * Returns 0 for an invalid pointer, 1 for an empty string. */ static size_t check_str_len(char_u *str) { SYSTEM_INFO si; MEMORY_BASIC_INFORMATION mbi; size_t length = 0; size_t i; const char *p; /* get page size */ GetSystemInfo(&si); /* get memory information */ if (VirtualQuery(str, &mbi, sizeof(mbi))) { /* pre cast these (typing savers) */ long_u dwStr = (long_u)str; long_u dwBaseAddress = (long_u)mbi.BaseAddress; /* get start address of page that str is on */ long_u strPage = dwStr - (dwStr - dwBaseAddress) % si.dwPageSize; /* get length from str to end of page */ long_u pageLength = si.dwPageSize - (dwStr - strPage); for (p = str; !IsBadReadPtr(p, (UINT)pageLength); p += pageLength, pageLength = si.dwPageSize) for (i = 0; i < pageLength; ++i, ++length) if (p[i] == NUL) return length + 1; } return 0; } # endif int mch_libcall( char_u *libname, char_u *funcname, char_u *argstring, /* NULL when using a argint */ int argint, char_u **string_result,/* NULL when using number_result */ int *number_result) { HINSTANCE hinstLib; MYSTRPROCSTR ProcAdd; MYINTPROCSTR ProcAddI; char_u *retval_str = NULL; int retval_int = 0; size_t len; BOOL fRunTimeLinkSuccess = FALSE; // Get a handle to the DLL module. # ifdef WIN16 hinstLib = LoadLibrary(libname); # else hinstLib = vimLoadLib(libname); # endif // If the handle is valid, try to get the function address. if (hinstLib != NULL) { #ifdef HAVE_TRY_EXCEPT __try { #endif if (argstring != NULL) { /* Call with string argument */ ProcAdd = (MYSTRPROCSTR) GetProcAddress(hinstLib, funcname); if ((fRunTimeLinkSuccess = (ProcAdd != NULL)) != 0) { if (string_result == NULL) retval_int = ((MYSTRPROCINT)ProcAdd)(argstring); else retval_str = (ProcAdd)(argstring); } } else { /* Call with number argument */ ProcAddI = (MYINTPROCSTR) GetProcAddress(hinstLib, funcname); if ((fRunTimeLinkSuccess = (ProcAddI != NULL)) != 0) { if (string_result == NULL) retval_int = ((MYINTPROCINT)ProcAddI)(argint); else retval_str = (ProcAddI)(argint); } } // Save the string before we free the library. // Assume that a "1" result is an illegal pointer. if (string_result == NULL) *number_result = retval_int; else if (retval_str != NULL # ifdef WIN16 && retval_str != (char_u *)1 && retval_str != (char_u *)-1 && !IsBadStringPtr(retval_str, INT_MAX) && (len = strlen(retval_str) + 1) > 0 # else && (len = check_str_len(retval_str)) > 0 # endif ) { *string_result = lalloc((long_u)len, TRUE); if (*string_result != NULL) mch_memmove(*string_result, retval_str, len); } #ifdef HAVE_TRY_EXCEPT } __except(EXCEPTION_EXECUTE_HANDLER) { if (GetExceptionCode() == EXCEPTION_STACK_OVERFLOW) RESETSTKOFLW(); fRunTimeLinkSuccess = 0; } #endif // Free the DLL module. (void)FreeLibrary(hinstLib); } if (!fRunTimeLinkSuccess) { EMSG2(_(e_libcall), funcname); return FAIL; } return OK; } #endif #if defined(FEAT_MBYTE) || defined(PROTO) /* * Convert an UTF-8 string to UTF-16. * "instr[inlen]" is the input. "inlen" is in bytes. * When "outstr" is NULL only return the number of UTF-16 words produced. * Otherwise "outstr" must be a buffer of sufficient size. * Returns the number of UTF-16 words produced. */ int utf8_to_utf16(char_u *instr, int inlen, short_u *outstr, int *unconvlenp) { int outlen = 0; char_u *p = instr; int todo = inlen; int l; int ch; while (todo > 0) { /* Only convert if we have a complete sequence. */ l = utf_ptr2len_len(p, todo); if (l > todo) { /* Return length of incomplete sequence. */ if (unconvlenp != NULL) *unconvlenp = todo; break; } ch = utf_ptr2char(p); if (ch >= 0x10000) { /* non-BMP character, encoding with surrogate pairs */ ++outlen; if (outstr != NULL) { *outstr++ = (0xD800 - (0x10000 >> 10)) + (ch >> 10); *outstr++ = 0xDC00 | (ch & 0x3FF); } } else if (outstr != NULL) *outstr++ = ch; ++outlen; p += l; todo -= l; } return outlen; } /* * Convert an UTF-16 string to UTF-8. * The input is "instr[inlen]" with "inlen" in number of UTF-16 words. * When "outstr" is NULL only return the required number of bytes. * Otherwise "outstr" must be a buffer of sufficient size. * Return the number of bytes produced. */ int utf16_to_utf8(short_u *instr, int inlen, char_u *outstr) { int outlen = 0; int todo = inlen; short_u *p = instr; int l; int ch, ch2; while (todo > 0) { ch = *p; if (ch >= 0xD800 && ch <= 0xDBFF && todo > 1) { /* surrogate pairs handling */ ch2 = p[1]; if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) { ch = ((ch - 0xD800) << 10) + (ch2 & 0x3FF) + 0x10000; ++p; --todo; } } if (outstr != NULL) { l = utf_char2bytes(ch, outstr); outstr += l; } else l = utf_char2len(ch); ++p; outlen += l; --todo; } return outlen; } /* * Call MultiByteToWideChar() and allocate memory for the result. * Returns the result in "*out[*outlen]" with an extra zero appended. * "outlen" is in words. */ void MultiByteToWideChar_alloc(UINT cp, DWORD flags, LPCSTR in, int inlen, LPWSTR *out, int *outlen) { *outlen = MultiByteToWideChar(cp, flags, in, inlen, 0, 0); /* Add one one word to avoid a zero-length alloc(). */ *out = (LPWSTR)alloc(sizeof(WCHAR) * (*outlen + 1)); if (*out != NULL) { MultiByteToWideChar(cp, flags, in, inlen, *out, *outlen); (*out)[*outlen] = 0; } } /* * Call WideCharToMultiByte() and allocate memory for the result. * Returns the result in "*out[*outlen]" with an extra NUL appended. */ void WideCharToMultiByte_alloc(UINT cp, DWORD flags, LPCWSTR in, int inlen, LPSTR *out, int *outlen, LPCSTR def, LPBOOL useddef) { *outlen = WideCharToMultiByte(cp, flags, in, inlen, NULL, 0, def, useddef); /* Add one one byte to avoid a zero-length alloc(). */ *out = alloc((unsigned)*outlen + 1); if (*out != NULL) { WideCharToMultiByte(cp, flags, in, inlen, *out, *outlen, def, useddef); (*out)[*outlen] = 0; } } #endif /* FEAT_MBYTE */ #ifdef FEAT_CLIPBOARD /* * Clipboard stuff, for cutting and pasting text to other windows. */ /* Type used for the clipboard type of Vim's data. */ typedef struct { int type; /* MCHAR, MBLOCK or MLINE */ int txtlen; /* length of CF_TEXT in bytes */ int ucslen; /* length of CF_UNICODETEXT in words */ int rawlen; /* length of clip_star.format_raw, including encoding, excluding terminating NUL */ } VimClipType_t; /* * Make vim the owner of the current selection. Return OK upon success. */ /*ARGSUSED*/ int clip_mch_own_selection(VimClipboard *cbd) { /* * Never actually own the clipboard. If another application sets the * clipboard, we don't want to think that we still own it. */ return FAIL; } /* * Make vim NOT the owner of the current selection. */ /*ARGSUSED*/ void clip_mch_lose_selection(VimClipboard *cbd) { /* Nothing needs to be done here */ } /* * Copy "str[*size]" into allocated memory, changing CR-NL to NL. * Return the allocated result and the size in "*size". * Returns NULL when out of memory. */ static char_u * crnl_to_nl(const char_u *str, int *size) { int pos = 0; int str_len = *size; char_u *ret; char_u *retp; /* Avoid allocating zero bytes, it generates an error message. */ ret = lalloc((long_u)(str_len == 0 ? 1 : str_len), TRUE); if (ret != NULL) { retp = ret; for (pos = 0; pos < str_len; ++pos) { if (str[pos] == '\r' && str[pos + 1] == '\n') { ++pos; --(*size); } *retp++ = str[pos]; } } return ret; } /* * Wait for another process to Close the Clipboard. * Returns TRUE for success. */ static int vim_open_clipboard(void) { int delay = 10; while (!OpenClipboard(NULL)) { if (delay > 500) return FALSE; /* waited too long, give up */ Sleep(delay); delay *= 2; /* wait for 10, 20, 40, 80, etc. msec */ } return TRUE; } /* * Get the current selection and put it in the clipboard register. * * NOTE: Must use GlobalLock/Unlock here to ensure Win32s compatibility. * On NT/W95 the clipboard data is a fixed global memory object and * so its handle = its pointer. * On Win32s, however, co-operation with the Win16 system means that * the clipboard data is moveable and its handle is not a pointer at all, * so we can't just cast the return value of GetClipboardData to (char_u*). * <VN> */ void clip_mch_request_selection(VimClipboard *cbd) { VimClipType_t metadata = { -1, -1, -1, -1 }; HGLOBAL hMem = NULL; char_u *str = NULL; #if defined(FEAT_MBYTE) && defined(WIN3264) char_u *to_free = NULL; #endif #ifdef FEAT_MBYTE HGLOBAL rawh = NULL; #endif int str_size = 0; int maxlen; size_t n; /* * Don't pass GetActiveWindow() as an argument to OpenClipboard() because * then we can't paste back into the same window for some reason - webb. */ if (!vim_open_clipboard()) return; /* Check for vim's own clipboard format first. This only gets the type of * the data, still need to use CF_UNICODETEXT or CF_TEXT for the text. */ if (IsClipboardFormatAvailable(cbd->format)) { VimClipType_t *meta_p; HGLOBAL meta_h; /* We have metadata on the clipboard; try to get it. */ if ((meta_h = GetClipboardData(cbd->format)) != NULL && (meta_p = (VimClipType_t *)GlobalLock(meta_h)) != NULL) { /* The size of "VimClipType_t" changed, "rawlen" was added later. * Only copy what is available for backwards compatibility. */ n = sizeof(VimClipType_t); if (GlobalSize(meta_h) < n) n = GlobalSize(meta_h); memcpy(&metadata, meta_p, n); GlobalUnlock(meta_h); } } #ifdef FEAT_MBYTE /* Check for Vim's raw clipboard format first. This is used without * conversion, but only if 'encoding' matches. */ if (IsClipboardFormatAvailable(cbd->format_raw) && metadata.rawlen > (int)STRLEN(p_enc)) { /* We have raw data on the clipboard; try to get it. */ if ((rawh = GetClipboardData(cbd->format_raw)) != NULL) { char_u *rawp; rawp = (char_u *)GlobalLock(rawh); if (rawp != NULL && STRCMP(p_enc, rawp) == 0) { n = STRLEN(p_enc) + 1; str = rawp + n; str_size = (int)(metadata.rawlen - n); } else { GlobalUnlock(rawh); rawh = NULL; } } } if (str == NULL) { #endif #if defined(FEAT_MBYTE) && defined(WIN3264) /* Try to get the clipboard in Unicode if it's not an empty string. */ if (IsClipboardFormatAvailable(CF_UNICODETEXT) && metadata.ucslen != 0) { HGLOBAL hMemW; if ((hMemW = GetClipboardData(CF_UNICODETEXT)) != NULL) { WCHAR *hMemWstr = (WCHAR *)GlobalLock(hMemW); /* Use the length of our metadata if possible, but limit it to the * GlobalSize() for safety. */ maxlen = (int)(GlobalSize(hMemW) / sizeof(WCHAR)); if (metadata.ucslen >= 0) { if (metadata.ucslen > maxlen) str_size = maxlen; else str_size = metadata.ucslen; } else { for (str_size = 0; str_size < maxlen; ++str_size) if (hMemWstr[str_size] == NUL) break; } to_free = str = utf16_to_enc((short_u *)hMemWstr, &str_size); GlobalUnlock(hMemW); } } else #endif /* Get the clipboard in the Active codepage. */ if (IsClipboardFormatAvailable(CF_TEXT)) { if ((hMem = GetClipboardData(CF_TEXT)) != NULL) { str = (char_u *)GlobalLock(hMem); /* The length is either what our metadata says or the strlen(). * But limit it to the GlobalSize() for safety. */ maxlen = (int)GlobalSize(hMem); if (metadata.txtlen >= 0) { if (metadata.txtlen > maxlen) str_size = maxlen; else str_size = metadata.txtlen; } else { for (str_size = 0; str_size < maxlen; ++str_size) if (str[str_size] == NUL) break; } # if defined(FEAT_MBYTE) && defined(WIN3264) /* The text is in the active codepage. Convert to 'encoding', * going through UTF-16. */ acp_to_enc(str, str_size, &to_free, &maxlen); if (to_free != NULL) { str_size = maxlen; str = to_free; } # endif } } #ifdef FEAT_MBYTE } #endif if (str != NULL && *str != NUL) { char_u *temp_clipboard; /* If the type is not known detect it. */ if (metadata.type == -1) metadata.type = MAUTO; /* Translate <CR><NL> into <NL>. */ temp_clipboard = crnl_to_nl(str, &str_size); if (temp_clipboard != NULL) { clip_yank_selection(metadata.type, temp_clipboard, str_size, cbd); vim_free(temp_clipboard); } } /* unlock the global object */ if (hMem != NULL) GlobalUnlock(hMem); #ifdef FEAT_MBYTE if (rawh != NULL) GlobalUnlock(rawh); #endif CloseClipboard(); #if defined(FEAT_MBYTE) && defined(WIN3264) vim_free(to_free); #endif } /* * Send the current selection to the clipboard. */ void clip_mch_set_selection(VimClipboard *cbd) { char_u *str = NULL; VimClipType_t metadata; long_u txtlen; HGLOBAL hMemRaw = NULL; HGLOBAL hMem = NULL; HGLOBAL hMemVim = NULL; # if defined(FEAT_MBYTE) && defined(WIN3264) HGLOBAL hMemW = NULL; # endif /* If the '*' register isn't already filled in, fill it in now */ cbd->owned = TRUE; clip_get_selection(cbd); cbd->owned = FALSE; /* Get the text to be put on the clipboard, with CR-LF. */ metadata.type = clip_convert_selection(&str, &txtlen, cbd); if (metadata.type < 0) return; metadata.txtlen = (int)txtlen; metadata.ucslen = 0; metadata.rawlen = 0; #ifdef FEAT_MBYTE /* Always set the raw bytes: 'encoding', NUL and the text. This is used * when copy/paste from/to Vim with the same 'encoding', so that illegal * bytes can also be copied and no conversion is needed. */ { LPSTR lpszMemRaw; metadata.rawlen = (int)(txtlen + STRLEN(p_enc) + 1); hMemRaw = (LPSTR)GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, metadata.rawlen + 1); lpszMemRaw = (LPSTR)GlobalLock(hMemRaw); if (lpszMemRaw != NULL) { STRCPY(lpszMemRaw, p_enc); memcpy(lpszMemRaw + STRLEN(p_enc) + 1, str, txtlen + 1); GlobalUnlock(hMemRaw); } else metadata.rawlen = 0; } #endif # if defined(FEAT_MBYTE) && defined(WIN3264) { WCHAR *out; int len = metadata.txtlen; /* Convert the text to UTF-16. This is put on the clipboard as * CF_UNICODETEXT. */ out = (WCHAR *)enc_to_utf16(str, &len); if (out != NULL) { WCHAR *lpszMemW; /* Convert the text for CF_TEXT to Active codepage. Otherwise it's * p_enc, which has no relation to the Active codepage. */ metadata.txtlen = WideCharToMultiByte(GetACP(), 0, out, len, NULL, 0, 0, 0); vim_free(str); str = (char_u *)alloc((unsigned)(metadata.txtlen == 0 ? 1 : metadata.txtlen)); if (str == NULL) { vim_free(out); return; /* out of memory */ } WideCharToMultiByte(GetACP(), 0, out, len, str, metadata.txtlen, 0, 0); /* Allocate memory for the UTF-16 text, add one NUL word to * terminate the string. */ hMemW = (LPSTR)GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (len + 1) * sizeof(WCHAR)); lpszMemW = (WCHAR *)GlobalLock(hMemW); if (lpszMemW != NULL) { memcpy(lpszMemW, out, len * sizeof(WCHAR)); lpszMemW[len] = NUL; GlobalUnlock(hMemW); } vim_free(out); metadata.ucslen = len; } } # endif /* Allocate memory for the text, add one NUL byte to terminate the string. */ hMem = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, metadata.txtlen + 1); { LPSTR lpszMem = (LPSTR)GlobalLock(hMem); if (lpszMem) { vim_strncpy(lpszMem, str, metadata.txtlen); GlobalUnlock(hMem); } } /* Set up metadata: */ { VimClipType_t *lpszMemVim = NULL; hMemVim = GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE, sizeof(VimClipType_t)); lpszMemVim = (VimClipType_t *)GlobalLock(hMemVim); memcpy(lpszMemVim, &metadata, sizeof(metadata)); GlobalUnlock(hMemVim); } /* * Open the clipboard, clear it and put our text on it. * Always set our Vim format. Put Unicode and plain text on it. * * Don't pass GetActiveWindow() as an argument to OpenClipboard() * because then we can't paste back into the same window for some * reason - webb. */ if (vim_open_clipboard()) { if (EmptyClipboard()) { SetClipboardData(cbd->format, hMemVim); hMemVim = 0; # if defined(FEAT_MBYTE) && defined(WIN3264) if (hMemW != NULL) { if (SetClipboardData(CF_UNICODETEXT, hMemW) != NULL) hMemW = NULL; } # endif /* Always use CF_TEXT. On Win98 Notepad won't obtain the * CF_UNICODETEXT text, only CF_TEXT. */ SetClipboardData(CF_TEXT, hMem); hMem = 0; } CloseClipboard(); } vim_free(str); /* Free any allocations we didn't give to the clipboard: */ if (hMemRaw) GlobalFree(hMemRaw); if (hMem) GlobalFree(hMem); # if defined(FEAT_MBYTE) && defined(WIN3264) if (hMemW) GlobalFree(hMemW); # endif if (hMemVim) GlobalFree(hMemVim); } #endif /* FEAT_CLIPBOARD */ #if defined(FEAT_MBYTE) || defined(PROTO) /* * Note: the following two functions are only guaranteed to work when using * valid MS-Windows codepages or when iconv() is available. */ /* * Convert "str" from 'encoding' to UTF-16. * Input in "str" with length "*lenp". When "lenp" is NULL, use strlen(). * Output is returned as an allocated string. "*lenp" is set to the length of * the result. A trailing NUL is always added. * Returns NULL when out of memory. */ short_u * enc_to_utf16(char_u *str, int *lenp) { vimconv_T conv; WCHAR *ret; char_u *allocbuf = NULL; int len_loc; int length; if (lenp == NULL) { len_loc = (int)STRLEN(str) + 1; lenp = &len_loc; } if (enc_codepage > 0) { /* We can do any CP### -> UTF-16 in one pass, and we can do it * without iconv() (convert_* may need iconv). */ MultiByteToWideChar_alloc(enc_codepage, 0, str, *lenp, &ret, &length); } else { /* Use "latin1" by default, we might be called before we have p_enc * set up. Convert to utf-8 first, works better with iconv(). Does * nothing if 'encoding' is "utf-8". */ conv.vc_type = CONV_NONE; if (convert_setup(&conv, p_enc ? p_enc : (char_u *)"latin1", (char_u *)"utf-8") == FAIL) return NULL; if (conv.vc_type != CONV_NONE) { str = allocbuf = string_convert(&conv, str, lenp); if (str == NULL) return NULL; } convert_setup(&conv, NULL, NULL); length = utf8_to_utf16(str, *lenp, NULL, NULL); ret = (WCHAR *)alloc((unsigned)((length + 1) * sizeof(WCHAR))); if (ret != NULL) { utf8_to_utf16(str, *lenp, (short_u *)ret, NULL); ret[length] = 0; } vim_free(allocbuf); } *lenp = length; return (short_u *)ret; } /* * Convert an UTF-16 string to 'encoding'. * Input in "str" with length (counted in wide characters) "*lenp". When * "lenp" is NULL, use wcslen(). * Output is returned as an allocated string. If "*lenp" is not NULL it is * set to the length of the result. * Returns NULL when out of memory. */ char_u * utf16_to_enc(short_u *str, int *lenp) { vimconv_T conv; char_u *utf8_str = NULL, *enc_str = NULL; int len_loc; if (lenp == NULL) { len_loc = (int)wcslen(str) + 1; lenp = &len_loc; } if (enc_codepage > 0) { /* We can do any UTF-16 -> CP### in one pass. */ int length; WideCharToMultiByte_alloc(enc_codepage, 0, str, *lenp, (LPSTR *)&enc_str, &length, 0, 0); *lenp = length; return enc_str; } /* Avoid allocating zero bytes, it generates an error message. */ utf8_str = alloc(utf16_to_utf8(str, *lenp == 0 ? 1 : *lenp, NULL)); if (utf8_str != NULL) { *lenp = utf16_to_utf8(str, *lenp, utf8_str); /* We might be called before we have p_enc set up. */ conv.vc_type = CONV_NONE; convert_setup(&conv, (char_u *)"utf-8", p_enc? p_enc: (char_u *)"latin1"); if (conv.vc_type == CONV_NONE) { /* p_enc is utf-8, so we're done. */ enc_str = utf8_str; } else { enc_str = string_convert(&conv, utf8_str, lenp); vim_free(utf8_str); } convert_setup(&conv, NULL, NULL); } return enc_str; } #endif /* FEAT_MBYTE */ #if (defined(FEAT_MBYTE) && defined(WIN3264)) || defined(PROTO) /* * Convert from the active codepage to 'encoding'. * Input is "str[str_size]". * The result is in allocated memory: "out[outlen]". With terminating NUL. */ void acp_to_enc(str, str_size, out, outlen) char_u *str; int str_size; char_u **out; int *outlen; { LPWSTR widestr; MultiByteToWideChar_alloc(GetACP(), 0, str, str_size, &widestr, outlen); if (widestr != NULL) { ++*outlen; /* Include the 0 after the string */ *out = utf16_to_enc((short_u *)widestr, outlen); vim_free(widestr); } } #endif /* * Debugging helper: expose the MCH_WRITE_DUMP stuff to other modules */ /*ARGSUSED*/ void DumpPutS( const char *psz) { # ifdef MCH_WRITE_DUMP if (fdDump) { fputs(psz, fdDump); if (psz[strlen(psz) - 1] != '\n') fputc('\n', fdDump); fflush(fdDump); } # endif } #ifdef _DEBUG void __cdecl Trace( char *pszFormat, ...) { CHAR szBuff[2048]; va_list args; va_start(args, pszFormat); vsprintf(szBuff, pszFormat, args); va_end(args); OutputDebugString(szBuff); } #endif //_DEBUG #if !defined(FEAT_GUI) || defined(PROTO) # if defined(FEAT_TITLE) && defined(WIN3264) extern HWND g_hWnd; /* This is in os_win32.c. */ # endif /* * Showing the printer dialog is tricky since we have no GUI * window to parent it. The following routines are needed to * get the window parenting and Z-order to work properly. */ static void GetConsoleHwnd(void) { # define MY_BUFSIZE 1024 // Buffer size for console window titles. char pszNewWindowTitle[MY_BUFSIZE]; // Contains fabricated WindowTitle. char pszOldWindowTitle[MY_BUFSIZE]; // Contains original WindowTitle. /* Skip if it's already set. */ if (s_hwnd != 0) return; # if defined(FEAT_TITLE) && defined(WIN3264) /* Window handle may have been found by init code (Windows NT only) */ if (g_hWnd != 0) { s_hwnd = g_hWnd; return; } # endif GetConsoleTitle(pszOldWindowTitle, MY_BUFSIZE); wsprintf(pszNewWindowTitle, "%s/%d/%d", pszOldWindowTitle, GetTickCount(), GetCurrentProcessId()); SetConsoleTitle(pszNewWindowTitle); Sleep(40); s_hwnd = FindWindow(NULL, pszNewWindowTitle); SetConsoleTitle(pszOldWindowTitle); } /* * Console implementation of ":winpos". */ int mch_get_winpos(int *x, int *y) { RECT rect; GetConsoleHwnd(); GetWindowRect(s_hwnd, &rect); *x = rect.left; *y = rect.top; return OK; } /* * Console implementation of ":winpos x y". */ void mch_set_winpos(int x, int y) { GetConsoleHwnd(); SetWindowPos(s_hwnd, NULL, x, y, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE); } #endif #if (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) || defined(PROTO) # ifdef WIN16 # define TEXT(a) a # endif /*================================================================= * Win32 printer stuff */ static HFONT prt_font_handles[2][2][2]; static PRINTDLG prt_dlg; static const int boldface[2] = {FW_REGULAR, FW_BOLD}; static TEXTMETRIC prt_tm; static int prt_line_height; static int prt_number_width; static int prt_left_margin; static int prt_right_margin; static int prt_top_margin; static char_u szAppName[] = TEXT("VIM"); static HWND hDlgPrint; static int *bUserAbort = NULL; static char_u *prt_name = NULL; /* Defines which are also in vim.rc. */ #define IDC_BOX1 400 #define IDC_PRINTTEXT1 401 #define IDC_PRINTTEXT2 402 #define IDC_PROGRESS 403 /* * Convert BGR to RGB for Windows GDI calls */ static COLORREF swap_me(COLORREF colorref) { int temp; char *ptr = (char *)&colorref; temp = *(ptr); *(ptr ) = *(ptr + 2); *(ptr + 2) = temp; return colorref; } /* Attempt to make this work for old and new compilers */ #if !defined(_WIN64) && (!defined(_MSC_VER) || _MSC_VER < 1300) # define PDP_RETVAL BOOL #else # define PDP_RETVAL INT_PTR #endif /*ARGSUSED*/ static PDP_RETVAL CALLBACK PrintDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { #ifdef FEAT_GETTEXT NONCLIENTMETRICS nm; static HFONT hfont; #endif switch (message) { case WM_INITDIALOG: #ifdef FEAT_GETTEXT nm.cbSize = sizeof(NONCLIENTMETRICS); if (SystemParametersInfo( SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &nm, 0)) { char buff[MAX_PATH]; int i; /* Translate the dialog texts */ hfont = CreateFontIndirect(&nm.lfMessageFont); for (i = IDC_PRINTTEXT1; i <= IDC_PROGRESS; i++) { SendDlgItemMessage(hDlg, i, WM_SETFONT, (WPARAM)hfont, 1); if (GetDlgItemText(hDlg,i, buff, sizeof(buff))) SetDlgItemText(hDlg,i, _(buff)); } SendDlgItemMessage(hDlg, IDCANCEL, WM_SETFONT, (WPARAM)hfont, 1); if (GetDlgItemText(hDlg,IDCANCEL, buff, sizeof(buff))) SetDlgItemText(hDlg,IDCANCEL, _(buff)); } #endif SetWindowText(hDlg, szAppName); if (prt_name != NULL) { SetDlgItemText(hDlg, IDC_PRINTTEXT2, (LPSTR)prt_name); vim_free(prt_name); prt_name = NULL; } EnableMenuItem(GetSystemMenu(hDlg, FALSE), SC_CLOSE, MF_GRAYED); #ifndef FEAT_GUI BringWindowToTop(s_hwnd); #endif return TRUE; case WM_COMMAND: *bUserAbort = TRUE; EnableWindow(GetParent(hDlg), TRUE); DestroyWindow(hDlg); hDlgPrint = NULL; #ifdef FEAT_GETTEXT DeleteObject(hfont); #endif return TRUE; } return FALSE; } /*ARGSUSED*/ static BOOL CALLBACK AbortProc(HDC hdcPrn, int iCode) { MSG msg; while (!*bUserAbort && pPeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if (!hDlgPrint || !pIsDialogMessage(hDlgPrint, &msg)) { TranslateMessage(&msg); pDispatchMessage(&msg); } } return !*bUserAbort; } #ifndef FEAT_GUI static UINT_PTR CALLBACK PrintHookProc( HWND hDlg, // handle to dialog box UINT uiMsg, // message identifier WPARAM wParam, // message parameter LPARAM lParam // message parameter ) { HWND hwndOwner; RECT rc, rcDlg, rcOwner; PRINTDLG *pPD; if (uiMsg == WM_INITDIALOG) { // Get the owner window and dialog box rectangles. if ((hwndOwner = GetParent(hDlg)) == NULL) hwndOwner = GetDesktopWindow(); GetWindowRect(hwndOwner, &rcOwner); GetWindowRect(hDlg, &rcDlg); CopyRect(&rc, &rcOwner); // Offset the owner and dialog box rectangles so that // right and bottom values represent the width and // height, and then offset the owner again to discard // space taken up by the dialog box. OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top); OffsetRect(&rc, -rc.left, -rc.top); OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom); // The new position is the sum of half the remaining // space and the owner's original position. SetWindowPos(hDlg, HWND_TOP, rcOwner.left + (rc.right / 2), rcOwner.top + (rc.bottom / 2), 0, 0, // ignores size arguments SWP_NOSIZE); /* tackle the printdlg copiesctrl problem */ pPD = (PRINTDLG *)lParam; pPD->nCopies = (WORD)pPD->lCustData; SetDlgItemInt( hDlg, edt3, pPD->nCopies, FALSE ); /* Bring the window to top */ BringWindowToTop(GetParent(hDlg)); SetForegroundWindow(hDlg); } return FALSE; } #endif void mch_print_cleanup(void) { int pifItalic; int pifBold; int pifUnderline; for (pifBold = 0; pifBold <= 1; pifBold++) for (pifItalic = 0; pifItalic <= 1; pifItalic++) for (pifUnderline = 0; pifUnderline <= 1; pifUnderline++) DeleteObject(prt_font_handles[pifBold][pifItalic][pifUnderline]); if (prt_dlg.hDC != NULL) DeleteDC(prt_dlg.hDC); if (!*bUserAbort) SendMessage(hDlgPrint, WM_COMMAND, 0, 0); } static int to_device_units(int idx, int dpi, int physsize, int offset, int def_number) { int ret = 0; int u; int nr; u = prt_get_unit(idx); if (u == PRT_UNIT_NONE) { u = PRT_UNIT_PERC; nr = def_number; } else nr = printer_opts[idx].number; switch (u) { case PRT_UNIT_PERC: ret = (physsize * nr) / 100; break; case PRT_UNIT_INCH: ret = (nr * dpi); break; case PRT_UNIT_MM: ret = (nr * 10 * dpi) / 254; break; case PRT_UNIT_POINT: ret = (nr * 10 * dpi) / 720; break; } if (ret < offset) return 0; else return ret - offset; } static int prt_get_cpl(void) { int hr; int phyw; int dvoff; int rev_offset; int dpi; #ifdef WIN16 POINT pagesize; #endif GetTextMetrics(prt_dlg.hDC, &prt_tm); prt_line_height = prt_tm.tmHeight + prt_tm.tmExternalLeading; hr = GetDeviceCaps(prt_dlg.hDC, HORZRES); #ifdef WIN16 Escape(prt_dlg.hDC, GETPHYSPAGESIZE, NULL, NULL, &pagesize); phyw = pagesize.x; Escape(prt_dlg.hDC, GETPRINTINGOFFSET, NULL, NULL, &pagesize); dvoff = pagesize.x; #else phyw = GetDeviceCaps(prt_dlg.hDC, PHYSICALWIDTH); dvoff = GetDeviceCaps(prt_dlg.hDC, PHYSICALOFFSETX); #endif dpi = GetDeviceCaps(prt_dlg.hDC, LOGPIXELSX); rev_offset = phyw - (dvoff + hr); prt_left_margin = to_device_units(OPT_PRINT_LEFT, dpi, phyw, dvoff, 10); if (prt_use_number()) { prt_number_width = PRINT_NUMBER_WIDTH * prt_tm.tmAveCharWidth; prt_left_margin += prt_number_width; } else prt_number_width = 0; prt_right_margin = hr - to_device_units(OPT_PRINT_RIGHT, dpi, phyw, rev_offset, 5); return (prt_right_margin - prt_left_margin) / prt_tm.tmAveCharWidth; } static int prt_get_lpp(void) { int vr; int phyw; int dvoff; int rev_offset; int bottom_margin; int dpi; #ifdef WIN16 POINT pagesize; #endif vr = GetDeviceCaps(prt_dlg.hDC, VERTRES); #ifdef WIN16 Escape(prt_dlg.hDC, GETPHYSPAGESIZE, NULL, NULL, &pagesize); phyw = pagesize.y; Escape(prt_dlg.hDC, GETPRINTINGOFFSET, NULL, NULL, &pagesize); dvoff = pagesize.y; #else phyw = GetDeviceCaps(prt_dlg.hDC, PHYSICALHEIGHT); dvoff = GetDeviceCaps(prt_dlg.hDC, PHYSICALOFFSETY); #endif dpi = GetDeviceCaps(prt_dlg.hDC, LOGPIXELSY); rev_offset = phyw - (dvoff + vr); prt_top_margin = to_device_units(OPT_PRINT_TOP, dpi, phyw, dvoff, 5); /* adjust top margin if there is a header */ prt_top_margin += prt_line_height * prt_header_height(); bottom_margin = vr - to_device_units(OPT_PRINT_BOT, dpi, phyw, rev_offset, 5); return (bottom_margin - prt_top_margin) / prt_line_height; } int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit) { static HGLOBAL stored_dm = NULL; static HGLOBAL stored_devn = NULL; static int stored_nCopies = 1; static int stored_nFlags = 0; LOGFONT fLogFont; int pifItalic; int pifBold; int pifUnderline; DEVMODE *mem; DEVNAMES *devname; int i; bUserAbort = &(psettings->user_abort); vim_memset(&prt_dlg, 0, sizeof(PRINTDLG)); prt_dlg.lStructSize = sizeof(PRINTDLG); #ifndef FEAT_GUI GetConsoleHwnd(); /* get value of s_hwnd */ #endif prt_dlg.hwndOwner = s_hwnd; prt_dlg.Flags = PD_NOPAGENUMS | PD_NOSELECTION | PD_RETURNDC; if (!forceit) { prt_dlg.hDevMode = stored_dm; prt_dlg.hDevNames = stored_devn; prt_dlg.lCustData = stored_nCopies; // work around bug in print dialog #ifndef FEAT_GUI /* * Use hook to prevent console window being sent to back */ prt_dlg.lpfnPrintHook = PrintHookProc; prt_dlg.Flags |= PD_ENABLEPRINTHOOK; #endif prt_dlg.Flags |= stored_nFlags; } /* * If bang present, return default printer setup with no dialog * never show dialog if we are running over telnet */ if (forceit #ifndef FEAT_GUI || !term_console #endif ) { prt_dlg.Flags |= PD_RETURNDEFAULT; #ifdef WIN3264 /* * MSDN suggests setting the first parameter to WINSPOOL for * NT, but NULL appears to work just as well. */ if (*p_pdev != NUL) prt_dlg.hDC = CreateDC(NULL, p_pdev, NULL, NULL); else #endif { prt_dlg.Flags |= PD_RETURNDEFAULT; if (PrintDlg(&prt_dlg) == 0) goto init_fail_dlg; } } else if (PrintDlg(&prt_dlg) == 0) goto init_fail_dlg; else { /* * keep the previous driver context */ stored_dm = prt_dlg.hDevMode; stored_devn = prt_dlg.hDevNames; stored_nFlags = prt_dlg.Flags; stored_nCopies = prt_dlg.nCopies; } if (prt_dlg.hDC == NULL) { EMSG(_("E237: Printer selection failed")); mch_print_cleanup(); return FALSE; } /* Not all printer drivers report the support of color (or grey) in the * same way. Let's set has_color if there appears to be some way to print * more than B&W. */ i = GetDeviceCaps(prt_dlg.hDC, NUMCOLORS); psettings->has_color = (GetDeviceCaps(prt_dlg.hDC, BITSPIXEL) > 1 || GetDeviceCaps(prt_dlg.hDC, PLANES) > 1 || i > 2 || i == -1); /* Ensure all font styles are baseline aligned */ SetTextAlign(prt_dlg.hDC, TA_BASELINE|TA_LEFT); /* * On some windows systems the nCopies parameter is not * passed back correctly. It must be retrieved from the * hDevMode struct. */ mem = (DEVMODE *)GlobalLock(prt_dlg.hDevMode); if (mem != NULL) { #ifdef WIN3264 if (mem->dmCopies != 1) stored_nCopies = mem->dmCopies; #endif if ((mem->dmFields & DM_DUPLEX) && (mem->dmDuplex & ~DMDUP_SIMPLEX)) psettings->duplex = TRUE; if ((mem->dmFields & DM_COLOR) && (mem->dmColor & DMCOLOR_COLOR)) psettings->has_color = TRUE; } GlobalUnlock(prt_dlg.hDevMode); devname = (DEVNAMES *)GlobalLock(prt_dlg.hDevNames); if (devname != 0) { char_u *printer_name = (char_u *)devname + devname->wDeviceOffset; char_u *port_name = (char_u *)devname +devname->wOutputOffset; char_u *text = _("to %s on %s"); prt_name = alloc((unsigned)(STRLEN(printer_name) + STRLEN(port_name) + STRLEN(text))); if (prt_name != NULL) wsprintf(prt_name, text, printer_name, port_name); } GlobalUnlock(prt_dlg.hDevNames); /* * Initialise the font according to 'printfont' */ vim_memset(&fLogFont, 0, sizeof(fLogFont)); if (get_logfont(&fLogFont, p_pfn, prt_dlg.hDC, TRUE) == FAIL) { EMSG2(_("E613: Unknown printer font: %s"), p_pfn); mch_print_cleanup(); return FALSE; } for (pifBold = 0; pifBold <= 1; pifBold++) for (pifItalic = 0; pifItalic <= 1; pifItalic++) for (pifUnderline = 0; pifUnderline <= 1; pifUnderline++) { fLogFont.lfWeight = boldface[pifBold]; fLogFont.lfItalic = pifItalic; fLogFont.lfUnderline = pifUnderline; prt_font_handles[pifBold][pifItalic][pifUnderline] = CreateFontIndirect(&fLogFont); } SetBkMode(prt_dlg.hDC, OPAQUE); SelectObject(prt_dlg.hDC, prt_font_handles[0][0][0]); /* * Fill in the settings struct */ psettings->chars_per_line = prt_get_cpl(); psettings->lines_per_page = prt_get_lpp(); psettings->n_collated_copies = (prt_dlg.Flags & PD_COLLATE) ? prt_dlg.nCopies : 1; psettings->n_uncollated_copies = (prt_dlg.Flags & PD_COLLATE) ? 1 : prt_dlg.nCopies; if (psettings->n_collated_copies == 0) psettings->n_collated_copies = 1; if (psettings->n_uncollated_copies == 0) psettings->n_uncollated_copies = 1; psettings->jobname = jobname; return TRUE; init_fail_dlg: { DWORD err = CommDlgExtendedError(); if (err) { #ifdef WIN16 char buf[20]; sprintf(buf, "%ld", err); EMSG2(_("E238: Print error: %s"), buf); #else char_u *buf; /* I suspect FormatMessage() doesn't work for values returned by * CommDlgExtendedError(). What does? */ FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, 0, (LPTSTR)(&buf), 0, NULL); EMSG2(_("E238: Print error: %s"), buf == NULL ? (char_u *)_("Unknown") : buf); LocalFree((LPVOID)(buf)); #endif } else msg_clr_eos(); /* Maybe canceled */ mch_print_cleanup(); return FALSE; } } int mch_print_begin(prt_settings_T *psettings) { int ret; static DOCINFO di; char szBuffer[300]; hDlgPrint = CreateDialog(GetModuleHandle(NULL), TEXT("PrintDlgBox"), prt_dlg.hwndOwner, PrintDlgProc); #ifdef WIN16 Escape(prt_dlg.hDC, SETABORTPROC, 0, (LPSTR)AbortProc, NULL); #else SetAbortProc(prt_dlg.hDC, AbortProc); #endif wsprintf(szBuffer, _("Printing '%s'"), gettail(psettings->jobname)); SetDlgItemText(hDlgPrint, IDC_PRINTTEXT1, (LPSTR)szBuffer); vim_memset(&di, 0, sizeof(DOCINFO)); di.cbSize = sizeof(DOCINFO); di.lpszDocName = psettings->jobname; ret = StartDoc(prt_dlg.hDC, &di); #ifdef FEAT_GUI /* Give focus back to main window (when using MDI). */ SetFocus(s_hwnd); #endif return (ret > 0); } /*ARGSUSED*/ void mch_print_end(prt_settings_T *psettings) { EndDoc(prt_dlg.hDC); if (!*bUserAbort) SendMessage(hDlgPrint, WM_COMMAND, 0, 0); } int mch_print_end_page(void) { return (EndPage(prt_dlg.hDC) > 0); } int mch_print_begin_page(char_u *msg) { if (msg != NULL) SetDlgItemText(hDlgPrint, IDC_PROGRESS, (LPSTR)msg); return (StartPage(prt_dlg.hDC) > 0); } int mch_print_blank_page(void) { return (mch_print_begin_page(NULL) ? (mch_print_end_page()) : FALSE); } static int prt_pos_x = 0; static int prt_pos_y = 0; void mch_print_start_line(margin, page_line) int margin; int page_line; { if (margin) prt_pos_x = -prt_number_width; else prt_pos_x = 0; prt_pos_y = page_line * prt_line_height + prt_tm.tmAscent + prt_tm.tmExternalLeading; } int mch_print_text_out(char_u *p, int len) { #ifdef FEAT_PROPORTIONAL_FONTS SIZE sz; #endif TextOut(prt_dlg.hDC, prt_pos_x + prt_left_margin, prt_pos_y + prt_top_margin, p, len); #ifndef FEAT_PROPORTIONAL_FONTS prt_pos_x += len * prt_tm.tmAveCharWidth; return (prt_pos_x + prt_left_margin + prt_tm.tmAveCharWidth + prt_tm.tmOverhang > prt_right_margin); #else # ifdef WIN16 GetTextExtentPoint(prt_dlg.hDC, p, len, &sz); # else GetTextExtentPoint32(prt_dlg.hDC, p, len, &sz); # endif prt_pos_x += (sz.cx - prt_tm.tmOverhang); /* This is wrong when printing spaces for a TAB. */ if (p[len] == NUL) return FALSE; # ifdef WIN16 GetTextExtentPoint(prt_dlg.hDC, p + len, 1, &sz); # else GetTextExtentPoint32(prt_dlg.hDC, p + len, 1, &sz); # endif return (prt_pos_x + prt_left_margin + sz.cx > prt_right_margin); #endif } void mch_print_set_font(int iBold, int iItalic, int iUnderline) { SelectObject(prt_dlg.hDC, prt_font_handles[iBold][iItalic][iUnderline]); } void mch_print_set_bg(long_u bgcol) { SetBkColor(prt_dlg.hDC, GetNearestColor(prt_dlg.hDC, swap_me((COLORREF)bgcol))); /* * With a white background we can draw characters transparent, which is * good for italic characters that overlap to the next char cell. */ if (bgcol == 0xffffffUL) SetBkMode(prt_dlg.hDC, TRANSPARENT); else SetBkMode(prt_dlg.hDC, OPAQUE); } void mch_print_set_fg(long_u fgcol) { SetTextColor(prt_dlg.hDC, GetNearestColor(prt_dlg.hDC, swap_me((COLORREF)fgcol))); } #endif /*FEAT_PRINTER && !FEAT_POSTSCRIPT*/ #if defined(FEAT_SHORTCUT) || defined(PROTO) # include <shlobj.h> /* * When "fname" is the name of a shortcut (*.lnk) resolve the file it points * to and return that name in allocated memory. * Otherwise NULL is returned. */ char_u * mch_resolve_shortcut(char_u *fname) { HRESULT hr; IShellLink *psl = NULL; IPersistFile *ppf = NULL; OLECHAR wsz[MAX_PATH]; WIN32_FIND_DATA ffd; // we get those free of charge TCHAR buf[MAX_PATH]; // could have simply reused 'wsz'... char_u *rfname = NULL; int len; /* Check if the file name ends in ".lnk". Avoid calling * CoCreateInstance(), it's quite slow. */ if (fname == NULL) return rfname; len = (int)STRLEN(fname); if (len <= 4 || STRNICMP(fname + len - 4, ".lnk", 4) != 0) return rfname; CoInitialize(NULL); // create a link manager object and request its interface hr = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, &IID_IShellLink, (void**)&psl); if (hr != S_OK) goto shortcut_error; // Get a pointer to the IPersistFile interface. hr = psl->lpVtbl->QueryInterface( psl, &IID_IPersistFile, (void**)&ppf); if (hr != S_OK) goto shortcut_error; // full path string must be in Unicode. MultiByteToWideChar(CP_ACP, 0, fname, -1, wsz, MAX_PATH); // "load" the name and resolve the link hr = ppf->lpVtbl->Load(ppf, wsz, STGM_READ); if (hr != S_OK) goto shortcut_error; #if 0 // This makes Vim wait a long time if the target doesn't exist. hr = psl->lpVtbl->Resolve(psl, NULL, SLR_NO_UI); if (hr != S_OK) goto shortcut_error; #endif // Get the path to the link target. ZeroMemory(buf, MAX_PATH); hr = psl->lpVtbl->GetPath(psl, buf, MAX_PATH, &ffd, 0); if (hr == S_OK && buf[0] != NUL) rfname = vim_strsave(buf); shortcut_error: // Release all interface pointers (both belong to the same object) if (ppf != NULL) ppf->lpVtbl->Release(ppf); if (psl != NULL) psl->lpVtbl->Release(psl); CoUninitialize(); return rfname; } #endif #if (defined(FEAT_EVAL) && !defined(FEAT_GUI)) || defined(PROTO) /* * Bring ourselves to the foreground. Does work if the OS doesn't allow it. */ void win32_set_foreground() { # ifndef FEAT_GUI GetConsoleHwnd(); /* get value of s_hwnd */ # endif if (s_hwnd != 0) SetForegroundWindow(s_hwnd); } #endif #if defined(FEAT_CLIENTSERVER) || defined(PROTO) /* * Client-server code for Vim * * Originally written by Paul Moore */ /* In order to handle inter-process messages, we need to have a window. But * the functions in this module can be called before the main GUI window is * created (and may also be called in the console version, where there is no * GUI window at all). * * So we create a hidden window, and arrange to destroy it on exit. */ HWND message_window = 0; /* window that's handling messsages */ #define VIM_CLASSNAME "VIM_MESSAGES" #define VIM_CLASSNAME_LEN (sizeof(VIM_CLASSNAME) - 1) /* Communication is via WM_COPYDATA messages. The message type is send in * the dwData parameter. Types are defined here. */ #define COPYDATA_KEYS 0 #define COPYDATA_REPLY 1 #define COPYDATA_EXPR 10 #define COPYDATA_RESULT 11 #define COPYDATA_ERROR_RESULT 12 #define COPYDATA_ENCODING 20 /* This is a structure containing a server HWND and its name. */ struct server_id { HWND hwnd; char_u *name; }; /* Last received 'encoding' that the client uses. */ static char_u *client_enc = NULL; /* * Tell the other side what encoding we are using. * Errors are ignored. */ static void serverSendEnc(HWND target) { COPYDATASTRUCT data; data.dwData = COPYDATA_ENCODING; #ifdef FEAT_MBYTE data.cbData = (DWORD)STRLEN(p_enc) + 1; data.lpData = p_enc; #else data.cbData = (DWORD)STRLEN("latin1") + 1; data.lpData = "latin1"; #endif (void)SendMessage(target, WM_COPYDATA, (WPARAM)message_window, (LPARAM)(&data)); } /* * Clean up on exit. This destroys the hidden message window. */ static void #ifdef __BORLANDC__ _RTLENTRYF #endif CleanUpMessaging(void) { if (message_window != 0) { DestroyWindow(message_window); message_window = 0; } } static int save_reply(HWND server, char_u *reply, int expr); /*s * The window procedure for the hidden message window. * It handles callback messages and notifications from servers. * In order to process these messages, it is necessary to run a * message loop. Code which may run before the main message loop * is started (in the GUI) is careful to pump messages when it needs * to. Features which require message delivery during normal use will * not work in the console version - this basically means those * features which allow Vim to act as a server, rather than a client. */ static LRESULT CALLBACK Messaging_WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (msg == WM_COPYDATA) { /* This is a message from another Vim. The dwData member of the * COPYDATASTRUCT determines the type of message: * COPYDATA_ENCODING: * The encoding that the client uses. Following messages will * use this encoding, convert if needed. * COPYDATA_KEYS: * A key sequence. We are a server, and a client wants these keys * adding to the input queue. * COPYDATA_REPLY: * A reply. We are a client, and a server has sent this message * in response to a request. (server2client()) * COPYDATA_EXPR: * An expression. We are a server, and a client wants us to * evaluate this expression. * COPYDATA_RESULT: * A reply. We are a client, and a server has sent this message * in response to a COPYDATA_EXPR. * COPYDATA_ERROR_RESULT: * A reply. We are a client, and a server has sent this message * in response to a COPYDATA_EXPR that failed to evaluate. */ COPYDATASTRUCT *data = (COPYDATASTRUCT*)lParam; HWND sender = (HWND)wParam; COPYDATASTRUCT reply; char_u *res; char_u winstr[30]; int retval; char_u *str; char_u *tofree; switch (data->dwData) { case COPYDATA_ENCODING: # ifdef FEAT_MBYTE /* Remember the encoding that the client uses. */ vim_free(client_enc); client_enc = enc_canonize((char_u *)data->lpData); # endif return 1; case COPYDATA_KEYS: /* Remember who sent this, for <client> */ clientWindow = sender; /* Add the received keys to the input buffer. The loop waiting * for the user to do something should check the input buffer. */ str = serverConvert(client_enc, (char_u *)data->lpData, &tofree); server_to_input_buf(str); vim_free(tofree); # ifdef FEAT_GUI /* Wake up the main GUI loop. */ if (s_hwnd != 0) PostMessage(s_hwnd, WM_NULL, 0, 0); # endif return 1; case COPYDATA_EXPR: /* Remember who sent this, for <client> */ clientWindow = sender; str = serverConvert(client_enc, (char_u *)data->lpData, &tofree); res = eval_client_expr_to_string(str); vim_free(tofree); if (res == NULL) { res = vim_strsave(_(e_invexprmsg)); reply.dwData = COPYDATA_ERROR_RESULT; } else reply.dwData = COPYDATA_RESULT; reply.lpData = res; reply.cbData = (DWORD)STRLEN(res) + 1; serverSendEnc(sender); retval = (int)SendMessage(sender, WM_COPYDATA, (WPARAM)message_window, (LPARAM)(&reply)); vim_free(res); return retval; case COPYDATA_REPLY: case COPYDATA_RESULT: case COPYDATA_ERROR_RESULT: if (data->lpData != NULL) { str = serverConvert(client_enc, (char_u *)data->lpData, &tofree); if (tofree == NULL) str = vim_strsave(str); if (save_reply(sender, str, (data->dwData == COPYDATA_REPLY ? 0 : (data->dwData == COPYDATA_RESULT ? 1 : 2))) == FAIL) vim_free(str); #ifdef FEAT_AUTOCMD else if (data->dwData == COPYDATA_REPLY) { sprintf((char *)winstr, PRINTF_HEX_LONG_U, (long_u)sender); apply_autocmds(EVENT_REMOTEREPLY, winstr, str, TRUE, curbuf); } #endif } return 1; } return 0; } else if (msg == WM_ACTIVATE && wParam == WA_ACTIVE) { /* When the message window is activated (brought to the foreground), * this actually applies to the text window. */ #ifndef FEAT_GUI GetConsoleHwnd(); /* get value of s_hwnd */ #endif if (s_hwnd != 0) { SetForegroundWindow(s_hwnd); return 0; } } return DefWindowProc(hwnd, msg, wParam, lParam); } /* * Initialise the message handling process. This involves creating a window * to handle messages - the window will not be visible. */ void serverInitMessaging(void) { WNDCLASS wndclass; HINSTANCE s_hinst; /* Clean up on exit */ atexit(CleanUpMessaging); /* Register a window class - we only really care * about the window procedure */ s_hinst = (HINSTANCE)GetModuleHandle(0); wndclass.style = 0; wndclass.lpfnWndProc = Messaging_WndProc; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = s_hinst; wndclass.hIcon = NULL; wndclass.hCursor = NULL; wndclass.hbrBackground = NULL; wndclass.lpszMenuName = NULL; wndclass.lpszClassName = VIM_CLASSNAME; RegisterClass(&wndclass); /* Create the message window. It will be hidden, so the details don't * matter. Don't use WS_OVERLAPPEDWINDOW, it will make a shortcut remove * focus from gvim. */ message_window = CreateWindow(VIM_CLASSNAME, "", WS_POPUPWINDOW | WS_CAPTION, CW_USEDEFAULT, CW_USEDEFAULT, 100, 100, NULL, NULL, s_hinst, NULL); } /* Used by serverSendToVim() to find an alternate server name. */ static char_u *altname_buf_ptr = NULL; /* * Get the title of the window "hwnd", which is the Vim server name, in * "name[namelen]" and return the length. * Returns zero if window "hwnd" is not a Vim server. */ static int getVimServerName(HWND hwnd, char *name, int namelen) { int len; char buffer[VIM_CLASSNAME_LEN + 1]; /* Ignore windows which aren't Vim message windows */ len = GetClassName(hwnd, buffer, sizeof(buffer)); if (len != VIM_CLASSNAME_LEN || STRCMP(buffer, VIM_CLASSNAME) != 0) return 0; /* Get the title of the window */ return GetWindowText(hwnd, name, namelen); } static BOOL CALLBACK enumWindowsGetServer(HWND hwnd, LPARAM lparam) { struct server_id *id = (struct server_id *)lparam; char server[MAX_PATH]; /* Get the title of the window */ if (getVimServerName(hwnd, server, sizeof(server)) == 0) return TRUE; /* If this is the server we're looking for, return its HWND */ if (STRICMP(server, id->name) == 0) { id->hwnd = hwnd; return FALSE; } /* If we are looking for an alternate server, remember this name. */ if (altname_buf_ptr != NULL && STRNICMP(server, id->name, STRLEN(id->name)) == 0 && vim_isdigit(server[STRLEN(id->name)])) { STRCPY(altname_buf_ptr, server); altname_buf_ptr = NULL; /* don't use another name */ } /* Otherwise, keep looking */ return TRUE; } static BOOL CALLBACK enumWindowsGetNames(HWND hwnd, LPARAM lparam) { garray_T *ga = (garray_T *)lparam; char server[MAX_PATH]; /* Get the title of the window */ if (getVimServerName(hwnd, server, sizeof(server)) == 0) return TRUE; /* Add the name to the list */ ga_concat(ga, server); ga_concat(ga, "\n"); return TRUE; } static HWND findServer(char_u *name) { struct server_id id; id.name = name; id.hwnd = 0; EnumWindows(enumWindowsGetServer, (LPARAM)(&id)); return id.hwnd; } void serverSetName(char_u *name) { char_u *ok_name; HWND hwnd = 0; int i = 0; char_u *p; /* Leave enough space for a 9-digit suffix to ensure uniqueness! */ ok_name = alloc((unsigned)STRLEN(name) + 10); STRCPY(ok_name, name); p = ok_name + STRLEN(name); for (;;) { /* This is inefficient - we're doing an EnumWindows loop for each * possible name. It would be better to grab all names in one go, * and scan the list each time... */ hwnd = findServer(ok_name); if (hwnd == 0) break; ++i; if (i >= 1000) break; sprintf((char *)p, "%d", i); } if (hwnd != 0) vim_free(ok_name); else { /* Remember the name */ serverName = ok_name; #ifdef FEAT_TITLE need_maketitle = TRUE; /* update Vim window title later */ #endif /* Update the message window title */ SetWindowText(message_window, ok_name); #ifdef FEAT_EVAL /* Set the servername variable */ set_vim_var_string(VV_SEND_SERVER, serverName, -1); #endif } } char_u * serverGetVimNames(void) { garray_T ga; ga_init2(&ga, 1, 100); EnumWindows(enumWindowsGetNames, (LPARAM)(&ga)); ga_append(&ga, NUL); return ga.ga_data; } int serverSendReply(name, reply) char_u *name; /* Where to send. */ char_u *reply; /* What to send. */ { HWND target; COPYDATASTRUCT data; long_u n = 0; /* The "name" argument is a magic cookie obtained from expand("<client>"). * It should be of the form 0xXXXXX - i.e. a C hex literal, which is the * value of the client's message window HWND. */ sscanf((char *)name, SCANF_HEX_LONG_U, &n); if (n == 0) return -1; target = (HWND)n; if (!IsWindow(target)) return -1; data.dwData = COPYDATA_REPLY; data.cbData = (DWORD)STRLEN(reply) + 1; data.lpData = reply; serverSendEnc(target); if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window, (LPARAM)(&data))) return 0; return -1; } int serverSendToVim(name, cmd, result, ptarget, asExpr, silent) char_u *name; /* Where to send. */ char_u *cmd; /* What to send. */ char_u **result; /* Result of eval'ed expression */ void *ptarget; /* HWND of server */ int asExpr; /* Expression or keys? */ int silent; /* don't complain about no server */ { HWND target; COPYDATASTRUCT data; char_u *retval = NULL; int retcode = 0; char_u altname_buf[MAX_PATH]; /* If the server name does not end in a digit then we look for an * alternate name. e.g. when "name" is GVIM the we may find GVIM2. */ if (STRLEN(name) > 1 && !vim_isdigit(name[STRLEN(name) - 1])) altname_buf_ptr = altname_buf; altname_buf[0] = NUL; target = findServer(name); altname_buf_ptr = NULL; if (target == 0 && altname_buf[0] != NUL) /* Use another server name we found. */ target = findServer(altname_buf); if (target == 0) { if (!silent) EMSG2(_(e_noserver), name); return -1; } if (ptarget) *(HWND *)ptarget = target; data.dwData = asExpr ? COPYDATA_EXPR : COPYDATA_KEYS; data.cbData = (DWORD)STRLEN(cmd) + 1; data.lpData = cmd; serverSendEnc(target); if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window, (LPARAM)(&data)) == 0) return -1; if (asExpr) retval = serverGetReply(target, &retcode, TRUE, TRUE); if (result == NULL) vim_free(retval); else *result = retval; /* Caller assumes responsibility for freeing */ return retcode; } /* * Bring the server to the foreground. */ void serverForeground(name) char_u *name; { HWND target = findServer(name); if (target != 0) SetForegroundWindow(target); } /* Replies from server need to be stored until the client picks them up via * remote_read(). So we maintain a list of server-id/reply pairs. * Note that there could be multiple replies from one server pending if the * client is slow picking them up. * We just store the replies in a simple list. When we remove an entry, we * move list entries down to fill the gap. * The server ID is simply the HWND. */ typedef struct { HWND server; /* server window */ char_u *reply; /* reply string */ int expr_result; /* 0 for REPLY, 1 for RESULT 2 for error */ } reply_T; static garray_T reply_list = {0, 0, sizeof(reply_T), 5, 0}; #define REPLY_ITEM(i) ((reply_T *)(reply_list.ga_data) + (i)) #define REPLY_COUNT (reply_list.ga_len) /* Flag which is used to wait for a reply */ static int reply_received = 0; /* * Store a reply. "reply" must be allocated memory (or NULL). */ static int save_reply(HWND server, char_u *reply, int expr) { reply_T *rep; if (ga_grow(&reply_list, 1) == FAIL) return FAIL; rep = REPLY_ITEM(REPLY_COUNT); rep->server = server; rep->reply = reply; rep->expr_result = expr; if (rep->reply == NULL) return FAIL; ++REPLY_COUNT; reply_received = 1; return OK; } /* * Get a reply from server "server". * When "expr_res" is non NULL, get the result of an expression, otherwise a * server2client() message. * When non NULL, point to return code. 0 => OK, -1 => ERROR * If "remove" is TRUE, consume the message, the caller must free it then. * if "wait" is TRUE block until a message arrives (or the server exits). */ char_u * serverGetReply(HWND server, int *expr_res, int remove, int wait) { int i; char_u *reply; reply_T *rep; /* When waiting, loop until the message waiting for is received. */ for (;;) { /* Reset this here, in case a message arrives while we are going * through the already received messages. */ reply_received = 0; for (i = 0; i < REPLY_COUNT; ++i) { rep = REPLY_ITEM(i); if (rep->server == server && ((rep->expr_result != 0) == (expr_res != NULL))) { /* Save the values we've found for later */ reply = rep->reply; if (expr_res != NULL) *expr_res = rep->expr_result == 1 ? 0 : -1; if (remove) { /* Move the rest of the list down to fill the gap */ mch_memmove(rep, rep + 1, (REPLY_COUNT - i - 1) * sizeof(reply_T)); --REPLY_COUNT; } /* Return the reply to the caller, who takes on responsibility * for freeing it if "remove" is TRUE. */ return reply; } } /* If we got here, we didn't find a reply. Return immediately if the * "wait" parameter isn't set. */ if (!wait) break; /* We need to wait for a reply. Enter a message loop until the * "reply_received" flag gets set. */ /* Loop until we receive a reply */ while (reply_received == 0) { /* Wait for a SendMessage() call to us. This could be the reply * we are waiting for. Use a timeout of a second, to catch the * situation that the server died unexpectedly. */ MsgWaitForMultipleObjects(0, NULL, TRUE, 1000, QS_ALLINPUT); /* If the server has died, give up */ if (!IsWindow(server)) return NULL; serverProcessPendingMessages(); } } return NULL; } /* * Process any messages in the Windows message queue. */ void serverProcessPendingMessages(void) { MSG msg; while (pPeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); pDispatchMessage(&msg); } } #endif /* FEAT_CLIENTSERVER */ #if defined(FEAT_GUI) || (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) \ || defined(PROTO) struct charset_pair { char *name; BYTE charset; }; static struct charset_pair charset_pairs[] = { {"ANSI", ANSI_CHARSET}, {"CHINESEBIG5", CHINESEBIG5_CHARSET}, {"DEFAULT", DEFAULT_CHARSET}, {"HANGEUL", HANGEUL_CHARSET}, {"OEM", OEM_CHARSET}, {"SHIFTJIS", SHIFTJIS_CHARSET}, {"SYMBOL", SYMBOL_CHARSET}, #ifdef WIN3264 {"ARABIC", ARABIC_CHARSET}, {"BALTIC", BALTIC_CHARSET}, {"EASTEUROPE", EASTEUROPE_CHARSET}, {"GB2312", GB2312_CHARSET}, {"GREEK", GREEK_CHARSET}, {"HEBREW", HEBREW_CHARSET}, {"JOHAB", JOHAB_CHARSET}, {"MAC", MAC_CHARSET}, {"RUSSIAN", RUSSIAN_CHARSET}, {"THAI", THAI_CHARSET}, {"TURKISH", TURKISH_CHARSET}, # if (!defined(_MSC_VER) || (_MSC_VER > 1010)) \ && (!defined(__BORLANDC__) || (__BORLANDC__ > 0x0500)) {"VIETNAMESE", VIETNAMESE_CHARSET}, # endif #endif {NULL, 0} }; /* * Convert a charset ID to a name. * Return NULL when not recognized. */ char * charset_id2name(int id) { struct charset_pair *cp; for (cp = charset_pairs; cp->name != NULL; ++cp) if ((BYTE)id == cp->charset) break; return cp->name; } static const LOGFONT s_lfDefault = { -12, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, PROOF_QUALITY, FIXED_PITCH | FF_DONTCARE, "Fixedsys" /* see _ReadVimIni */ }; /* Initialise the "current height" to -12 (same as s_lfDefault) just * in case the user specifies a font in "guifont" with no size before a font * with an explicit size has been set. This defaults the size to this value * (-12 equates to roughly 9pt). */ int current_font_height = -12; /* also used in gui_w48.c */ /* Convert a string representing a point size into pixels. The string should * be a positive decimal number, with an optional decimal point (eg, "12", or * "10.5"). The pixel value is returned, and a pointer to the next unconverted * character is stored in *end. The flag "vertical" says whether this * calculation is for a vertical (height) size or a horizontal (width) one. */ static int points_to_pixels(char_u *str, char_u **end, int vertical, long_i pprinter_dc) { int pixels; int points = 0; int divisor = 0; HWND hwnd = (HWND)0; HDC hdc; HDC printer_dc = (HDC)pprinter_dc; while (*str != NUL) { if (*str == '.' && divisor == 0) { /* Start keeping a divisor, for later */ divisor = 1; } else { if (!VIM_ISDIGIT(*str)) break; points *= 10; points += *str - '0'; divisor *= 10; } ++str; } if (divisor == 0) divisor = 1; if (printer_dc == NULL) { hwnd = GetDesktopWindow(); hdc = GetWindowDC(hwnd); } else hdc = printer_dc; pixels = MulDiv(points, GetDeviceCaps(hdc, vertical ? LOGPIXELSY : LOGPIXELSX), 72 * divisor); if (printer_dc == NULL) ReleaseDC(hwnd, hdc); *end = str; return pixels; } /*ARGSUSED*/ static int CALLBACK font_enumproc( ENUMLOGFONT *elf, NEWTEXTMETRIC *ntm, int type, LPARAM lparam) { /* Return value: * 0 = terminate now (monospace & ANSI) * 1 = continue, still no luck... * 2 = continue, but we have an acceptable LOGFONT * (monospace, not ANSI) * We use these values, as EnumFontFamilies returns 1 if the * callback function is never called. So, we check the return as * 0 = perfect, 2 = OK, 1 = no good... * It's not pretty, but it works! */ LOGFONT *lf = (LOGFONT *)(lparam); #ifndef FEAT_PROPORTIONAL_FONTS /* Ignore non-monospace fonts without further ado */ if ((ntm->tmPitchAndFamily & 1) != 0) return 1; #endif /* Remember this LOGFONT as a "possible" */ *lf = elf->elfLogFont; /* Terminate the scan as soon as we find an ANSI font */ if (lf->lfCharSet == ANSI_CHARSET || lf->lfCharSet == OEM_CHARSET || lf->lfCharSet == DEFAULT_CHARSET) return 0; /* Continue the scan - we have a non-ANSI font */ return 2; } static int init_logfont(LOGFONT *lf) { int n; HWND hwnd = GetDesktopWindow(); HDC hdc = GetWindowDC(hwnd); n = EnumFontFamilies(hdc, (LPCSTR)lf->lfFaceName, (FONTENUMPROC)font_enumproc, (LPARAM)lf); ReleaseDC(hwnd, hdc); /* If we couldn't find a useable font, return failure */ if (n == 1) return FAIL; /* Tidy up the rest of the LOGFONT structure. We set to a basic * font - get_logfont() sets bold, italic, etc based on the user's * input. */ lf->lfHeight = current_font_height; lf->lfWidth = 0; lf->lfItalic = FALSE; lf->lfUnderline = FALSE; lf->lfStrikeOut = FALSE; lf->lfWeight = FW_NORMAL; /* Return success */ return OK; } /* * Get font info from "name" into logfont "lf". * Return OK for a valid name, FAIL otherwise. */ int get_logfont( LOGFONT *lf, char_u *name, HDC printer_dc, int verbose) { char_u *p; int i; static LOGFONT *lastlf = NULL; *lf = s_lfDefault; if (name == NULL) return OK; if (STRCMP(name, "*") == 0) { #if defined(FEAT_GUI_W32) CHOOSEFONT cf; /* if name is "*", bring up std font dialog: */ vim_memset(&cf, 0, sizeof(cf)); cf.lStructSize = sizeof(cf); cf.hwndOwner = s_hwnd; cf.Flags = CF_SCREENFONTS | CF_FIXEDPITCHONLY | CF_INITTOLOGFONTSTRUCT; if (lastlf != NULL) *lf = *lastlf; cf.lpLogFont = lf; cf.nFontType = 0 ; //REGULAR_FONTTYPE; if (ChooseFont(&cf)) goto theend; #else return FAIL; #endif } /* * Split name up, it could be <name>:h<height>:w<width> etc. */ for (p = name; *p && *p != ':'; p++) { if (p - name + 1 > LF_FACESIZE) return FAIL; /* Name too long */ lf->lfFaceName[p - name] = *p; } if (p != name) lf->lfFaceName[p - name] = NUL; /* First set defaults */ lf->lfHeight = -12; lf->lfWidth = 0; lf->lfWeight = FW_NORMAL; lf->lfItalic = FALSE; lf->lfUnderline = FALSE; lf->lfStrikeOut = FALSE; /* * If the font can't be found, try replacing '_' by ' '. */ if (init_logfont(lf) == FAIL) { int did_replace = FALSE; for (i = 0; lf->lfFaceName[i]; ++i) if (lf->lfFaceName[i] == '_') { lf->lfFaceName[i] = ' '; did_replace = TRUE; } if (!did_replace || init_logfont(lf) == FAIL) return FAIL; } while (*p == ':') p++; /* Set the values found after ':' */ while (*p) { switch (*p++) { case 'h': lf->lfHeight = - points_to_pixels(p, &p, TRUE, (long_i)printer_dc); break; case 'w': lf->lfWidth = points_to_pixels(p, &p, FALSE, (long_i)printer_dc); break; case 'b': #ifndef MSWIN16_FASTTEXT lf->lfWeight = FW_BOLD; #endif break; case 'i': #ifndef MSWIN16_FASTTEXT lf->lfItalic = TRUE; #endif break; case 'u': lf->lfUnderline = TRUE; break; case 's': lf->lfStrikeOut = TRUE; break; case 'c': { struct charset_pair *cp; for (cp = charset_pairs; cp->name != NULL; ++cp) if (STRNCMP(p, cp->name, strlen(cp->name)) == 0) { lf->lfCharSet = cp->charset; p += strlen(cp->name); break; } if (cp->name == NULL && verbose) { vim_snprintf((char *)IObuff, IOSIZE, _("E244: Illegal charset name \"%s\" in font name \"%s\""), p, name); EMSG(IObuff); break; } break; } default: if (verbose) { vim_snprintf((char *)IObuff, IOSIZE, _("E245: Illegal char '%c' in font name \"%s\""), p[-1], name); EMSG(IObuff); } return FAIL; } while (*p == ':') p++; } #if defined(FEAT_GUI_W32) theend: #endif /* ron: init lastlf */ if (printer_dc == NULL) { vim_free(lastlf); lastlf = (LOGFONT *)alloc(sizeof(LOGFONT)); if (lastlf != NULL) mch_memmove(lastlf, lf, sizeof(LOGFONT)); } return OK; } #endif /* defined(FEAT_GUI) || defined(FEAT_PRINTER) */
zyz2011-vim
src/os_mswin.c
C
gpl2
82,142
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * edit.c: functions for Insert mode */ #include "vim.h" #ifdef FEAT_INS_EXPAND /* * definitions used for CTRL-X submode */ #define CTRL_X_WANT_IDENT 0x100 #define CTRL_X_NOT_DEFINED_YET 1 #define CTRL_X_SCROLL 2 #define CTRL_X_WHOLE_LINE 3 #define CTRL_X_FILES 4 #define CTRL_X_TAGS (5 + CTRL_X_WANT_IDENT) #define CTRL_X_PATH_PATTERNS (6 + CTRL_X_WANT_IDENT) #define CTRL_X_PATH_DEFINES (7 + CTRL_X_WANT_IDENT) #define CTRL_X_FINISHED 8 #define CTRL_X_DICTIONARY (9 + CTRL_X_WANT_IDENT) #define CTRL_X_THESAURUS (10 + CTRL_X_WANT_IDENT) #define CTRL_X_CMDLINE 11 #define CTRL_X_FUNCTION 12 #define CTRL_X_OMNI 13 #define CTRL_X_SPELL 14 #define CTRL_X_LOCAL_MSG 15 /* only used in "ctrl_x_msgs" */ #define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT] static char *ctrl_x_msgs[] = { N_(" Keyword completion (^N^P)"), /* ctrl_x_mode == 0, ^P/^N compl. */ N_(" ^X mode (^]^D^E^F^I^K^L^N^O^Ps^U^V^Y)"), NULL, N_(" Whole line completion (^L^N^P)"), N_(" File name completion (^F^N^P)"), N_(" Tag completion (^]^N^P)"), N_(" Path pattern completion (^N^P)"), N_(" Definition completion (^D^N^P)"), NULL, N_(" Dictionary completion (^K^N^P)"), N_(" Thesaurus completion (^T^N^P)"), N_(" Command-line completion (^V^N^P)"), N_(" User defined completion (^U^N^P)"), N_(" Omni completion (^O^N^P)"), N_(" Spelling suggestion (s^N^P)"), N_(" Keyword Local completion (^N^P)"), }; static char e_hitend[] = N_("Hit end of paragraph"); #ifdef FEAT_COMPL_FUNC static char e_complwin[] = N_("E839: Completion function changed window"); static char e_compldel[] = N_("E840: Completion function deleted text"); #endif /* * Structure used to store one match for insert completion. */ typedef struct compl_S compl_T; struct compl_S { compl_T *cp_next; compl_T *cp_prev; char_u *cp_str; /* matched text */ char cp_icase; /* TRUE or FALSE: ignore case */ char_u *(cp_text[CPT_COUNT]); /* text for the menu */ char_u *cp_fname; /* file containing the match, allocated when * cp_flags has FREE_FNAME */ int cp_flags; /* ORIGINAL_TEXT, CONT_S_IPOS or FREE_FNAME */ int cp_number; /* sequence number */ }; #define ORIGINAL_TEXT (1) /* the original text when the expansion begun */ #define FREE_FNAME (2) /* * All the current matches are stored in a list. * "compl_first_match" points to the start of the list. * "compl_curr_match" points to the currently selected entry. * "compl_shown_match" is different from compl_curr_match during * ins_compl_get_exp(). */ static compl_T *compl_first_match = NULL; static compl_T *compl_curr_match = NULL; static compl_T *compl_shown_match = NULL; /* After using a cursor key <Enter> selects a match in the popup menu, * otherwise it inserts a line break. */ static int compl_enter_selects = FALSE; /* When "compl_leader" is not NULL only matches that start with this string * are used. */ static char_u *compl_leader = NULL; static int compl_get_longest = FALSE; /* put longest common string in compl_leader */ static int compl_used_match; /* Selected one of the matches. When FALSE the match was edited or using the longest common string. */ static int compl_was_interrupted = FALSE; /* didn't finish finding completions. */ static int compl_restarting = FALSE; /* don't insert match */ /* When the first completion is done "compl_started" is set. When it's * FALSE the word to be completed must be located. */ static int compl_started = FALSE; /* Set when doing something for completion that may call edit() recursively, * which is not allowed. */ static int compl_busy = FALSE; static int compl_matches = 0; static char_u *compl_pattern = NULL; static int compl_direction = FORWARD; static int compl_shows_dir = FORWARD; static int compl_pending = 0; /* > 1 for postponed CTRL-N */ static pos_T compl_startpos; static colnr_T compl_col = 0; /* column where the text starts * that is being completed */ static char_u *compl_orig_text = NULL; /* text as it was before * completion started */ static int compl_cont_mode = 0; static expand_T compl_xp; static int compl_opt_refresh_always = FALSE; static void ins_ctrl_x __ARGS((void)); static int has_compl_option __ARGS((int dict_opt)); static int ins_compl_accept_char __ARGS((int c)); static int ins_compl_add __ARGS((char_u *str, int len, int icase, char_u *fname, char_u **cptext, int cdir, int flags, int adup)); static int ins_compl_equal __ARGS((compl_T *match, char_u *str, int len)); static void ins_compl_longest_match __ARGS((compl_T *match)); static void ins_compl_add_matches __ARGS((int num_matches, char_u **matches, int icase)); static int ins_compl_make_cyclic __ARGS((void)); static void ins_compl_upd_pum __ARGS((void)); static void ins_compl_del_pum __ARGS((void)); static int pum_wanted __ARGS((void)); static int pum_enough_matches __ARGS((void)); static void ins_compl_dictionaries __ARGS((char_u *dict, char_u *pat, int flags, int thesaurus)); static void ins_compl_files __ARGS((int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir)); static char_u *find_line_end __ARGS((char_u *ptr)); static void ins_compl_free __ARGS((void)); static void ins_compl_clear __ARGS((void)); static int ins_compl_bs __ARGS((void)); static int ins_compl_need_restart __ARGS((void)); static void ins_compl_new_leader __ARGS((void)); static void ins_compl_addleader __ARGS((int c)); static int ins_compl_len __ARGS((void)); static void ins_compl_restart __ARGS((void)); static void ins_compl_set_original_text __ARGS((char_u *str)); static void ins_compl_addfrommatch __ARGS((void)); static int ins_compl_prep __ARGS((int c)); static void ins_compl_fixRedoBufForLeader __ARGS((char_u *ptr_arg)); static buf_T *ins_compl_next_buf __ARGS((buf_T *buf, int flag)); #if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) static void ins_compl_add_list __ARGS((list_T *list)); static void ins_compl_add_dict __ARGS((dict_T *dict)); #endif static int ins_compl_get_exp __ARGS((pos_T *ini)); static void ins_compl_delete __ARGS((void)); static void ins_compl_insert __ARGS((void)); static int ins_compl_next __ARGS((int allow_get_expansion, int count, int insert_match)); static int ins_compl_key2dir __ARGS((int c)); static int ins_compl_pum_key __ARGS((int c)); static int ins_compl_key2count __ARGS((int c)); static int ins_compl_use_match __ARGS((int c)); static int ins_complete __ARGS((int c)); static unsigned quote_meta __ARGS((char_u *dest, char_u *str, int len)); #endif /* FEAT_INS_EXPAND */ #define BACKSPACE_CHAR 1 #define BACKSPACE_WORD 2 #define BACKSPACE_WORD_NOT_SPACE 3 #define BACKSPACE_LINE 4 static void ins_redraw __ARGS((int ready)); static void ins_ctrl_v __ARGS((void)); static void undisplay_dollar __ARGS((void)); static void insert_special __ARGS((int, int, int)); static void internal_format __ARGS((int textwidth, int second_indent, int flags, int format_only, int c)); static void check_auto_format __ARGS((int)); static void redo_literal __ARGS((int c)); static void start_arrow __ARGS((pos_T *end_insert_pos)); #ifdef FEAT_SPELL static void check_spell_redraw __ARGS((void)); static void spell_back_to_badword __ARGS((void)); static int spell_bad_len = 0; /* length of located bad word */ #endif static void stop_insert __ARGS((pos_T *end_insert_pos, int esc)); static int echeck_abbr __ARGS((int)); static int replace_pop __ARGS((void)); static void replace_join __ARGS((int off)); static void replace_pop_ins __ARGS((void)); #ifdef FEAT_MBYTE static void mb_replace_pop_ins __ARGS((int cc)); #endif static void replace_flush __ARGS((void)); static void replace_do_bs __ARGS((int limit_col)); static int del_char_after_col __ARGS((int limit_col)); #ifdef FEAT_CINDENT static int cindent_on __ARGS((void)); #endif static void ins_reg __ARGS((void)); static void ins_ctrl_g __ARGS((void)); static void ins_ctrl_hat __ARGS((void)); static int ins_esc __ARGS((long *count, int cmdchar, int nomove)); #ifdef FEAT_RIGHTLEFT static void ins_ctrl_ __ARGS((void)); #endif #ifdef FEAT_VISUAL static int ins_start_select __ARGS((int c)); #endif static void ins_insert __ARGS((int replaceState)); static void ins_ctrl_o __ARGS((void)); static void ins_shift __ARGS((int c, int lastc)); static void ins_del __ARGS((void)); static int ins_bs __ARGS((int c, int mode, int *inserted_space_p)); #ifdef FEAT_MOUSE static void ins_mouse __ARGS((int c)); static void ins_mousescroll __ARGS((int dir)); #endif #if defined(FEAT_GUI_TABLINE) || defined(PROTO) static void ins_tabline __ARGS((int c)); #endif static void ins_left __ARGS((void)); static void ins_home __ARGS((int c)); static void ins_end __ARGS((int c)); static void ins_s_left __ARGS((void)); static void ins_right __ARGS((void)); static void ins_s_right __ARGS((void)); static void ins_up __ARGS((int startcol)); static void ins_pageup __ARGS((void)); static void ins_down __ARGS((int startcol)); static void ins_pagedown __ARGS((void)); #ifdef FEAT_DND static void ins_drop __ARGS((void)); #endif static int ins_tab __ARGS((void)); static int ins_eol __ARGS((int c)); #ifdef FEAT_DIGRAPHS static int ins_digraph __ARGS((void)); #endif static int ins_ctrl_ey __ARGS((int tc)); #ifdef FEAT_SMARTINDENT static void ins_try_si __ARGS((int c)); #endif static colnr_T get_nolist_virtcol __ARGS((void)); #ifdef FEAT_AUTOCMD static char_u *do_insert_char_pre __ARGS((int c)); #endif static colnr_T Insstart_textlen; /* length of line when insert started */ static colnr_T Insstart_blank_vcol; /* vcol for first inserted blank */ static char_u *last_insert = NULL; /* the text of the previous insert, K_SPECIAL and CSI are escaped */ static int last_insert_skip; /* nr of chars in front of previous insert */ static int new_insert_skip; /* nr of chars in front of current insert */ static int did_restart_edit; /* "restart_edit" when calling edit() */ #ifdef FEAT_CINDENT static int can_cindent; /* may do cindenting on this line */ #endif static int old_indent = 0; /* for ^^D command in insert mode */ #ifdef FEAT_RIGHTLEFT static int revins_on; /* reverse insert mode on */ static int revins_chars; /* how much to skip after edit */ static int revins_legal; /* was the last char 'legal'? */ static int revins_scol; /* start column of revins session */ #endif static int ins_need_undo; /* call u_save() before inserting a char. Set when edit() is called. after that arrow_used is used. */ static int did_add_space = FALSE; /* auto_format() added an extra space under the cursor */ /* * edit(): Start inserting text. * * "cmdchar" can be: * 'i' normal insert command * 'a' normal append command * 'R' replace command * 'r' "r<CR>" command: insert one <CR>. Note: count can be > 1, for redo, * but still only one <CR> is inserted. The <Esc> is not used for redo. * 'g' "gI" command. * 'V' "gR" command for Virtual Replace mode. * 'v' "gr" command for single character Virtual Replace mode. * * This function is not called recursively. For CTRL-O commands, it returns * and lets the caller handle the Normal-mode command. * * Return TRUE if a CTRL-O command caused the return (insert mode pending). */ int edit(cmdchar, startln, count) int cmdchar; int startln; /* if set, insert at start of line */ long count; { int c = 0; char_u *ptr; int lastc; int mincol; static linenr_T o_lnum = 0; int i; int did_backspace = TRUE; /* previous char was backspace */ #ifdef FEAT_CINDENT int line_is_white = FALSE; /* line is empty before insert */ #endif linenr_T old_topline = 0; /* topline before insertion */ #ifdef FEAT_DIFF int old_topfill = -1; #endif int inserted_space = FALSE; /* just inserted a space */ int replaceState = REPLACE; int nomove = FALSE; /* don't move cursor on return */ /* Remember whether editing was restarted after CTRL-O. */ did_restart_edit = restart_edit; /* sleep before redrawing, needed for "CTRL-O :" that results in an * error message */ check_for_delay(TRUE); #ifdef HAVE_SANDBOX /* Don't allow inserting in the sandbox. */ if (sandbox != 0) { EMSG(_(e_sandbox)); return FALSE; } #endif /* Don't allow changes in the buffer while editing the cmdline. The * caller of getcmdline() may get confused. */ if (textlock != 0) { EMSG(_(e_secure)); return FALSE; } #ifdef FEAT_INS_EXPAND /* Don't allow recursive insert mode when busy with completion. */ if (compl_started || compl_busy || pum_visible()) { EMSG(_(e_secure)); return FALSE; } ins_compl_clear(); /* clear stuff for CTRL-X mode */ #endif #ifdef FEAT_AUTOCMD /* * Trigger InsertEnter autocommands. Do not do this for "r<CR>" or "grx". */ if (cmdchar != 'r' && cmdchar != 'v') { # ifdef FEAT_EVAL if (cmdchar == 'R') ptr = (char_u *)"r"; else if (cmdchar == 'V') ptr = (char_u *)"v"; else ptr = (char_u *)"i"; set_vim_var_string(VV_INSERTMODE, ptr, 1); # endif apply_autocmds(EVENT_INSERTENTER, NULL, NULL, FALSE, curbuf); } #endif #ifdef FEAT_CONCEAL /* Check if the cursor line needs redrawing before changing State. If * 'concealcursor' is "n" it needs to be redrawn without concealing. */ conceal_check_cursur_line(); #endif #ifdef FEAT_MOUSE /* * When doing a paste with the middle mouse button, Insstart is set to * where the paste started. */ if (where_paste_started.lnum != 0) Insstart = where_paste_started; else #endif { Insstart = curwin->w_cursor; if (startln) Insstart.col = 0; } Insstart_textlen = (colnr_T)linetabsize(ml_get_curline()); Insstart_blank_vcol = MAXCOL; if (!did_ai) ai_col = 0; if (cmdchar != NUL && restart_edit == 0) { ResetRedobuff(); AppendNumberToRedobuff(count); #ifdef FEAT_VREPLACE if (cmdchar == 'V' || cmdchar == 'v') { /* "gR" or "gr" command */ AppendCharToRedobuff('g'); AppendCharToRedobuff((cmdchar == 'v') ? 'r' : 'R'); } else #endif { AppendCharToRedobuff(cmdchar); if (cmdchar == 'g') /* "gI" command */ AppendCharToRedobuff('I'); else if (cmdchar == 'r') /* "r<CR>" command */ count = 1; /* insert only one <CR> */ } } if (cmdchar == 'R') { #ifdef FEAT_FKMAP if (p_fkmap && p_ri) { beep_flush(); EMSG(farsi_text_3); /* encoded in Farsi */ State = INSERT; } else #endif State = REPLACE; } #ifdef FEAT_VREPLACE else if (cmdchar == 'V' || cmdchar == 'v') { State = VREPLACE; replaceState = VREPLACE; orig_line_count = curbuf->b_ml.ml_line_count; vr_lines_changed = 1; } #endif else State = INSERT; stop_insert_mode = FALSE; /* * Need to recompute the cursor position, it might move when the cursor is * on a TAB or special character. */ curs_columns(TRUE); /* * Enable langmap or IME, indicated by 'iminsert'. * Note that IME may enabled/disabled without us noticing here, thus the * 'iminsert' value may not reflect what is actually used. It is updated * when hitting <Esc>. */ if (curbuf->b_p_iminsert == B_IMODE_LMAP) State |= LANGMAP; #ifdef USE_IM_CONTROL im_set_active(curbuf->b_p_iminsert == B_IMODE_IM); #endif #ifdef FEAT_MOUSE setmouse(); #endif #ifdef FEAT_CMDL_INFO clear_showcmd(); #endif #ifdef FEAT_RIGHTLEFT /* there is no reverse replace mode */ revins_on = (State == INSERT && p_ri); if (revins_on) undisplay_dollar(); revins_chars = 0; revins_legal = 0; revins_scol = -1; #endif /* * Handle restarting Insert mode. * Don't do this for "CTRL-O ." (repeat an insert): we get here with * restart_edit non-zero, and something in the stuff buffer. */ if (restart_edit != 0 && stuff_empty()) { #ifdef FEAT_MOUSE /* * After a paste we consider text typed to be part of the insert for * the pasted text. You can backspace over the pasted text too. */ if (where_paste_started.lnum) arrow_used = FALSE; else #endif arrow_used = TRUE; restart_edit = 0; /* * If the cursor was after the end-of-line before the CTRL-O and it is * now at the end-of-line, put it after the end-of-line (this is not * correct in very rare cases). * Also do this if curswant is greater than the current virtual * column. Eg after "^O$" or "^O80|". */ validate_virtcol(); update_curswant(); if (((ins_at_eol && curwin->w_cursor.lnum == o_lnum) || curwin->w_curswant > curwin->w_virtcol) && *(ptr = ml_get_curline() + curwin->w_cursor.col) != NUL) { if (ptr[1] == NUL) ++curwin->w_cursor.col; #ifdef FEAT_MBYTE else if (has_mbyte) { i = (*mb_ptr2len)(ptr); if (ptr[i] == NUL) curwin->w_cursor.col += i; } #endif } ins_at_eol = FALSE; } else arrow_used = FALSE; /* we are in insert mode now, don't need to start it anymore */ need_start_insertmode = FALSE; /* Need to save the line for undo before inserting the first char. */ ins_need_undo = TRUE; #ifdef FEAT_MOUSE where_paste_started.lnum = 0; #endif #ifdef FEAT_CINDENT can_cindent = TRUE; #endif #ifdef FEAT_FOLDING /* The cursor line is not in a closed fold, unless 'insertmode' is set or * restarting. */ if (!p_im && did_restart_edit == 0) foldOpenCursor(); #endif /* * If 'showmode' is set, show the current (insert/replace/..) mode. * A warning message for changing a readonly file is given here, before * actually changing anything. It's put after the mode, if any. */ i = 0; if (p_smd && msg_silent == 0) i = showmode(); if (!p_im && did_restart_edit == 0) change_warning(i == 0 ? 0 : i + 1); #ifdef CURSOR_SHAPE ui_cursor_shape(); /* may show different cursor shape */ #endif #ifdef FEAT_DIGRAPHS do_digraph(-1); /* clear digraphs */ #endif /* * Get the current length of the redo buffer, those characters have to be * skipped if we want to get to the inserted characters. */ ptr = get_inserted(); if (ptr == NULL) new_insert_skip = 0; else { new_insert_skip = (int)STRLEN(ptr); vim_free(ptr); } old_indent = 0; /* * Main loop in Insert mode: repeat until Insert mode is left. */ for (;;) { #ifdef FEAT_RIGHTLEFT if (!revins_legal) revins_scol = -1; /* reset on illegal motions */ else revins_legal = 0; #endif if (arrow_used) /* don't repeat insert when arrow key used */ count = 0; if (stop_insert_mode) { /* ":stopinsert" used or 'insertmode' reset */ count = 0; goto doESCkey; } /* set curwin->w_curswant for next K_DOWN or K_UP */ if (!arrow_used) curwin->w_set_curswant = TRUE; /* If there is no typeahead may check for timestamps (e.g., for when a * menu invoked a shell command). */ if (stuff_empty()) { did_check_timestamps = FALSE; if (need_check_timestamps) check_timestamps(FALSE); } /* * When emsg() was called msg_scroll will have been set. */ msg_scroll = FALSE; #ifdef FEAT_GUI /* When 'mousefocus' is set a mouse movement may have taken us to * another window. "need_mouse_correct" may then be set because of an * autocommand. */ if (need_mouse_correct) gui_mouse_correct(); #endif #ifdef FEAT_FOLDING /* Open fold at the cursor line, according to 'foldopen'. */ if (fdo_flags & FDO_INSERT) foldOpenCursor(); /* Close folds where the cursor isn't, according to 'foldclose' */ if (!char_avail()) foldCheckClose(); #endif /* * If we inserted a character at the last position of the last line in * the window, scroll the window one line up. This avoids an extra * redraw. * This is detected when the cursor column is smaller after inserting * something. * Don't do this when the topline changed already, it has * already been adjusted (by insertchar() calling open_line())). */ if (curbuf->b_mod_set && curwin->w_p_wrap && !did_backspace && curwin->w_topline == old_topline #ifdef FEAT_DIFF && curwin->w_topfill == old_topfill #endif ) { mincol = curwin->w_wcol; validate_cursor_col(); if ((int)curwin->w_wcol < mincol - curbuf->b_p_ts && curwin->w_wrow == W_WINROW(curwin) + curwin->w_height - 1 - p_so && (curwin->w_cursor.lnum != curwin->w_topline #ifdef FEAT_DIFF || curwin->w_topfill > 0 #endif )) { #ifdef FEAT_DIFF if (curwin->w_topfill > 0) --curwin->w_topfill; else #endif #ifdef FEAT_FOLDING if (hasFolding(curwin->w_topline, NULL, &old_topline)) set_topline(curwin, old_topline + 1); else #endif set_topline(curwin, curwin->w_topline + 1); } } /* May need to adjust w_topline to show the cursor. */ update_topline(); did_backspace = FALSE; validate_cursor(); /* may set must_redraw */ /* * Redraw the display when no characters are waiting. * Also shows mode, ruler and positions cursor. */ ins_redraw(TRUE); #ifdef FEAT_SCROLLBIND if (curwin->w_p_scb) do_check_scrollbind(TRUE); #endif #ifdef FEAT_CURSORBIND if (curwin->w_p_crb) do_check_cursorbind(); #endif update_curswant(); old_topline = curwin->w_topline; #ifdef FEAT_DIFF old_topfill = curwin->w_topfill; #endif #ifdef USE_ON_FLY_SCROLL dont_scroll = FALSE; /* allow scrolling here */ #endif /* * Get a character for Insert mode. Ignore K_IGNORE. */ lastc = c; /* remember previous char for CTRL-D */ do { c = safe_vgetc(); } while (c == K_IGNORE); #ifdef FEAT_AUTOCMD /* Don't want K_CURSORHOLD for the second key, e.g., after CTRL-V. */ did_cursorhold = TRUE; #endif #ifdef FEAT_RIGHTLEFT if (p_hkmap && KeyTyped) c = hkmap(c); /* Hebrew mode mapping */ #endif #ifdef FEAT_FKMAP if (p_fkmap && KeyTyped) c = fkmap(c); /* Farsi mode mapping */ #endif #ifdef FEAT_INS_EXPAND /* * Special handling of keys while the popup menu is visible or wanted * and the cursor is still in the completed word. Only when there is * a match, skip this when no matches were found. */ if (compl_started && pum_wanted() && curwin->w_cursor.col >= compl_col && (compl_shown_match == NULL || compl_shown_match != compl_shown_match->cp_next)) { /* BS: Delete one character from "compl_leader". */ if ((c == K_BS || c == Ctrl_H) && curwin->w_cursor.col > compl_col && (c = ins_compl_bs()) == NUL) continue; /* When no match was selected or it was edited. */ if (!compl_used_match) { /* CTRL-L: Add one character from the current match to * "compl_leader". Except when at the original match and * there is nothing to add, CTRL-L works like CTRL-P then. */ if (c == Ctrl_L && (ctrl_x_mode != CTRL_X_WHOLE_LINE || (int)STRLEN(compl_shown_match->cp_str) > curwin->w_cursor.col - compl_col)) { ins_compl_addfrommatch(); continue; } /* A non-white character that fits in with the current * completion: Add to "compl_leader". */ if (ins_compl_accept_char(c)) { #ifdef FEAT_AUTOCMD /* Trigger InsertCharPre. */ char_u *str = do_insert_char_pre(c); char_u *p; if (str != NULL) { for (p = str; *p != NUL; mb_ptr_adv(p)) ins_compl_addleader(PTR2CHAR(p)); vim_free(str); } else #endif ins_compl_addleader(c); continue; } /* Pressing CTRL-Y selects the current match. When * compl_enter_selects is set the Enter key does the same. */ if (c == Ctrl_Y || (compl_enter_selects && (c == CAR || c == K_KENTER || c == NL))) { ins_compl_delete(); ins_compl_insert(); } } } /* Prepare for or stop CTRL-X mode. This doesn't do completion, but * it does fix up the text when finishing completion. */ compl_get_longest = FALSE; if (ins_compl_prep(c)) continue; #endif /* CTRL-\ CTRL-N goes to Normal mode, * CTRL-\ CTRL-G goes to mode selected with 'insertmode', * CTRL-\ CTRL-O is like CTRL-O but without moving the cursor. */ if (c == Ctrl_BSL) { /* may need to redraw when no more chars available now */ ins_redraw(FALSE); ++no_mapping; ++allow_keys; c = plain_vgetc(); --no_mapping; --allow_keys; if (c != Ctrl_N && c != Ctrl_G && c != Ctrl_O) { /* it's something else */ vungetc(c); c = Ctrl_BSL; } else if (c == Ctrl_G && p_im) continue; else { if (c == Ctrl_O) { ins_ctrl_o(); ins_at_eol = FALSE; /* cursor keeps its column */ nomove = TRUE; } count = 0; goto doESCkey; } } #ifdef FEAT_DIGRAPHS c = do_digraph(c); #endif #ifdef FEAT_INS_EXPAND if ((c == Ctrl_V || c == Ctrl_Q) && ctrl_x_mode == CTRL_X_CMDLINE) goto docomplete; #endif if (c == Ctrl_V || c == Ctrl_Q) { ins_ctrl_v(); c = Ctrl_V; /* pretend CTRL-V is last typed character */ continue; } #ifdef FEAT_CINDENT if (cindent_on() # ifdef FEAT_INS_EXPAND && ctrl_x_mode == 0 # endif ) { /* A key name preceded by a bang means this key is not to be * inserted. Skip ahead to the re-indenting below. * A key name preceded by a star means that indenting has to be * done before inserting the key. */ line_is_white = inindent(0); if (in_cinkeys(c, '!', line_is_white)) goto force_cindent; if (can_cindent && in_cinkeys(c, '*', line_is_white) && stop_arrow() == OK) do_c_expr_indent(); } #endif #ifdef FEAT_RIGHTLEFT if (curwin->w_p_rl) switch (c) { case K_LEFT: c = K_RIGHT; break; case K_S_LEFT: c = K_S_RIGHT; break; case K_C_LEFT: c = K_C_RIGHT; break; case K_RIGHT: c = K_LEFT; break; case K_S_RIGHT: c = K_S_LEFT; break; case K_C_RIGHT: c = K_C_LEFT; break; } #endif #ifdef FEAT_VISUAL /* * If 'keymodel' contains "startsel", may start selection. If it * does, a CTRL-O and c will be stuffed, we need to get these * characters. */ if (ins_start_select(c)) continue; #endif /* * The big switch to handle a character in insert mode. */ switch (c) { case ESC: /* End input mode */ if (echeck_abbr(ESC + ABBR_OFF)) break; /*FALLTHROUGH*/ case Ctrl_C: /* End input mode */ #ifdef FEAT_CMDWIN if (c == Ctrl_C && cmdwin_type != 0) { /* Close the cmdline window. */ cmdwin_result = K_IGNORE; got_int = FALSE; /* don't stop executing autocommands et al. */ nomove = TRUE; goto doESCkey; } #endif #ifdef UNIX do_intr: #endif /* when 'insertmode' set, and not halfway a mapping, don't leave * Insert mode */ if (goto_im()) { if (got_int) { (void)vgetc(); /* flush all buffers */ got_int = FALSE; } else vim_beep(); break; } doESCkey: /* * This is the ONLY return from edit()! */ /* Always update o_lnum, so that a "CTRL-O ." that adds a line * still puts the cursor back after the inserted text. */ if (ins_at_eol && gchar_cursor() == NUL) o_lnum = curwin->w_cursor.lnum; if (ins_esc(&count, cmdchar, nomove)) { #ifdef FEAT_AUTOCMD if (cmdchar != 'r' && cmdchar != 'v') apply_autocmds(EVENT_INSERTLEAVE, NULL, NULL, FALSE, curbuf); did_cursorhold = FALSE; #endif return (c == Ctrl_O); } continue; case Ctrl_Z: /* suspend when 'insertmode' set */ if (!p_im) goto normalchar; /* insert CTRL-Z as normal char */ stuffReadbuff((char_u *)":st\r"); c = Ctrl_O; /*FALLTHROUGH*/ case Ctrl_O: /* execute one command */ #ifdef FEAT_COMPL_FUNC if (ctrl_x_mode == CTRL_X_OMNI) goto docomplete; #endif if (echeck_abbr(Ctrl_O + ABBR_OFF)) break; ins_ctrl_o(); #ifdef FEAT_VIRTUALEDIT /* don't move the cursor left when 'virtualedit' has "onemore". */ if (ve_flags & VE_ONEMORE) { ins_at_eol = FALSE; nomove = TRUE; } #endif count = 0; goto doESCkey; case K_INS: /* toggle insert/replace mode */ case K_KINS: ins_insert(replaceState); break; case K_SELECT: /* end of Select mode mapping - ignore */ break; #ifdef FEAT_SNIFF case K_SNIFF: /* Sniff command received */ stuffcharReadbuff(K_SNIFF); goto doESCkey; #endif case K_HELP: /* Help key works like <ESC> <Help> */ case K_F1: case K_XF1: stuffcharReadbuff(K_HELP); if (p_im) need_start_insertmode = TRUE; goto doESCkey; #ifdef FEAT_NETBEANS_INTG case K_F21: /* NetBeans command */ ++no_mapping; /* don't map the next key hits */ i = plain_vgetc(); --no_mapping; netbeans_keycommand(i); break; #endif case K_ZERO: /* Insert the previously inserted text. */ case NUL: case Ctrl_A: /* For ^@ the trailing ESC will end the insert, unless there is an * error. */ if (stuff_inserted(NUL, 1L, (c == Ctrl_A)) == FAIL && c != Ctrl_A && !p_im) goto doESCkey; /* quit insert mode */ inserted_space = FALSE; break; case Ctrl_R: /* insert the contents of a register */ ins_reg(); auto_format(FALSE, TRUE); inserted_space = FALSE; break; case Ctrl_G: /* commands starting with CTRL-G */ ins_ctrl_g(); break; case Ctrl_HAT: /* switch input mode and/or langmap */ ins_ctrl_hat(); break; #ifdef FEAT_RIGHTLEFT case Ctrl__: /* switch between languages */ if (!p_ari) goto normalchar; ins_ctrl_(); break; #endif case Ctrl_D: /* Make indent one shiftwidth smaller. */ #if defined(FEAT_INS_EXPAND) && defined(FEAT_FIND_ID) if (ctrl_x_mode == CTRL_X_PATH_DEFINES) goto docomplete; #endif /* FALLTHROUGH */ case Ctrl_T: /* Make indent one shiftwidth greater. */ # ifdef FEAT_INS_EXPAND if (c == Ctrl_T && ctrl_x_mode == CTRL_X_THESAURUS) { if (has_compl_option(FALSE)) goto docomplete; break; } # endif ins_shift(c, lastc); auto_format(FALSE, TRUE); inserted_space = FALSE; break; case K_DEL: /* delete character under the cursor */ case K_KDEL: ins_del(); auto_format(FALSE, TRUE); break; case K_BS: /* delete character before the cursor */ case Ctrl_H: did_backspace = ins_bs(c, BACKSPACE_CHAR, &inserted_space); auto_format(FALSE, TRUE); break; case Ctrl_W: /* delete word before the cursor */ did_backspace = ins_bs(c, BACKSPACE_WORD, &inserted_space); auto_format(FALSE, TRUE); break; case Ctrl_U: /* delete all inserted text in current line */ # ifdef FEAT_COMPL_FUNC /* CTRL-X CTRL-U completes with 'completefunc'. */ if (ctrl_x_mode == CTRL_X_FUNCTION) goto docomplete; # endif did_backspace = ins_bs(c, BACKSPACE_LINE, &inserted_space); auto_format(FALSE, TRUE); inserted_space = FALSE; break; #ifdef FEAT_MOUSE case K_LEFTMOUSE: /* mouse keys */ case K_LEFTMOUSE_NM: case K_LEFTDRAG: case K_LEFTRELEASE: case K_LEFTRELEASE_NM: case K_MIDDLEMOUSE: case K_MIDDLEDRAG: case K_MIDDLERELEASE: case K_RIGHTMOUSE: case K_RIGHTDRAG: case K_RIGHTRELEASE: case K_X1MOUSE: case K_X1DRAG: case K_X1RELEASE: case K_X2MOUSE: case K_X2DRAG: case K_X2RELEASE: ins_mouse(c); break; case K_MOUSEDOWN: /* Default action for scroll wheel up: scroll up */ ins_mousescroll(MSCR_DOWN); break; case K_MOUSEUP: /* Default action for scroll wheel down: scroll down */ ins_mousescroll(MSCR_UP); break; case K_MOUSELEFT: /* Scroll wheel left */ ins_mousescroll(MSCR_LEFT); break; case K_MOUSERIGHT: /* Scroll wheel right */ ins_mousescroll(MSCR_RIGHT); break; #endif #ifdef FEAT_GUI_TABLINE case K_TABLINE: case K_TABMENU: ins_tabline(c); break; #endif case K_IGNORE: /* Something mapped to nothing */ break; #ifdef FEAT_AUTOCMD case K_CURSORHOLD: /* Didn't type something for a while. */ apply_autocmds(EVENT_CURSORHOLDI, NULL, NULL, FALSE, curbuf); did_cursorhold = TRUE; break; #endif #ifdef FEAT_GUI_W32 /* On Win32 ignore <M-F4>, we get it when closing the window was * cancelled. */ case K_F4: if (mod_mask != MOD_MASK_ALT) goto normalchar; break; #endif #ifdef FEAT_GUI case K_VER_SCROLLBAR: ins_scroll(); break; case K_HOR_SCROLLBAR: ins_horscroll(); break; #endif case K_HOME: /* <Home> */ case K_KHOME: case K_S_HOME: case K_C_HOME: ins_home(c); break; case K_END: /* <End> */ case K_KEND: case K_S_END: case K_C_END: ins_end(c); break; case K_LEFT: /* <Left> */ if (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)) ins_s_left(); else ins_left(); break; case K_S_LEFT: /* <S-Left> */ case K_C_LEFT: ins_s_left(); break; case K_RIGHT: /* <Right> */ if (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)) ins_s_right(); else ins_right(); break; case K_S_RIGHT: /* <S-Right> */ case K_C_RIGHT: ins_s_right(); break; case K_UP: /* <Up> */ #ifdef FEAT_INS_EXPAND if (pum_visible()) goto docomplete; #endif if (mod_mask & MOD_MASK_SHIFT) ins_pageup(); else ins_up(FALSE); break; case K_S_UP: /* <S-Up> */ case K_PAGEUP: case K_KPAGEUP: #ifdef FEAT_INS_EXPAND if (pum_visible()) goto docomplete; #endif ins_pageup(); break; case K_DOWN: /* <Down> */ #ifdef FEAT_INS_EXPAND if (pum_visible()) goto docomplete; #endif if (mod_mask & MOD_MASK_SHIFT) ins_pagedown(); else ins_down(FALSE); break; case K_S_DOWN: /* <S-Down> */ case K_PAGEDOWN: case K_KPAGEDOWN: #ifdef FEAT_INS_EXPAND if (pum_visible()) goto docomplete; #endif ins_pagedown(); break; #ifdef FEAT_DND case K_DROP: /* drag-n-drop event */ ins_drop(); break; #endif case K_S_TAB: /* When not mapped, use like a normal TAB */ c = TAB; /* FALLTHROUGH */ case TAB: /* TAB or Complete patterns along path */ #if defined(FEAT_INS_EXPAND) && defined(FEAT_FIND_ID) if (ctrl_x_mode == CTRL_X_PATH_PATTERNS) goto docomplete; #endif inserted_space = FALSE; if (ins_tab()) goto normalchar; /* insert TAB as a normal char */ auto_format(FALSE, TRUE); break; case K_KENTER: /* <Enter> */ c = CAR; /* FALLTHROUGH */ case CAR: case NL: #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX) /* In a quickfix window a <CR> jumps to the error under the * cursor. */ if (bt_quickfix(curbuf) && c == CAR) { if (curwin->w_llist_ref == NULL) /* quickfix window */ do_cmdline_cmd((char_u *)".cc"); else /* location list window */ do_cmdline_cmd((char_u *)".ll"); break; } #endif #ifdef FEAT_CMDWIN if (cmdwin_type != 0) { /* Execute the command in the cmdline window. */ cmdwin_result = CAR; goto doESCkey; } #endif if (ins_eol(c) && !p_im) goto doESCkey; /* out of memory */ auto_format(FALSE, FALSE); inserted_space = FALSE; break; #if defined(FEAT_DIGRAPHS) || defined(FEAT_INS_EXPAND) case Ctrl_K: /* digraph or keyword completion */ # ifdef FEAT_INS_EXPAND if (ctrl_x_mode == CTRL_X_DICTIONARY) { if (has_compl_option(TRUE)) goto docomplete; break; } # endif # ifdef FEAT_DIGRAPHS c = ins_digraph(); if (c == NUL) break; # endif goto normalchar; #endif #ifdef FEAT_INS_EXPAND case Ctrl_X: /* Enter CTRL-X mode */ ins_ctrl_x(); break; case Ctrl_RSB: /* Tag name completion after ^X */ if (ctrl_x_mode != CTRL_X_TAGS) goto normalchar; goto docomplete; case Ctrl_F: /* File name completion after ^X */ if (ctrl_x_mode != CTRL_X_FILES) goto normalchar; goto docomplete; case 's': /* Spelling completion after ^X */ case Ctrl_S: if (ctrl_x_mode != CTRL_X_SPELL) goto normalchar; goto docomplete; #endif case Ctrl_L: /* Whole line completion after ^X */ #ifdef FEAT_INS_EXPAND if (ctrl_x_mode != CTRL_X_WHOLE_LINE) #endif { /* CTRL-L with 'insertmode' set: Leave Insert mode */ if (p_im) { if (echeck_abbr(Ctrl_L + ABBR_OFF)) break; goto doESCkey; } goto normalchar; } #ifdef FEAT_INS_EXPAND /* FALLTHROUGH */ case Ctrl_P: /* Do previous/next pattern completion */ case Ctrl_N: /* if 'complete' is empty then plain ^P is no longer special, * but it is under other ^X modes */ if (*curbuf->b_p_cpt == NUL && ctrl_x_mode != 0 && !(compl_cont_status & CONT_LOCAL)) goto normalchar; docomplete: compl_busy = TRUE; if (ins_complete(c) == FAIL) compl_cont_status = 0; compl_busy = FALSE; break; #endif /* FEAT_INS_EXPAND */ case Ctrl_Y: /* copy from previous line or scroll down */ case Ctrl_E: /* copy from next line or scroll up */ c = ins_ctrl_ey(c); break; default: #ifdef UNIX if (c == intr_char) /* special interrupt char */ goto do_intr; #endif normalchar: /* * Insert a nomal character. */ #ifdef FEAT_AUTOCMD if (!p_paste) { /* Trigger InsertCharPre. */ char_u *str = do_insert_char_pre(c); char_u *p; if (str != NULL) { if (*str != NUL && stop_arrow() != FAIL) { /* Insert the new value of v:char literally. */ for (p = str; *p != NUL; mb_ptr_adv(p)) { c = PTR2CHAR(p); if (c == CAR || c == K_KENTER || c == NL) ins_eol(c); else ins_char(c); } AppendToRedobuffLit(str, -1); } vim_free(str); c = NUL; } /* If the new value is already inserted or an empty string * then don't insert any character. */ if (c == NUL) break; } #endif #ifdef FEAT_SMARTINDENT /* Try to perform smart-indenting. */ ins_try_si(c); #endif if (c == ' ') { inserted_space = TRUE; #ifdef FEAT_CINDENT if (inindent(0)) can_cindent = FALSE; #endif if (Insstart_blank_vcol == MAXCOL && curwin->w_cursor.lnum == Insstart.lnum) Insstart_blank_vcol = get_nolist_virtcol(); } /* Insert a normal character and check for abbreviations on a * special character. Let CTRL-] expand abbreviations without * inserting it. */ if (vim_iswordc(c) || (!echeck_abbr( #ifdef FEAT_MBYTE /* Add ABBR_OFF for characters above 0x100, this is * what check_abbr() expects. */ (has_mbyte && c >= 0x100) ? (c + ABBR_OFF) : #endif c) && c != Ctrl_RSB)) { insert_special(c, FALSE, FALSE); #ifdef FEAT_RIGHTLEFT revins_legal++; revins_chars++; #endif } auto_format(FALSE, TRUE); #ifdef FEAT_FOLDING /* When inserting a character the cursor line must never be in a * closed fold. */ foldOpenCursor(); #endif break; } /* end of switch (c) */ #ifdef FEAT_AUTOCMD /* If typed something may trigger CursorHoldI again. */ if (c != K_CURSORHOLD) did_cursorhold = FALSE; #endif /* If the cursor was moved we didn't just insert a space */ if (arrow_used) inserted_space = FALSE; #ifdef FEAT_CINDENT if (can_cindent && cindent_on() # ifdef FEAT_INS_EXPAND && ctrl_x_mode == 0 # endif ) { force_cindent: /* * Indent now if a key was typed that is in 'cinkeys'. */ if (in_cinkeys(c, ' ', line_is_white)) { if (stop_arrow() == OK) /* re-indent the current line */ do_c_expr_indent(); } } #endif /* FEAT_CINDENT */ } /* for (;;) */ /* NOTREACHED */ } /* * Redraw for Insert mode. * This is postponed until getting the next character to make '$' in the 'cpo' * option work correctly. * Only redraw when there are no characters available. This speeds up * inserting sequences of characters (e.g., for CTRL-R). */ static void ins_redraw(ready) int ready UNUSED; /* not busy with something */ { #ifdef FEAT_CONCEAL linenr_T conceal_old_cursor_line = 0; linenr_T conceal_new_cursor_line = 0; int conceal_update_lines = FALSE; #endif if (!char_avail()) { #if defined(FEAT_AUTOCMD) || defined(FEAT_CONCEAL) /* Trigger CursorMoved if the cursor moved. Not when the popup menu is * visible, the command might delete it. */ if (ready && ( # ifdef FEAT_AUTOCMD has_cursormovedI() # endif # if defined(FEAT_AUTOCMD) && defined(FEAT_CONCEAL) || # endif # ifdef FEAT_CONCEAL curwin->w_p_cole > 0 # endif ) && !equalpos(last_cursormoved, curwin->w_cursor) # ifdef FEAT_INS_EXPAND && !pum_visible() # endif ) { # ifdef FEAT_SYN_HL /* Need to update the screen first, to make sure syntax * highlighting is correct after making a change (e.g., inserting * a "(". The autocommand may also require a redraw, so it's done * again below, unfortunately. */ if (syntax_present(curwin) && must_redraw) update_screen(0); # endif # ifdef FEAT_AUTOCMD if (has_cursormovedI()) apply_autocmds(EVENT_CURSORMOVEDI, NULL, NULL, FALSE, curbuf); # endif # ifdef FEAT_CONCEAL if (curwin->w_p_cole > 0) { conceal_old_cursor_line = last_cursormoved.lnum; conceal_new_cursor_line = curwin->w_cursor.lnum; conceal_update_lines = TRUE; } # endif last_cursormoved = curwin->w_cursor; } #endif if (must_redraw) update_screen(0); else if (clear_cmdline || redraw_cmdline) showmode(); /* clear cmdline and show mode */ # if defined(FEAT_CONCEAL) if ((conceal_update_lines && (conceal_old_cursor_line != conceal_new_cursor_line || conceal_cursor_line(curwin))) || need_cursor_line_redraw) { if (conceal_old_cursor_line != conceal_new_cursor_line) update_single_line(curwin, conceal_old_cursor_line); update_single_line(curwin, conceal_new_cursor_line == 0 ? curwin->w_cursor.lnum : conceal_new_cursor_line); curwin->w_valid &= ~VALID_CROW; } # endif showruler(FALSE); setcursor(); emsg_on_display = FALSE; /* may remove error message now */ } } /* * Handle a CTRL-V or CTRL-Q typed in Insert mode. */ static void ins_ctrl_v() { int c; int did_putchar = FALSE; /* may need to redraw when no more chars available now */ ins_redraw(FALSE); if (redrawing() && !char_avail()) { edit_putchar('^', TRUE); did_putchar = TRUE; } AppendToRedobuff((char_u *)CTRL_V_STR); /* CTRL-V */ #ifdef FEAT_CMDL_INFO add_to_showcmd_c(Ctrl_V); #endif c = get_literal(); if (did_putchar) /* when the line fits in 'columns' the '^' is at the start of the next * line and will not removed by the redraw */ edit_unputchar(); #ifdef FEAT_CMDL_INFO clear_showcmd(); #endif insert_special(c, FALSE, TRUE); #ifdef FEAT_RIGHTLEFT revins_chars++; revins_legal++; #endif } /* * Put a character directly onto the screen. It's not stored in a buffer. * Used while handling CTRL-K, CTRL-V, etc. in Insert mode. */ static int pc_status; #define PC_STATUS_UNSET 0 /* pc_bytes was not set */ #define PC_STATUS_RIGHT 1 /* right halve of double-wide char */ #define PC_STATUS_LEFT 2 /* left halve of double-wide char */ #define PC_STATUS_SET 3 /* pc_bytes was filled */ static char_u pc_bytes[MB_MAXBYTES + 1]; /* saved bytes */ static int pc_attr; static int pc_row; static int pc_col; void edit_putchar(c, highlight) int c; int highlight; { int attr; if (ScreenLines != NULL) { update_topline(); /* just in case w_topline isn't valid */ validate_cursor(); if (highlight) attr = hl_attr(HLF_8); else attr = 0; pc_row = W_WINROW(curwin) + curwin->w_wrow; pc_col = W_WINCOL(curwin); #if defined(FEAT_RIGHTLEFT) || defined(FEAT_MBYTE) pc_status = PC_STATUS_UNSET; #endif #ifdef FEAT_RIGHTLEFT if (curwin->w_p_rl) { pc_col += W_WIDTH(curwin) - 1 - curwin->w_wcol; # ifdef FEAT_MBYTE if (has_mbyte) { int fix_col = mb_fix_col(pc_col, pc_row); if (fix_col != pc_col) { screen_putchar(' ', pc_row, fix_col, attr); --curwin->w_wcol; pc_status = PC_STATUS_RIGHT; } } # endif } else #endif { pc_col += curwin->w_wcol; #ifdef FEAT_MBYTE if (mb_lefthalve(pc_row, pc_col)) pc_status = PC_STATUS_LEFT; #endif } /* save the character to be able to put it back */ #if defined(FEAT_RIGHTLEFT) || defined(FEAT_MBYTE) if (pc_status == PC_STATUS_UNSET) #endif { screen_getbytes(pc_row, pc_col, pc_bytes, &pc_attr); pc_status = PC_STATUS_SET; } screen_putchar(c, pc_row, pc_col, attr); } } /* * Undo the previous edit_putchar(). */ void edit_unputchar() { if (pc_status != PC_STATUS_UNSET && pc_row >= msg_scrolled) { #if defined(FEAT_MBYTE) if (pc_status == PC_STATUS_RIGHT) ++curwin->w_wcol; if (pc_status == PC_STATUS_RIGHT || pc_status == PC_STATUS_LEFT) redrawWinline(curwin->w_cursor.lnum, FALSE); else #endif screen_puts(pc_bytes, pc_row - msg_scrolled, pc_col, pc_attr); } } /* * Called when p_dollar is set: display a '$' at the end of the changed text * Only works when cursor is in the line that changes. */ void display_dollar(col) colnr_T col; { colnr_T save_col; if (!redrawing()) return; cursor_off(); save_col = curwin->w_cursor.col; curwin->w_cursor.col = col; #ifdef FEAT_MBYTE if (has_mbyte) { char_u *p; /* If on the last byte of a multi-byte move to the first byte. */ p = ml_get_curline(); curwin->w_cursor.col -= (*mb_head_off)(p, p + col); } #endif curs_columns(FALSE); /* recompute w_wrow and w_wcol */ if (curwin->w_wcol < W_WIDTH(curwin)) { edit_putchar('$', FALSE); dollar_vcol = curwin->w_virtcol; } curwin->w_cursor.col = save_col; } /* * Call this function before moving the cursor from the normal insert position * in insert mode. */ static void undisplay_dollar() { if (dollar_vcol >= 0) { dollar_vcol = -1; redrawWinline(curwin->w_cursor.lnum, FALSE); } } /* * Insert an indent (for <Tab> or CTRL-T) or delete an indent (for CTRL-D). * Keep the cursor on the same character. * type == INDENT_INC increase indent (for CTRL-T or <Tab>) * type == INDENT_DEC decrease indent (for CTRL-D) * type == INDENT_SET set indent to "amount" * if round is TRUE, round the indent to 'shiftwidth' (only with _INC and _Dec). */ void change_indent(type, amount, round, replaced, call_changed_bytes) int type; int amount; int round; int replaced; /* replaced character, put on replace stack */ int call_changed_bytes; /* call changed_bytes() */ { int vcol; int last_vcol; int insstart_less; /* reduction for Insstart.col */ int new_cursor_col; int i; char_u *ptr; int save_p_list; int start_col; colnr_T vc; #ifdef FEAT_VREPLACE colnr_T orig_col = 0; /* init for GCC */ char_u *new_line, *orig_line = NULL; /* init for GCC */ /* VREPLACE mode needs to know what the line was like before changing */ if (State & VREPLACE_FLAG) { orig_line = vim_strsave(ml_get_curline()); /* Deal with NULL below */ orig_col = curwin->w_cursor.col; } #endif /* for the following tricks we don't want list mode */ save_p_list = curwin->w_p_list; curwin->w_p_list = FALSE; vc = getvcol_nolist(&curwin->w_cursor); vcol = vc; /* * For Replace mode we need to fix the replace stack later, which is only * possible when the cursor is in the indent. Remember the number of * characters before the cursor if it's possible. */ start_col = curwin->w_cursor.col; /* determine offset from first non-blank */ new_cursor_col = curwin->w_cursor.col; beginline(BL_WHITE); new_cursor_col -= curwin->w_cursor.col; insstart_less = curwin->w_cursor.col; /* * If the cursor is in the indent, compute how many screen columns the * cursor is to the left of the first non-blank. */ if (new_cursor_col < 0) vcol = get_indent() - vcol; if (new_cursor_col > 0) /* can't fix replace stack */ start_col = -1; /* * Set the new indent. The cursor will be put on the first non-blank. */ if (type == INDENT_SET) (void)set_indent(amount, call_changed_bytes ? SIN_CHANGED : 0); else { #ifdef FEAT_VREPLACE int save_State = State; /* Avoid being called recursively. */ if (State & VREPLACE_FLAG) State = INSERT; #endif shift_line(type == INDENT_DEC, round, 1, call_changed_bytes); #ifdef FEAT_VREPLACE State = save_State; #endif } insstart_less -= curwin->w_cursor.col; /* * Try to put cursor on same character. * If the cursor is at or after the first non-blank in the line, * compute the cursor column relative to the column of the first * non-blank character. * If we are not in insert mode, leave the cursor on the first non-blank. * If the cursor is before the first non-blank, position it relative * to the first non-blank, counted in screen columns. */ if (new_cursor_col >= 0) { /* * When changing the indent while the cursor is touching it, reset * Insstart_col to 0. */ if (new_cursor_col == 0) insstart_less = MAXCOL; new_cursor_col += curwin->w_cursor.col; } else if (!(State & INSERT)) new_cursor_col = curwin->w_cursor.col; else { /* * Compute the screen column where the cursor should be. */ vcol = get_indent() - vcol; curwin->w_virtcol = (colnr_T)((vcol < 0) ? 0 : vcol); /* * Advance the cursor until we reach the right screen column. */ vcol = last_vcol = 0; new_cursor_col = -1; ptr = ml_get_curline(); while (vcol <= (int)curwin->w_virtcol) { last_vcol = vcol; #ifdef FEAT_MBYTE if (has_mbyte && new_cursor_col >= 0) new_cursor_col += (*mb_ptr2len)(ptr + new_cursor_col); else #endif ++new_cursor_col; vcol += lbr_chartabsize(ptr + new_cursor_col, (colnr_T)vcol); } vcol = last_vcol; /* * May need to insert spaces to be able to position the cursor on * the right screen column. */ if (vcol != (int)curwin->w_virtcol) { curwin->w_cursor.col = (colnr_T)new_cursor_col; i = (int)curwin->w_virtcol - vcol; ptr = alloc((unsigned)(i + 1)); if (ptr != NULL) { new_cursor_col += i; ptr[i] = NUL; while (--i >= 0) ptr[i] = ' '; ins_str(ptr); vim_free(ptr); } } /* * When changing the indent while the cursor is in it, reset * Insstart_col to 0. */ insstart_less = MAXCOL; } curwin->w_p_list = save_p_list; if (new_cursor_col <= 0) curwin->w_cursor.col = 0; else curwin->w_cursor.col = (colnr_T)new_cursor_col; curwin->w_set_curswant = TRUE; changed_cline_bef_curs(); /* * May have to adjust the start of the insert. */ if (State & INSERT) { if (curwin->w_cursor.lnum == Insstart.lnum && Insstart.col != 0) { if ((int)Insstart.col <= insstart_less) Insstart.col = 0; else Insstart.col -= insstart_less; } if ((int)ai_col <= insstart_less) ai_col = 0; else ai_col -= insstart_less; } /* * For REPLACE mode, may have to fix the replace stack, if it's possible. * If the number of characters before the cursor decreased, need to pop a * few characters from the replace stack. * If the number of characters before the cursor increased, need to push a * few NULs onto the replace stack. */ if (REPLACE_NORMAL(State) && start_col >= 0) { while (start_col > (int)curwin->w_cursor.col) { replace_join(0); /* remove a NUL from the replace stack */ --start_col; } while (start_col < (int)curwin->w_cursor.col || replaced) { replace_push(NUL); if (replaced) { replace_push(replaced); replaced = NUL; } ++start_col; } } #ifdef FEAT_VREPLACE /* * For VREPLACE mode, we also have to fix the replace stack. In this case * it is always possible because we backspace over the whole line and then * put it back again the way we wanted it. */ if (State & VREPLACE_FLAG) { /* If orig_line didn't allocate, just return. At least we did the job, * even if you can't backspace. */ if (orig_line == NULL) return; /* Save new line */ new_line = vim_strsave(ml_get_curline()); if (new_line == NULL) return; /* We only put back the new line up to the cursor */ new_line[curwin->w_cursor.col] = NUL; /* Put back original line */ ml_replace(curwin->w_cursor.lnum, orig_line, FALSE); curwin->w_cursor.col = orig_col; /* Backspace from cursor to start of line */ backspace_until_column(0); /* Insert new stuff into line again */ ins_bytes(new_line); vim_free(new_line); } #endif } /* * Truncate the space at the end of a line. This is to be used only in an * insert mode. It handles fixing the replace stack for REPLACE and VREPLACE * modes. */ void truncate_spaces(line) char_u *line; { int i; /* find start of trailing white space */ for (i = (int)STRLEN(line) - 1; i >= 0 && vim_iswhite(line[i]); i--) { if (State & REPLACE_FLAG) replace_join(0); /* remove a NUL from the replace stack */ } line[i + 1] = NUL; } #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \ || defined(FEAT_COMMENTS) || defined(PROTO) /* * Backspace the cursor until the given column. Handles REPLACE and VREPLACE * modes correctly. May also be used when not in insert mode at all. * Will attempt not to go before "col" even when there is a composing * character. */ void backspace_until_column(col) int col; { while ((int)curwin->w_cursor.col > col) { curwin->w_cursor.col--; if (State & REPLACE_FLAG) replace_do_bs(col); else if (!del_char_after_col(col)) break; } } #endif /* * Like del_char(), but make sure not to go before column "limit_col". * Only matters when there are composing characters. * Return TRUE when something was deleted. */ static int del_char_after_col(limit_col) int limit_col UNUSED; { #ifdef FEAT_MBYTE if (enc_utf8 && limit_col >= 0) { colnr_T ecol = curwin->w_cursor.col + 1; /* Make sure the cursor is at the start of a character, but * skip forward again when going too far back because of a * composing character. */ mb_adjust_cursor(); while (curwin->w_cursor.col < (colnr_T)limit_col) { int l = utf_ptr2len(ml_get_cursor()); if (l == 0) /* end of line */ break; curwin->w_cursor.col += l; } if (*ml_get_cursor() == NUL || curwin->w_cursor.col == ecol) return FALSE; del_bytes((long)((int)ecol - curwin->w_cursor.col), FALSE, TRUE); } else #endif (void)del_char(FALSE); return TRUE; } #if defined(FEAT_INS_EXPAND) || defined(PROTO) /* * CTRL-X pressed in Insert mode. */ static void ins_ctrl_x() { /* CTRL-X after CTRL-X CTRL-V doesn't do anything, so that CTRL-X * CTRL-V works like CTRL-N */ if (ctrl_x_mode != CTRL_X_CMDLINE) { /* if the next ^X<> won't ADD nothing, then reset * compl_cont_status */ if (compl_cont_status & CONT_N_ADDS) compl_cont_status |= CONT_INTRPT; else compl_cont_status = 0; /* We're not sure which CTRL-X mode it will be yet */ ctrl_x_mode = CTRL_X_NOT_DEFINED_YET; edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode)); edit_submode_pre = NULL; showmode(); } } /* * Return TRUE if the 'dict' or 'tsr' option can be used. */ static int has_compl_option(dict_opt) int dict_opt; { if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL # ifdef FEAT_SPELL && !curwin->w_p_spell # endif ) : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL)) { ctrl_x_mode = 0; edit_submode = NULL; msg_attr(dict_opt ? (char_u *)_("'dictionary' option is empty") : (char_u *)_("'thesaurus' option is empty"), hl_attr(HLF_E)); if (emsg_silent == 0) { vim_beep(); setcursor(); out_flush(); ui_delay(2000L, FALSE); } return FALSE; } return TRUE; } /* * Is the character 'c' a valid key to go to or keep us in CTRL-X mode? * This depends on the current mode. */ int vim_is_ctrl_x_key(c) int c; { /* Always allow ^R - let it's results then be checked */ if (c == Ctrl_R) return TRUE; /* Accept <PageUp> and <PageDown> if the popup menu is visible. */ if (ins_compl_pum_key(c)) return TRUE; switch (ctrl_x_mode) { case 0: /* Not in any CTRL-X mode */ return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X); case CTRL_X_NOT_DEFINED_YET: return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O || c == Ctrl_S || c == Ctrl_K || c == 's'); case CTRL_X_SCROLL: return (c == Ctrl_Y || c == Ctrl_E); case CTRL_X_WHOLE_LINE: return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N); case CTRL_X_FILES: return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N); case CTRL_X_DICTIONARY: return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N); case CTRL_X_THESAURUS: return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N); case CTRL_X_TAGS: return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N); #ifdef FEAT_FIND_ID case CTRL_X_PATH_PATTERNS: return (c == Ctrl_P || c == Ctrl_N); case CTRL_X_PATH_DEFINES: return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N); #endif case CTRL_X_CMDLINE: return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N || c == Ctrl_X); #ifdef FEAT_COMPL_FUNC case CTRL_X_FUNCTION: return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N); case CTRL_X_OMNI: return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N); #endif case CTRL_X_SPELL: return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N); } EMSG(_(e_internal)); return FALSE; } /* * Return TRUE when character "c" is part of the item currently being * completed. Used to decide whether to abandon complete mode when the menu * is visible. */ static int ins_compl_accept_char(c) int c; { if (ctrl_x_mode & CTRL_X_WANT_IDENT) /* When expanding an identifier only accept identifier chars. */ return vim_isIDc(c); switch (ctrl_x_mode) { case CTRL_X_FILES: /* When expanding file name only accept file name chars. But not * path separators, so that "proto/<Tab>" expands files in * "proto", not "proto/" as a whole */ return vim_isfilec(c) && !vim_ispathsep(c); case CTRL_X_CMDLINE: case CTRL_X_OMNI: /* Command line and Omni completion can work with just about any * printable character, but do stop at white space. */ return vim_isprintc(c) && !vim_iswhite(c); case CTRL_X_WHOLE_LINE: /* For while line completion a space can be part of the line. */ return vim_isprintc(c); } return vim_iswordc(c); } /* * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the * case of the originally typed text is used, and the case of the completed * text is inferred, ie this tries to work out what case you probably wanted * the rest of the word to be in -- webb */ int ins_compl_add_infercase(str, len, icase, fname, dir, flags) char_u *str; int len; int icase; char_u *fname; int dir; int flags; { char_u *p; int i, c; int actual_len; /* Take multi-byte characters */ int actual_compl_length; /* into account. */ int min_len; int *wca; /* Wide character array. */ int has_lower = FALSE; int was_letter = FALSE; if (p_ic && curbuf->b_p_inf && len > 0) { /* Infer case of completed part. */ /* Find actual length of completion. */ #ifdef FEAT_MBYTE if (has_mbyte) { p = str; actual_len = 0; while (*p != NUL) { mb_ptr_adv(p); ++actual_len; } } else #endif actual_len = len; /* Find actual length of original text. */ #ifdef FEAT_MBYTE if (has_mbyte) { p = compl_orig_text; actual_compl_length = 0; while (*p != NUL) { mb_ptr_adv(p); ++actual_compl_length; } } else #endif actual_compl_length = compl_length; /* "actual_len" may be smaller than "actual_compl_length" when using * thesaurus, only use the minimum when comparing. */ min_len = actual_len < actual_compl_length ? actual_len : actual_compl_length; /* Allocate wide character array for the completion and fill it. */ wca = (int *)alloc((unsigned)(actual_len * sizeof(int))); if (wca != NULL) { p = str; for (i = 0; i < actual_len; ++i) #ifdef FEAT_MBYTE if (has_mbyte) wca[i] = mb_ptr2char_adv(&p); else #endif wca[i] = *(p++); /* Rule 1: Were any chars converted to lower? */ p = compl_orig_text; for (i = 0; i < min_len; ++i) { #ifdef FEAT_MBYTE if (has_mbyte) c = mb_ptr2char_adv(&p); else #endif c = *(p++); if (MB_ISLOWER(c)) { has_lower = TRUE; if (MB_ISUPPER(wca[i])) { /* Rule 1 is satisfied. */ for (i = actual_compl_length; i < actual_len; ++i) wca[i] = MB_TOLOWER(wca[i]); break; } } } /* * Rule 2: No lower case, 2nd consecutive letter converted to * upper case. */ if (!has_lower) { p = compl_orig_text; for (i = 0; i < min_len; ++i) { #ifdef FEAT_MBYTE if (has_mbyte) c = mb_ptr2char_adv(&p); else #endif c = *(p++); if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i])) { /* Rule 2 is satisfied. */ for (i = actual_compl_length; i < actual_len; ++i) wca[i] = MB_TOUPPER(wca[i]); break; } was_letter = MB_ISLOWER(c) || MB_ISUPPER(c); } } /* Copy the original case of the part we typed. */ p = compl_orig_text; for (i = 0; i < min_len; ++i) { #ifdef FEAT_MBYTE if (has_mbyte) c = mb_ptr2char_adv(&p); else #endif c = *(p++); if (MB_ISLOWER(c)) wca[i] = MB_TOLOWER(wca[i]); else if (MB_ISUPPER(c)) wca[i] = MB_TOUPPER(wca[i]); } /* * Generate encoding specific output from wide character array. * Multi-byte characters can occupy up to five bytes more than * ASCII characters, and we also need one byte for NUL, so stay * six bytes away from the edge of IObuff. */ p = IObuff; i = 0; while (i < actual_len && (p - IObuff + 6) < IOSIZE) #ifdef FEAT_MBYTE if (has_mbyte) p += (*mb_char2bytes)(wca[i++], p); else #endif *(p++) = wca[i++]; *p = NUL; vim_free(wca); } return ins_compl_add(IObuff, len, icase, fname, NULL, dir, flags, FALSE); } return ins_compl_add(str, len, icase, fname, NULL, dir, flags, FALSE); } /* * Add a match to the list of matches. * If the given string is already in the list of completions, then return * NOTDONE, otherwise add it to the list and return OK. If there is an error, * maybe because alloc() returns NULL, then FAIL is returned. */ static int ins_compl_add(str, len, icase, fname, cptext, cdir, flags, adup) char_u *str; int len; int icase; char_u *fname; char_u **cptext; /* extra text for popup menu or NULL */ int cdir; int flags; int adup; /* accept duplicate match */ { compl_T *match; int dir = (cdir == 0 ? compl_direction : cdir); ui_breakcheck(); if (got_int) return FAIL; if (len < 0) len = (int)STRLEN(str); /* * If the same match is already present, don't add it. */ if (compl_first_match != NULL && !adup) { match = compl_first_match; do { if ( !(match->cp_flags & ORIGINAL_TEXT) && STRNCMP(match->cp_str, str, len) == 0 && match->cp_str[len] == NUL) return NOTDONE; match = match->cp_next; } while (match != NULL && match != compl_first_match); } /* Remove any popup menu before changing the list of matches. */ ins_compl_del_pum(); /* * Allocate a new match structure. * Copy the values to the new match structure. */ match = (compl_T *)alloc_clear((unsigned)sizeof(compl_T)); if (match == NULL) return FAIL; match->cp_number = -1; if (flags & ORIGINAL_TEXT) match->cp_number = 0; if ((match->cp_str = vim_strnsave(str, len)) == NULL) { vim_free(match); return FAIL; } match->cp_icase = icase; /* match-fname is: * - compl_curr_match->cp_fname if it is a string equal to fname. * - a copy of fname, FREE_FNAME is set to free later THE allocated mem. * - NULL otherwise. --Acevedo */ if (fname != NULL && compl_curr_match != NULL && compl_curr_match->cp_fname != NULL && STRCMP(fname, compl_curr_match->cp_fname) == 0) match->cp_fname = compl_curr_match->cp_fname; else if (fname != NULL) { match->cp_fname = vim_strsave(fname); flags |= FREE_FNAME; } else match->cp_fname = NULL; match->cp_flags = flags; if (cptext != NULL) { int i; for (i = 0; i < CPT_COUNT; ++i) if (cptext[i] != NULL && *cptext[i] != NUL) match->cp_text[i] = vim_strsave(cptext[i]); } /* * Link the new match structure in the list of matches. */ if (compl_first_match == NULL) match->cp_next = match->cp_prev = NULL; else if (dir == FORWARD) { match->cp_next = compl_curr_match->cp_next; match->cp_prev = compl_curr_match; } else /* BACKWARD */ { match->cp_next = compl_curr_match; match->cp_prev = compl_curr_match->cp_prev; } if (match->cp_next) match->cp_next->cp_prev = match; if (match->cp_prev) match->cp_prev->cp_next = match; else /* if there's nothing before, it is the first match */ compl_first_match = match; compl_curr_match = match; /* * Find the longest common string if still doing that. */ if (compl_get_longest && (flags & ORIGINAL_TEXT) == 0) ins_compl_longest_match(match); return OK; } /* * Return TRUE if "str[len]" matches with match->cp_str, considering * match->cp_icase. */ static int ins_compl_equal(match, str, len) compl_T *match; char_u *str; int len; { if (match->cp_icase) return STRNICMP(match->cp_str, str, (size_t)len) == 0; return STRNCMP(match->cp_str, str, (size_t)len) == 0; } /* * Reduce the longest common string for match "match". */ static void ins_compl_longest_match(match) compl_T *match; { char_u *p, *s; int c1, c2; int had_match; if (compl_leader == NULL) { /* First match, use it as a whole. */ compl_leader = vim_strsave(match->cp_str); if (compl_leader != NULL) { had_match = (curwin->w_cursor.col > compl_col); ins_compl_delete(); ins_bytes(compl_leader + ins_compl_len()); ins_redraw(FALSE); /* When the match isn't there (to avoid matching itself) remove it * again after redrawing. */ if (!had_match) ins_compl_delete(); compl_used_match = FALSE; } } else { /* Reduce the text if this match differs from compl_leader. */ p = compl_leader; s = match->cp_str; while (*p != NUL) { #ifdef FEAT_MBYTE if (has_mbyte) { c1 = mb_ptr2char(p); c2 = mb_ptr2char(s); } else #endif { c1 = *p; c2 = *s; } if (match->cp_icase ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2)) break; #ifdef FEAT_MBYTE if (has_mbyte) { mb_ptr_adv(p); mb_ptr_adv(s); } else #endif { ++p; ++s; } } if (*p != NUL) { /* Leader was shortened, need to change the inserted text. */ *p = NUL; had_match = (curwin->w_cursor.col > compl_col); ins_compl_delete(); ins_bytes(compl_leader + ins_compl_len()); ins_redraw(FALSE); /* When the match isn't there (to avoid matching itself) remove it * again after redrawing. */ if (!had_match) ins_compl_delete(); } compl_used_match = FALSE; } } /* * Add an array of matches to the list of matches. * Frees matches[]. */ static void ins_compl_add_matches(num_matches, matches, icase) int num_matches; char_u **matches; int icase; { int i; int add_r = OK; int dir = compl_direction; for (i = 0; i < num_matches && add_r != FAIL; i++) if ((add_r = ins_compl_add(matches[i], -1, icase, NULL, NULL, dir, 0, FALSE)) == OK) /* if dir was BACKWARD then honor it just once */ dir = FORWARD; FreeWild(num_matches, matches); } /* Make the completion list cyclic. * Return the number of matches (excluding the original). */ static int ins_compl_make_cyclic() { compl_T *match; int count = 0; if (compl_first_match != NULL) { /* * Find the end of the list. */ match = compl_first_match; /* there's always an entry for the compl_orig_text, it doesn't count. */ while (match->cp_next != NULL && match->cp_next != compl_first_match) { match = match->cp_next; ++count; } match->cp_next = compl_first_match; compl_first_match->cp_prev = match; } return count; } /* * Start completion for the complete() function. * "startcol" is where the matched text starts (1 is first column). * "list" is the list of matches. */ void set_completion(startcol, list) colnr_T startcol; list_T *list; { /* If already doing completions stop it. */ if (ctrl_x_mode != 0) ins_compl_prep(' '); ins_compl_clear(); if (stop_arrow() == FAIL) return; compl_direction = FORWARD; if (startcol > curwin->w_cursor.col) startcol = curwin->w_cursor.col; compl_col = startcol; compl_length = (int)curwin->w_cursor.col - (int)startcol; /* compl_pattern doesn't need to be set */ compl_orig_text = vim_strnsave(ml_get_curline() + compl_col, compl_length); if (compl_orig_text == NULL || ins_compl_add(compl_orig_text, -1, p_ic, NULL, NULL, 0, ORIGINAL_TEXT, FALSE) != OK) return; /* Handle like dictionary completion. */ ctrl_x_mode = CTRL_X_WHOLE_LINE; ins_compl_add_list(list); compl_matches = ins_compl_make_cyclic(); compl_started = TRUE; compl_used_match = TRUE; compl_cont_status = 0; compl_curr_match = compl_first_match; ins_complete(Ctrl_N); out_flush(); } /* "compl_match_array" points the currently displayed list of entries in the * popup menu. It is NULL when there is no popup menu. */ static pumitem_T *compl_match_array = NULL; static int compl_match_arraysize; /* * Update the screen and when there is any scrolling remove the popup menu. */ static void ins_compl_upd_pum() { int h; if (compl_match_array != NULL) { h = curwin->w_cline_height; update_screen(0); if (h != curwin->w_cline_height) ins_compl_del_pum(); } } /* * Remove any popup menu. */ static void ins_compl_del_pum() { if (compl_match_array != NULL) { pum_undisplay(); vim_free(compl_match_array); compl_match_array = NULL; } } /* * Return TRUE if the popup menu should be displayed. */ static int pum_wanted() { /* 'completeopt' must contain "menu" or "menuone" */ if (vim_strchr(p_cot, 'm') == NULL) return FALSE; /* The display looks bad on a B&W display. */ if (t_colors < 8 #ifdef FEAT_GUI && !gui.in_use #endif ) return FALSE; return TRUE; } /* * Return TRUE if there are two or more matches to be shown in the popup menu. * One if 'completopt' contains "menuone". */ static int pum_enough_matches() { compl_T *compl; int i; /* Don't display the popup menu if there are no matches or there is only * one (ignoring the original text). */ compl = compl_first_match; i = 0; do { if (compl == NULL || ((compl->cp_flags & ORIGINAL_TEXT) == 0 && ++i == 2)) break; compl = compl->cp_next; } while (compl != compl_first_match); if (strstr((char *)p_cot, "menuone") != NULL) return (i >= 1); return (i >= 2); } /* * Show the popup menu for the list of matches. * Also adjusts "compl_shown_match" to an entry that is actually displayed. */ void ins_compl_show_pum() { compl_T *compl; compl_T *shown_compl = NULL; int did_find_shown_match = FALSE; int shown_match_ok = FALSE; int i; int cur = -1; colnr_T col; int lead_len = 0; if (!pum_wanted() || !pum_enough_matches()) return; #if defined(FEAT_EVAL) /* Dirty hard-coded hack: remove any matchparen highlighting. */ do_cmdline_cmd((char_u *)"if exists('g:loaded_matchparen')|3match none|endif"); #endif /* Update the screen before drawing the popup menu over it. */ update_screen(0); if (compl_match_array == NULL) { /* Need to build the popup menu list. */ compl_match_arraysize = 0; compl = compl_first_match; if (compl_leader != NULL) lead_len = (int)STRLEN(compl_leader); do { if ((compl->cp_flags & ORIGINAL_TEXT) == 0 && (compl_leader == NULL || ins_compl_equal(compl, compl_leader, lead_len))) ++compl_match_arraysize; compl = compl->cp_next; } while (compl != NULL && compl != compl_first_match); if (compl_match_arraysize == 0) return; compl_match_array = (pumitem_T *)alloc_clear( (unsigned)(sizeof(pumitem_T) * compl_match_arraysize)); if (compl_match_array != NULL) { /* If the current match is the original text don't find the first * match after it, don't highlight anything. */ if (compl_shown_match->cp_flags & ORIGINAL_TEXT) shown_match_ok = TRUE; i = 0; compl = compl_first_match; do { if ((compl->cp_flags & ORIGINAL_TEXT) == 0 && (compl_leader == NULL || ins_compl_equal(compl, compl_leader, lead_len))) { if (!shown_match_ok) { if (compl == compl_shown_match || did_find_shown_match) { /* This item is the shown match or this is the * first displayed item after the shown match. */ compl_shown_match = compl; did_find_shown_match = TRUE; shown_match_ok = TRUE; } else /* Remember this displayed match for when the * shown match is just below it. */ shown_compl = compl; cur = i; } if (compl->cp_text[CPT_ABBR] != NULL) compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR]; else compl_match_array[i].pum_text = compl->cp_str; compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND]; compl_match_array[i].pum_info = compl->cp_text[CPT_INFO]; if (compl->cp_text[CPT_MENU] != NULL) compl_match_array[i++].pum_extra = compl->cp_text[CPT_MENU]; else compl_match_array[i++].pum_extra = compl->cp_fname; } if (compl == compl_shown_match) { did_find_shown_match = TRUE; /* When the original text is the shown match don't set * compl_shown_match. */ if (compl->cp_flags & ORIGINAL_TEXT) shown_match_ok = TRUE; if (!shown_match_ok && shown_compl != NULL) { /* The shown match isn't displayed, set it to the * previously displayed match. */ compl_shown_match = shown_compl; shown_match_ok = TRUE; } } compl = compl->cp_next; } while (compl != NULL && compl != compl_first_match); if (!shown_match_ok) /* no displayed match at all */ cur = -1; } } else { /* popup menu already exists, only need to find the current item.*/ for (i = 0; i < compl_match_arraysize; ++i) if (compl_match_array[i].pum_text == compl_shown_match->cp_str || compl_match_array[i].pum_text == compl_shown_match->cp_text[CPT_ABBR]) { cur = i; break; } } if (compl_match_array != NULL) { /* Compute the screen column of the start of the completed text. * Use the cursor to get all wrapping and other settings right. */ col = curwin->w_cursor.col; curwin->w_cursor.col = compl_col; pum_display(compl_match_array, compl_match_arraysize, cur); curwin->w_cursor.col = col; } } #define DICT_FIRST (1) /* use just first element in "dict" */ #define DICT_EXACT (2) /* "dict" is the exact name of a file */ /* * Add any identifiers that match the given pattern in the list of dictionary * files "dict_start" to the list of completions. */ static void ins_compl_dictionaries(dict_start, pat, flags, thesaurus) char_u *dict_start; char_u *pat; int flags; /* DICT_FIRST and/or DICT_EXACT */ int thesaurus; /* Thesaurus completion */ { char_u *dict = dict_start; char_u *ptr; char_u *buf; regmatch_T regmatch; char_u **files; int count; int save_p_scs; int dir = compl_direction; if (*dict == NUL) { #ifdef FEAT_SPELL /* When 'dictionary' is empty and spell checking is enabled use * "spell". */ if (!thesaurus && curwin->w_p_spell) dict = (char_u *)"spell"; else #endif return; } buf = alloc(LSIZE); if (buf == NULL) return; regmatch.regprog = NULL; /* so that we can goto theend */ /* If 'infercase' is set, don't use 'smartcase' here */ save_p_scs = p_scs; if (curbuf->b_p_inf) p_scs = FALSE; /* When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern * to only match at the start of a line. Otherwise just match the * pattern. Also need to double backslashes. */ if (ctrl_x_mode == CTRL_X_WHOLE_LINE) { char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\"); size_t len; if (pat_esc == NULL) goto theend; len = STRLEN(pat_esc) + 10; ptr = alloc((unsigned)len); if (ptr == NULL) { vim_free(pat_esc); goto theend; } vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc); regmatch.regprog = vim_regcomp(ptr, RE_MAGIC); vim_free(pat_esc); vim_free(ptr); } else { regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0); if (regmatch.regprog == NULL) goto theend; } /* ignore case depends on 'ignorecase', 'smartcase' and "pat" */ regmatch.rm_ic = ignorecase(pat); while (*dict != NUL && !got_int && !compl_interrupted) { /* copy one dictionary file name into buf */ if (flags == DICT_EXACT) { count = 1; files = &dict; } else { /* Expand wildcards in the dictionary name, but do not allow * backticks (for security, the 'dict' option may have been set in * a modeline). */ copy_option_part(&dict, buf, LSIZE, ","); # ifdef FEAT_SPELL if (!thesaurus && STRCMP(buf, "spell") == 0) count = -1; else # endif if (vim_strchr(buf, '`') != NULL || expand_wildcards(1, &buf, &count, &files, EW_FILE|EW_SILENT) != OK) count = 0; } # ifdef FEAT_SPELL if (count == -1) { /* Complete from active spelling. Skip "\<" in the pattern, we * don't use it as a RE. */ if (pat[0] == '\\' && pat[1] == '<') ptr = pat + 2; else ptr = pat; spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0); } else # endif if (count > 0) /* avoid warning for using "files" uninit */ { ins_compl_files(count, files, thesaurus, flags, &regmatch, buf, &dir); if (flags != DICT_EXACT) FreeWild(count, files); } if (flags != 0) break; } theend: p_scs = save_p_scs; vim_free(regmatch.regprog); vim_free(buf); } static void ins_compl_files(count, files, thesaurus, flags, regmatch, buf, dir) int count; char_u **files; int thesaurus; int flags; regmatch_T *regmatch; char_u *buf; int *dir; { char_u *ptr; int i; FILE *fp; int add_r; for (i = 0; i < count && !got_int && !compl_interrupted; i++) { fp = mch_fopen((char *)files[i], "r"); /* open dictionary file */ if (flags != DICT_EXACT) { vim_snprintf((char *)IObuff, IOSIZE, _("Scanning dictionary: %s"), (char *)files[i]); (void)msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R)); } if (fp != NULL) { /* * Read dictionary file line by line. * Check each line for a match. */ while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp)) { ptr = buf; while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf))) { ptr = regmatch->startp[0]; if (ctrl_x_mode == CTRL_X_WHOLE_LINE) ptr = find_line_end(ptr); else ptr = find_word_end(ptr); add_r = ins_compl_add_infercase(regmatch->startp[0], (int)(ptr - regmatch->startp[0]), p_ic, files[i], *dir, 0); if (thesaurus) { char_u *wstart; /* * Add the other matches on the line */ ptr = buf; while (!got_int) { /* Find start of the next word. Skip white * space and punctuation. */ ptr = find_word_start(ptr); if (*ptr == NUL || *ptr == NL) break; wstart = ptr; /* Find end of the word. */ #ifdef FEAT_MBYTE if (has_mbyte) /* Japanese words may have characters in * different classes, only separate words * with single-byte non-word characters. */ while (*ptr != NUL) { int l = (*mb_ptr2len)(ptr); if (l < 2 && !vim_iswordc(*ptr)) break; ptr += l; } else #endif ptr = find_word_end(ptr); /* Add the word. Skip the regexp match. */ if (wstart != regmatch->startp[0]) add_r = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic, files[i], *dir, 0); } } if (add_r == OK) /* if dir was BACKWARD then honor it just once */ *dir = FORWARD; else if (add_r == FAIL) break; /* avoid expensive call to vim_regexec() when at end * of line */ if (*ptr == '\n' || got_int) break; } line_breakcheck(); ins_compl_check_keys(50); } fclose(fp); } } } /* * Find the start of the next word. * Returns a pointer to the first char of the word. Also stops at a NUL. */ char_u * find_word_start(ptr) char_u *ptr; { #ifdef FEAT_MBYTE if (has_mbyte) while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1) ptr += (*mb_ptr2len)(ptr); else #endif while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr)) ++ptr; return ptr; } /* * Find the end of the word. Assumes it starts inside a word. * Returns a pointer to just after the word. */ char_u * find_word_end(ptr) char_u *ptr; { #ifdef FEAT_MBYTE int start_class; if (has_mbyte) { start_class = mb_get_class(ptr); if (start_class > 1) while (*ptr != NUL) { ptr += (*mb_ptr2len)(ptr); if (mb_get_class(ptr) != start_class) break; } } else #endif while (vim_iswordc(*ptr)) ++ptr; return ptr; } /* * Find the end of the line, omitting CR and NL at the end. * Returns a pointer to just after the line. */ static char_u * find_line_end(ptr) char_u *ptr; { char_u *s; s = ptr + STRLEN(ptr); while (s > ptr && (s[-1] == CAR || s[-1] == NL)) --s; return s; } /* * Free the list of completions */ static void ins_compl_free() { compl_T *match; int i; vim_free(compl_pattern); compl_pattern = NULL; vim_free(compl_leader); compl_leader = NULL; if (compl_first_match == NULL) return; ins_compl_del_pum(); pum_clear(); compl_curr_match = compl_first_match; do { match = compl_curr_match; compl_curr_match = compl_curr_match->cp_next; vim_free(match->cp_str); /* several entries may use the same fname, free it just once. */ if (match->cp_flags & FREE_FNAME) vim_free(match->cp_fname); for (i = 0; i < CPT_COUNT; ++i) vim_free(match->cp_text[i]); vim_free(match); } while (compl_curr_match != NULL && compl_curr_match != compl_first_match); compl_first_match = compl_curr_match = NULL; compl_shown_match = NULL; } static void ins_compl_clear() { compl_cont_status = 0; compl_started = FALSE; compl_matches = 0; vim_free(compl_pattern); compl_pattern = NULL; vim_free(compl_leader); compl_leader = NULL; edit_submode_extra = NULL; vim_free(compl_orig_text); compl_orig_text = NULL; compl_enter_selects = FALSE; } /* * Return TRUE when Insert completion is active. */ int ins_compl_active() { return compl_started; } /* * Delete one character before the cursor and show the subset of the matches * that match the word that is now before the cursor. * Returns the character to be used, NUL if the work is done and another char * to be got from the user. */ static int ins_compl_bs() { char_u *line; char_u *p; line = ml_get_curline(); p = line + curwin->w_cursor.col; mb_ptr_back(line, p); /* Stop completion when the whole word was deleted. For Omni completion * allow the word to be deleted, we won't match everything. */ if ((int)(p - line) - (int)compl_col < 0 || ((int)(p - line) - (int)compl_col == 0 && (ctrl_x_mode & CTRL_X_OMNI) == 0)) return K_BS; /* Deleted more than what was used to find matches or didn't finish * finding all matches: need to look for matches all over again. */ if (curwin->w_cursor.col <= compl_col + compl_length || ins_compl_need_restart()) ins_compl_restart(); vim_free(compl_leader); compl_leader = vim_strnsave(line + compl_col, (int)(p - line) - compl_col); if (compl_leader != NULL) { ins_compl_new_leader(); return NUL; } return K_BS; } /* * Return TRUE when we need to find matches again, ins_compl_restart() is to * be called. */ static int ins_compl_need_restart() { /* Return TRUE if we didn't complete finding matches or when the * 'completefunc' returned "always" in the "refresh" dictionary item. */ return compl_was_interrupted || ((ctrl_x_mode == CTRL_X_FUNCTION || ctrl_x_mode == CTRL_X_OMNI) && compl_opt_refresh_always); } /* * Called after changing "compl_leader". * Show the popup menu with a different set of matches. * May also search for matches again if the previous search was interrupted. */ static void ins_compl_new_leader() { ins_compl_del_pum(); ins_compl_delete(); ins_bytes(compl_leader + ins_compl_len()); compl_used_match = FALSE; if (compl_started) ins_compl_set_original_text(compl_leader); else { #ifdef FEAT_SPELL spell_bad_len = 0; /* need to redetect bad word */ #endif /* * Matches were cleared, need to search for them now. First display * the changed text before the cursor. Set "compl_restarting" to * avoid that the first match is inserted. */ update_screen(0); #ifdef FEAT_GUI if (gui.in_use) { /* Show the cursor after the match, not after the redrawn text. */ setcursor(); out_flush(); gui_update_cursor(FALSE, FALSE); } #endif compl_restarting = TRUE; if (ins_complete(Ctrl_N) == FAIL) compl_cont_status = 0; compl_restarting = FALSE; } compl_enter_selects = !compl_used_match; /* Show the popup menu with a different set of matches. */ ins_compl_show_pum(); /* Don't let Enter select the original text when there is no popup menu. */ if (compl_match_array == NULL) compl_enter_selects = FALSE; } /* * Return the length of the completion, from the completion start column to * the cursor column. Making sure it never goes below zero. */ static int ins_compl_len() { int off = (int)curwin->w_cursor.col - (int)compl_col; if (off < 0) return 0; return off; } /* * Append one character to the match leader. May reduce the number of * matches. */ static void ins_compl_addleader(c) int c; { #ifdef FEAT_MBYTE int cc; if (has_mbyte && (cc = (*mb_char2len)(c)) > 1) { char_u buf[MB_MAXBYTES + 1]; (*mb_char2bytes)(c, buf); buf[cc] = NUL; ins_char_bytes(buf, cc); if (compl_opt_refresh_always) AppendToRedobuff(buf); } else #endif { ins_char(c); if (compl_opt_refresh_always) AppendCharToRedobuff(c); } /* If we didn't complete finding matches we must search again. */ if (ins_compl_need_restart()) ins_compl_restart(); /* When 'always' is set, don't reset compl_leader. While completing, * cursor doesn't point original position, changing compl_leader would * break redo. */ if (!compl_opt_refresh_always) { vim_free(compl_leader); compl_leader = vim_strnsave(ml_get_curline() + compl_col, (int)(curwin->w_cursor.col - compl_col)); if (compl_leader != NULL) ins_compl_new_leader(); } } /* * Setup for finding completions again without leaving CTRL-X mode. Used when * BS or a key was typed while still searching for matches. */ static void ins_compl_restart() { ins_compl_free(); compl_started = FALSE; compl_matches = 0; compl_cont_status = 0; compl_cont_mode = 0; } /* * Set the first match, the original text. */ static void ins_compl_set_original_text(str) char_u *str; { char_u *p; /* Replace the original text entry. */ if (compl_first_match->cp_flags & ORIGINAL_TEXT) /* safety check */ { p = vim_strsave(str); if (p != NULL) { vim_free(compl_first_match->cp_str); compl_first_match->cp_str = p; } } } /* * Append one character to the match leader. May reduce the number of * matches. */ static void ins_compl_addfrommatch() { char_u *p; int len = (int)curwin->w_cursor.col - (int)compl_col; int c; compl_T *cp; p = compl_shown_match->cp_str; if ((int)STRLEN(p) <= len) /* the match is too short */ { /* When still at the original match use the first entry that matches * the leader. */ if (compl_shown_match->cp_flags & ORIGINAL_TEXT) { p = NULL; for (cp = compl_shown_match->cp_next; cp != NULL && cp != compl_first_match; cp = cp->cp_next) { if (compl_leader == NULL || ins_compl_equal(cp, compl_leader, (int)STRLEN(compl_leader))) { p = cp->cp_str; break; } } if (p == NULL || (int)STRLEN(p) <= len) return; } else return; } p += len; c = PTR2CHAR(p); ins_compl_addleader(c); } /* * Prepare for Insert mode completion, or stop it. * Called just after typing a character in Insert mode. * Returns TRUE when the character is not to be inserted; */ static int ins_compl_prep(c) int c; { char_u *ptr; int want_cindent; int retval = FALSE; /* Forget any previous 'special' messages if this is actually * a ^X mode key - bar ^R, in which case we wait to see what it gives us. */ if (c != Ctrl_R && vim_is_ctrl_x_key(c)) edit_submode_extra = NULL; /* Ignore end of Select mode mapping and mouse scroll buttons. */ if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP || c == K_MOUSELEFT || c == K_MOUSERIGHT) return retval; /* Set "compl_get_longest" when finding the first matches. */ if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET || (ctrl_x_mode == 0 && !compl_started)) { compl_get_longest = (vim_strchr(p_cot, 'l') != NULL); compl_used_match = TRUE; } if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET) { /* * We have just typed CTRL-X and aren't quite sure which CTRL-X mode * it will be yet. Now we decide. */ switch (c) { case Ctrl_E: case Ctrl_Y: ctrl_x_mode = CTRL_X_SCROLL; if (!(State & REPLACE_FLAG)) edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)"); else edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)"); edit_submode_pre = NULL; showmode(); break; case Ctrl_L: ctrl_x_mode = CTRL_X_WHOLE_LINE; break; case Ctrl_F: ctrl_x_mode = CTRL_X_FILES; break; case Ctrl_K: ctrl_x_mode = CTRL_X_DICTIONARY; break; case Ctrl_R: /* Simply allow ^R to happen without affecting ^X mode */ break; case Ctrl_T: ctrl_x_mode = CTRL_X_THESAURUS; break; #ifdef FEAT_COMPL_FUNC case Ctrl_U: ctrl_x_mode = CTRL_X_FUNCTION; break; case Ctrl_O: ctrl_x_mode = CTRL_X_OMNI; break; #endif case 's': case Ctrl_S: ctrl_x_mode = CTRL_X_SPELL; #ifdef FEAT_SPELL ++emsg_off; /* Avoid getting the E756 error twice. */ spell_back_to_badword(); --emsg_off; #endif break; case Ctrl_RSB: ctrl_x_mode = CTRL_X_TAGS; break; #ifdef FEAT_FIND_ID case Ctrl_I: case K_S_TAB: ctrl_x_mode = CTRL_X_PATH_PATTERNS; break; case Ctrl_D: ctrl_x_mode = CTRL_X_PATH_DEFINES; break; #endif case Ctrl_V: case Ctrl_Q: ctrl_x_mode = CTRL_X_CMDLINE; break; case Ctrl_P: case Ctrl_N: /* ^X^P means LOCAL expansion if nothing interrupted (eg we * just started ^X mode, or there were enough ^X's to cancel * the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below) * do normal expansion when interrupting a different mode (say * ^X^F^X^P or ^P^X^X^P, see below) * nothing changes if interrupting mode 0, (eg, the flag * doesn't change when going to ADDING mode -- Acevedo */ if (!(compl_cont_status & CONT_INTRPT)) compl_cont_status |= CONT_LOCAL; else if (compl_cont_mode != 0) compl_cont_status &= ~CONT_LOCAL; /* FALLTHROUGH */ default: /* If we have typed at least 2 ^X's... for modes != 0, we set * compl_cont_status = 0 (eg, as if we had just started ^X * mode). * For mode 0, we set "compl_cont_mode" to an impossible * value, in both cases ^X^X can be used to restart the same * mode (avoiding ADDING mode). * Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start * 'complete' and local ^P expansions respectively. * In mode 0 an extra ^X is needed since ^X^P goes to ADDING * mode -- Acevedo */ if (c == Ctrl_X) { if (compl_cont_mode != 0) compl_cont_status = 0; else compl_cont_mode = CTRL_X_NOT_DEFINED_YET; } ctrl_x_mode = 0; edit_submode = NULL; showmode(); break; } } else if (ctrl_x_mode != 0) { /* We're already in CTRL-X mode, do we stay in it? */ if (!vim_is_ctrl_x_key(c)) { if (ctrl_x_mode == CTRL_X_SCROLL) ctrl_x_mode = 0; else ctrl_x_mode = CTRL_X_FINISHED; edit_submode = NULL; } showmode(); } if (compl_started || ctrl_x_mode == CTRL_X_FINISHED) { /* Show error message from attempted keyword completion (probably * 'Pattern not found') until another key is hit, then go back to * showing what mode we are in. */ showmode(); if ((ctrl_x_mode == 0 && c != Ctrl_N && c != Ctrl_P && c != Ctrl_R && !ins_compl_pum_key(c)) || ctrl_x_mode == CTRL_X_FINISHED) { /* Get here when we have finished typing a sequence of ^N and * ^P or other completion characters in CTRL-X mode. Free up * memory that was used, and make sure we can redo the insert. */ if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E) { /* * If any of the original typed text has been changed, eg when * ignorecase is set, we must add back-spaces to the redo * buffer. We add as few as necessary to delete just the part * of the original text that has changed. * When using the longest match, edited the match or used * CTRL-E then don't use the current match. */ if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E) ptr = compl_curr_match->cp_str; else ptr = NULL; ins_compl_fixRedoBufForLeader(ptr); } #ifdef FEAT_CINDENT want_cindent = (can_cindent && cindent_on()); #endif /* * When completing whole lines: fix indent for 'cindent'. * Otherwise, break line if it's too long. */ if (compl_cont_mode == CTRL_X_WHOLE_LINE) { #ifdef FEAT_CINDENT /* re-indent the current line */ if (want_cindent) { do_c_expr_indent(); want_cindent = FALSE; /* don't do it again */ } #endif } else { int prev_col = curwin->w_cursor.col; /* put the cursor on the last char, for 'tw' formatting */ if (prev_col > 0) dec_cursor(); if (stop_arrow() == OK) insertchar(NUL, 0, -1); if (prev_col > 0 && ml_get_curline()[curwin->w_cursor.col] != NUL) inc_cursor(); } /* If the popup menu is displayed pressing CTRL-Y means accepting * the selection without inserting anything. When * compl_enter_selects is set the Enter key does the same. */ if ((c == Ctrl_Y || (compl_enter_selects && (c == CAR || c == K_KENTER || c == NL))) && pum_visible()) retval = TRUE; /* CTRL-E means completion is Ended, go back to the typed text. */ if (c == Ctrl_E) { ins_compl_delete(); if (compl_leader != NULL) ins_bytes(compl_leader + ins_compl_len()); else if (compl_first_match != NULL) ins_bytes(compl_orig_text + ins_compl_len()); retval = TRUE; } auto_format(FALSE, TRUE); ins_compl_free(); compl_started = FALSE; compl_matches = 0; msg_clr_cmdline(); /* necessary for "noshowmode" */ ctrl_x_mode = 0; compl_enter_selects = FALSE; if (edit_submode != NULL) { edit_submode = NULL; showmode(); } #ifdef FEAT_CINDENT /* * Indent now if a key was typed that is in 'cinkeys'. */ if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0))) do_c_expr_indent(); #endif } } /* reset continue_* if we left expansion-mode, if we stay they'll be * (re)set properly in ins_complete() */ if (!vim_is_ctrl_x_key(c)) { compl_cont_status = 0; compl_cont_mode = 0; } return retval; } /* * Fix the redo buffer for the completion leader replacing some of the typed * text. This inserts backspaces and appends the changed text. * "ptr" is the known leader text or NUL. */ static void ins_compl_fixRedoBufForLeader(ptr_arg) char_u *ptr_arg; { int len; char_u *p; char_u *ptr = ptr_arg; if (ptr == NULL) { if (compl_leader != NULL) ptr = compl_leader; else return; /* nothing to do */ } if (compl_orig_text != NULL) { p = compl_orig_text; for (len = 0; p[len] != NUL && p[len] == ptr[len]; ++len) ; #ifdef FEAT_MBYTE if (len > 0) len -= (*mb_head_off)(p, p + len); #endif for (p += len; *p != NUL; mb_ptr_adv(p)) AppendCharToRedobuff(K_BS); } else len = 0; if (ptr != NULL) AppendToRedobuffLit(ptr + len, -1); } /* * Loops through the list of windows, loaded-buffers or non-loaded-buffers * (depending on flag) starting from buf and looking for a non-scanned * buffer (other than curbuf). curbuf is special, if it is called with * buf=curbuf then it has to be the first call for a given flag/expansion. * * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo */ static buf_T * ins_compl_next_buf(buf, flag) buf_T *buf; int flag; { #ifdef FEAT_WINDOWS static win_T *wp; #endif if (flag == 'w') /* just windows */ { #ifdef FEAT_WINDOWS if (buf == curbuf) /* first call for this flag/expansion */ wp = curwin; while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin && wp->w_buffer->b_scanned) ; buf = wp->w_buffer; #else buf = curbuf; #endif } else /* 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U' * (unlisted buffers) * When completing whole lines skip unloaded buffers. */ while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf && ((flag == 'U' ? buf->b_p_bl : (!buf->b_p_bl || (buf->b_ml.ml_mfp == NULL) != (flag == 'u'))) || buf->b_scanned)) ; return buf; } #ifdef FEAT_COMPL_FUNC static void expand_by_function __ARGS((int type, char_u *base)); /* * Execute user defined complete function 'completefunc' or 'omnifunc', and * get matches in "matches". */ static void expand_by_function(type, base) int type; /* CTRL_X_OMNI or CTRL_X_FUNCTION */ char_u *base; { list_T *matchlist = NULL; dict_T *matchdict = NULL; char_u *args[2]; char_u *funcname; pos_T pos; win_T *curwin_save; buf_T *curbuf_save; typval_T rettv; funcname = (type == CTRL_X_FUNCTION) ? curbuf->b_p_cfu : curbuf->b_p_ofu; if (*funcname == NUL) return; /* Call 'completefunc' to obtain the list of matches. */ args[0] = (char_u *)"0"; args[1] = base; pos = curwin->w_cursor; curwin_save = curwin; curbuf_save = curbuf; /* Call a function, which returns a list or dict. */ if (call_vim_function(funcname, 2, args, FALSE, &rettv) == OK) { switch (rettv.v_type) { case VAR_LIST: matchlist = rettv.vval.v_list; break; case VAR_DICT: matchdict = rettv.vval.v_dict; break; default: /* TODO: Give error message? */ clear_tv(&rettv); break; } } if (curwin_save != curwin || curbuf_save != curbuf) { EMSG(_(e_complwin)); goto theend; } curwin->w_cursor = pos; /* restore the cursor position */ check_cursor(); if (!equalpos(curwin->w_cursor, pos)) { EMSG(_(e_compldel)); goto theend; } if (matchlist != NULL) ins_compl_add_list(matchlist); else if (matchdict != NULL) ins_compl_add_dict(matchdict); theend: if (matchdict != NULL) dict_unref(matchdict); if (matchlist != NULL) list_unref(matchlist); } #endif /* FEAT_COMPL_FUNC */ #if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO) /* * Add completions from a list. */ static void ins_compl_add_list(list) list_T *list; { listitem_T *li; int dir = compl_direction; /* Go through the List with matches and add each of them. */ for (li = list->lv_first; li != NULL; li = li->li_next) { if (ins_compl_add_tv(&li->li_tv, dir) == OK) /* if dir was BACKWARD then honor it just once */ dir = FORWARD; else if (did_emsg) break; } } /* * Add completions from a dict. */ static void ins_compl_add_dict(dict) dict_T *dict; { dictitem_T *di_refresh; dictitem_T *di_words; /* Check for optional "refresh" item. */ compl_opt_refresh_always = FALSE; di_refresh = dict_find(dict, (char_u *)"refresh", 7); if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING) { char_u *v = di_refresh->di_tv.vval.v_string; if (v != NULL && STRCMP(v, (char_u *)"always") == 0) compl_opt_refresh_always = TRUE; } /* Add completions from a "words" list. */ di_words = dict_find(dict, (char_u *)"words", 5); if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST) ins_compl_add_list(di_words->di_tv.vval.v_list); } /* * Add a match to the list of matches from a typeval_T. * If the given string is already in the list of completions, then return * NOTDONE, otherwise add it to the list and return OK. If there is an error, * maybe because alloc() returns NULL, then FAIL is returned. */ int ins_compl_add_tv(tv, dir) typval_T *tv; int dir; { char_u *word; int icase = FALSE; int adup = FALSE; int aempty = FALSE; char_u *(cptext[CPT_COUNT]); if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL) { word = get_dict_string(tv->vval.v_dict, (char_u *)"word", FALSE); cptext[CPT_ABBR] = get_dict_string(tv->vval.v_dict, (char_u *)"abbr", FALSE); cptext[CPT_MENU] = get_dict_string(tv->vval.v_dict, (char_u *)"menu", FALSE); cptext[CPT_KIND] = get_dict_string(tv->vval.v_dict, (char_u *)"kind", FALSE); cptext[CPT_INFO] = get_dict_string(tv->vval.v_dict, (char_u *)"info", FALSE); if (get_dict_string(tv->vval.v_dict, (char_u *)"icase", FALSE) != NULL) icase = get_dict_number(tv->vval.v_dict, (char_u *)"icase"); if (get_dict_string(tv->vval.v_dict, (char_u *)"dup", FALSE) != NULL) adup = get_dict_number(tv->vval.v_dict, (char_u *)"dup"); if (get_dict_string(tv->vval.v_dict, (char_u *)"empty", FALSE) != NULL) aempty = get_dict_number(tv->vval.v_dict, (char_u *)"empty"); } else { word = get_tv_string_chk(tv); vim_memset(cptext, 0, sizeof(cptext)); } if (word == NULL || (!aempty && *word == NUL)) return FAIL; return ins_compl_add(word, -1, icase, NULL, cptext, dir, 0, adup); } #endif /* * Get the next expansion(s), using "compl_pattern". * The search starts at position "ini" in curbuf and in the direction * compl_direction. * When "compl_started" is FALSE start at that position, otherwise continue * where we stopped searching before. * This may return before finding all the matches. * Return the total number of matches or -1 if still unknown -- Acevedo */ static int ins_compl_get_exp(ini) pos_T *ini; { static pos_T first_match_pos; static pos_T last_match_pos; static char_u *e_cpt = (char_u *)""; /* curr. entry in 'complete' */ static int found_all = FALSE; /* Found all matches of a certain type. */ static buf_T *ins_buf = NULL; /* buffer being scanned */ pos_T *pos; char_u **matches; int save_p_scs; int save_p_ws; int save_p_ic; int i; int num_matches; int len; int found_new_match; int type = ctrl_x_mode; char_u *ptr; char_u *dict = NULL; int dict_f = 0; compl_T *old_match; if (!compl_started) { for (ins_buf = firstbuf; ins_buf != NULL; ins_buf = ins_buf->b_next) ins_buf->b_scanned = 0; found_all = FALSE; ins_buf = curbuf; e_cpt = (compl_cont_status & CONT_LOCAL) ? (char_u *)"." : curbuf->b_p_cpt; last_match_pos = first_match_pos = *ini; } old_match = compl_curr_match; /* remember the last current match */ pos = (compl_direction == FORWARD) ? &last_match_pos : &first_match_pos; /* For ^N/^P loop over all the flags/windows/buffers in 'complete' */ for (;;) { found_new_match = FAIL; /* For ^N/^P pick a new entry from e_cpt if compl_started is off, * or if found_all says this entry is done. For ^X^L only use the * entries from 'complete' that look in loaded buffers. */ if ((ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_WHOLE_LINE) && (!compl_started || found_all)) { found_all = FALSE; while (*e_cpt == ',' || *e_cpt == ' ') e_cpt++; if (*e_cpt == '.' && !curbuf->b_scanned) { ins_buf = curbuf; first_match_pos = *ini; /* So that ^N can match word immediately after cursor */ if (ctrl_x_mode == 0) dec(&first_match_pos); last_match_pos = first_match_pos; type = 0; } else if (vim_strchr((char_u *)"buwU", *e_cpt) != NULL && (ins_buf = ins_compl_next_buf(ins_buf, *e_cpt)) != curbuf) { /* Scan a buffer, but not the current one. */ if (ins_buf->b_ml.ml_mfp != NULL) /* loaded buffer */ { compl_started = TRUE; first_match_pos.col = last_match_pos.col = 0; first_match_pos.lnum = ins_buf->b_ml.ml_line_count + 1; last_match_pos.lnum = 0; type = 0; } else /* unloaded buffer, scan like dictionary */ { found_all = TRUE; if (ins_buf->b_fname == NULL) continue; type = CTRL_X_DICTIONARY; dict = ins_buf->b_fname; dict_f = DICT_EXACT; } vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"), ins_buf->b_fname == NULL ? buf_spname(ins_buf) : ins_buf->b_sfname == NULL ? (char *)ins_buf->b_fname : (char *)ins_buf->b_sfname); (void)msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R)); } else if (*e_cpt == NUL) break; else { if (ctrl_x_mode == CTRL_X_WHOLE_LINE) type = -1; else if (*e_cpt == 'k' || *e_cpt == 's') { if (*e_cpt == 'k') type = CTRL_X_DICTIONARY; else type = CTRL_X_THESAURUS; if (*++e_cpt != ',' && *e_cpt != NUL) { dict = e_cpt; dict_f = DICT_FIRST; } } #ifdef FEAT_FIND_ID else if (*e_cpt == 'i') type = CTRL_X_PATH_PATTERNS; else if (*e_cpt == 'd') type = CTRL_X_PATH_DEFINES; #endif else if (*e_cpt == ']' || *e_cpt == 't') { type = CTRL_X_TAGS; vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags.")); (void)msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R)); } else type = -1; /* in any case e_cpt is advanced to the next entry */ (void)copy_option_part(&e_cpt, IObuff, IOSIZE, ","); found_all = TRUE; if (type == -1) continue; } } switch (type) { case -1: break; #ifdef FEAT_FIND_ID case CTRL_X_PATH_PATTERNS: case CTRL_X_PATH_DEFINES: find_pattern_in_path(compl_pattern, compl_direction, (int)STRLEN(compl_pattern), FALSE, FALSE, (type == CTRL_X_PATH_DEFINES && !(compl_cont_status & CONT_SOL)) ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND, (linenr_T)1, (linenr_T)MAXLNUM); break; #endif case CTRL_X_DICTIONARY: case CTRL_X_THESAURUS: ins_compl_dictionaries( dict != NULL ? dict : (type == CTRL_X_THESAURUS ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr) : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)), compl_pattern, dict != NULL ? dict_f : 0, type == CTRL_X_THESAURUS); dict = NULL; break; case CTRL_X_TAGS: /* set p_ic according to p_ic, p_scs and pat for find_tags(). */ save_p_ic = p_ic; p_ic = ignorecase(compl_pattern); /* Find up to TAG_MANY matches. Avoids that an enormous number * of matches is found when compl_pattern is empty */ if (find_tags(compl_pattern, &num_matches, &matches, TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP | (ctrl_x_mode ? TAG_VERBOSE : 0), TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0) { ins_compl_add_matches(num_matches, matches, p_ic); } p_ic = save_p_ic; break; case CTRL_X_FILES: if (expand_wildcards(1, &compl_pattern, &num_matches, &matches, EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) == OK) { /* May change home directory back to "~". */ tilde_replace(compl_pattern, num_matches, matches); ins_compl_add_matches(num_matches, matches, #ifdef CASE_INSENSITIVE_FILENAME TRUE #else FALSE #endif ); } break; case CTRL_X_CMDLINE: if (expand_cmdline(&compl_xp, compl_pattern, (int)STRLEN(compl_pattern), &num_matches, &matches) == EXPAND_OK) ins_compl_add_matches(num_matches, matches, FALSE); break; #ifdef FEAT_COMPL_FUNC case CTRL_X_FUNCTION: case CTRL_X_OMNI: expand_by_function(type, compl_pattern); break; #endif case CTRL_X_SPELL: #ifdef FEAT_SPELL num_matches = expand_spelling(first_match_pos.lnum, compl_pattern, &matches); if (num_matches > 0) ins_compl_add_matches(num_matches, matches, p_ic); #endif break; default: /* normal ^P/^N and ^X^L */ /* * If 'infercase' is set, don't use 'smartcase' here */ save_p_scs = p_scs; if (ins_buf->b_p_inf) p_scs = FALSE; /* buffers other than curbuf are scanned from the beginning or the * end but never from the middle, thus setting nowrapscan in this * buffers is a good idea, on the other hand, we always set * wrapscan for curbuf to avoid missing matches -- Acevedo,Webb */ save_p_ws = p_ws; if (ins_buf != curbuf) p_ws = FALSE; else if (*e_cpt == '.') p_ws = TRUE; for (;;) { int flags = 0; ++msg_silent; /* Don't want messages for wrapscan. */ /* ctrl_x_mode == CTRL_X_WHOLE_LINE || word-wise search that * has added a word that was at the beginning of the line */ if ( ctrl_x_mode == CTRL_X_WHOLE_LINE || (compl_cont_status & CONT_SOL)) found_new_match = search_for_exact_line(ins_buf, pos, compl_direction, compl_pattern); else found_new_match = searchit(NULL, ins_buf, pos, compl_direction, compl_pattern, 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, (linenr_T)0, NULL); --msg_silent; if (!compl_started) { /* set "compl_started" even on fail */ compl_started = TRUE; first_match_pos = *pos; last_match_pos = *pos; } else if (first_match_pos.lnum == last_match_pos.lnum && first_match_pos.col == last_match_pos.col) found_new_match = FAIL; if (found_new_match == FAIL) { if (ins_buf == curbuf) found_all = TRUE; break; } /* when ADDING, the text before the cursor matches, skip it */ if ( (compl_cont_status & CONT_ADDING) && ins_buf == curbuf && ini->lnum == pos->lnum && ini->col == pos->col) continue; ptr = ml_get_buf(ins_buf, pos->lnum, FALSE) + pos->col; if (ctrl_x_mode == CTRL_X_WHOLE_LINE) { if (compl_cont_status & CONT_ADDING) { if (pos->lnum >= ins_buf->b_ml.ml_line_count) continue; ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE); if (!p_paste) ptr = skipwhite(ptr); } len = (int)STRLEN(ptr); } else { char_u *tmp_ptr = ptr; if (compl_cont_status & CONT_ADDING) { tmp_ptr += compl_length; /* Skip if already inside a word. */ if (vim_iswordp(tmp_ptr)) continue; /* Find start of next word. */ tmp_ptr = find_word_start(tmp_ptr); } /* Find end of this word. */ tmp_ptr = find_word_end(tmp_ptr); len = (int)(tmp_ptr - ptr); if ((compl_cont_status & CONT_ADDING) && len == compl_length) { if (pos->lnum < ins_buf->b_ml.ml_line_count) { /* Try next line, if any. the new word will be * "join" as if the normal command "J" was used. * IOSIZE is always greater than * compl_length, so the next STRNCPY always * works -- Acevedo */ STRNCPY(IObuff, ptr, len); ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE); tmp_ptr = ptr = skipwhite(ptr); /* Find start of next word. */ tmp_ptr = find_word_start(tmp_ptr); /* Find end of next word. */ tmp_ptr = find_word_end(tmp_ptr); if (tmp_ptr > ptr) { if (*ptr != ')' && IObuff[len - 1] != TAB) { if (IObuff[len - 1] != ' ') IObuff[len++] = ' '; /* IObuf =~ "\k.* ", thus len >= 2 */ if (p_js && (IObuff[len - 2] == '.' || (vim_strchr(p_cpo, CPO_JOINSP) == NULL && (IObuff[len - 2] == '?' || IObuff[len - 2] == '!')))) IObuff[len++] = ' '; } /* copy as much as possible of the new word */ if (tmp_ptr - ptr >= IOSIZE - len) tmp_ptr = ptr + IOSIZE - len - 1; STRNCPY(IObuff + len, ptr, tmp_ptr - ptr); len += (int)(tmp_ptr - ptr); flags |= CONT_S_IPOS; } IObuff[len] = NUL; ptr = IObuff; } if (len == compl_length) continue; } } if (ins_compl_add_infercase(ptr, len, p_ic, ins_buf == curbuf ? NULL : ins_buf->b_sfname, 0, flags) != NOTDONE) { found_new_match = OK; break; } } p_scs = save_p_scs; p_ws = save_p_ws; } /* check if compl_curr_match has changed, (e.g. other type of * expansion added something) */ if (type != 0 && compl_curr_match != old_match) found_new_match = OK; /* break the loop for specialized modes (use 'complete' just for the * generic ctrl_x_mode == 0) or when we've found a new match */ if ((ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE) || found_new_match != FAIL) { if (got_int) break; /* Fill the popup menu as soon as possible. */ if (type != -1) ins_compl_check_keys(0); if ((ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE) || compl_interrupted) break; compl_started = TRUE; } else { /* Mark a buffer scanned when it has been scanned completely */ if (type == 0 || type == CTRL_X_PATH_PATTERNS) ins_buf->b_scanned = TRUE; compl_started = FALSE; } } compl_started = TRUE; if ((ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_WHOLE_LINE) && *e_cpt == NUL) /* Got to end of 'complete' */ found_new_match = FAIL; i = -1; /* total of matches, unknown */ if (found_new_match == FAIL || (ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE)) i = ins_compl_make_cyclic(); /* If several matches were added (FORWARD) or the search failed and has * just been made cyclic then we have to move compl_curr_match to the next * or previous entry (if any) -- Acevedo */ compl_curr_match = compl_direction == FORWARD ? old_match->cp_next : old_match->cp_prev; if (compl_curr_match == NULL) compl_curr_match = old_match; return i; } /* Delete the old text being completed. */ static void ins_compl_delete() { int i; /* * In insert mode: Delete the typed part. * In replace mode: Put the old characters back, if any. */ i = compl_col + (compl_cont_status & CONT_ADDING ? compl_length : 0); backspace_until_column(i); changed_cline_bef_curs(); } /* Insert the new text being completed. */ static void ins_compl_insert() { ins_bytes(compl_shown_match->cp_str + ins_compl_len()); if (compl_shown_match->cp_flags & ORIGINAL_TEXT) compl_used_match = FALSE; else compl_used_match = TRUE; } /* * Fill in the next completion in the current direction. * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to * get more completions. If it is FALSE, then we just do nothing when there * are no more completions in a given direction. The latter case is used when * we are still in the middle of finding completions, to allow browsing * through the ones found so far. * Return the total number of matches, or -1 if still unknown -- webb. * * compl_curr_match is currently being used by ins_compl_get_exp(), so we use * compl_shown_match here. * * Note that this function may be called recursively once only. First with * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn * calls this function with "allow_get_expansion" FALSE. */ static int ins_compl_next(allow_get_expansion, count, insert_match) int allow_get_expansion; int count; /* repeat completion this many times; should be at least 1 */ int insert_match; /* Insert the newly selected match */ { int num_matches = -1; int i; int todo = count; compl_T *found_compl = NULL; int found_end = FALSE; int advance; /* When user complete function return -1 for findstart which is next * time of 'always', compl_shown_match become NULL. */ if (compl_shown_match == NULL) return -1; if (compl_leader != NULL && (compl_shown_match->cp_flags & ORIGINAL_TEXT) == 0) { /* Set "compl_shown_match" to the actually shown match, it may differ * when "compl_leader" is used to omit some of the matches. */ while (!ins_compl_equal(compl_shown_match, compl_leader, (int)STRLEN(compl_leader)) && compl_shown_match->cp_next != NULL && compl_shown_match->cp_next != compl_first_match) compl_shown_match = compl_shown_match->cp_next; /* If we didn't find it searching forward, and compl_shows_dir is * backward, find the last match. */ if (compl_shows_dir == BACKWARD && !ins_compl_equal(compl_shown_match, compl_leader, (int)STRLEN(compl_leader)) && (compl_shown_match->cp_next == NULL || compl_shown_match->cp_next == compl_first_match)) { while (!ins_compl_equal(compl_shown_match, compl_leader, (int)STRLEN(compl_leader)) && compl_shown_match->cp_prev != NULL && compl_shown_match->cp_prev != compl_first_match) compl_shown_match = compl_shown_match->cp_prev; } } if (allow_get_expansion && insert_match && (!(compl_get_longest || compl_restarting) || compl_used_match)) /* Delete old text to be replaced */ ins_compl_delete(); /* When finding the longest common text we stick at the original text, * don't let CTRL-N or CTRL-P move to the first match. */ advance = count != 1 || !allow_get_expansion || !compl_get_longest; /* When restarting the search don't insert the first match either. */ if (compl_restarting) { advance = FALSE; compl_restarting = FALSE; } /* Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap * around. */ while (--todo >= 0) { if (compl_shows_dir == FORWARD && compl_shown_match->cp_next != NULL) { compl_shown_match = compl_shown_match->cp_next; found_end = (compl_first_match != NULL && (compl_shown_match->cp_next == compl_first_match || compl_shown_match == compl_first_match)); } else if (compl_shows_dir == BACKWARD && compl_shown_match->cp_prev != NULL) { found_end = (compl_shown_match == compl_first_match); compl_shown_match = compl_shown_match->cp_prev; found_end |= (compl_shown_match == compl_first_match); } else { if (!allow_get_expansion) { if (advance) { if (compl_shows_dir == BACKWARD) compl_pending -= todo + 1; else compl_pending += todo + 1; } return -1; } if (advance) { if (compl_shows_dir == BACKWARD) --compl_pending; else ++compl_pending; } /* Find matches. */ num_matches = ins_compl_get_exp(&compl_startpos); /* handle any pending completions */ while (compl_pending != 0 && compl_direction == compl_shows_dir && advance) { if (compl_pending > 0 && compl_shown_match->cp_next != NULL) { compl_shown_match = compl_shown_match->cp_next; --compl_pending; } if (compl_pending < 0 && compl_shown_match->cp_prev != NULL) { compl_shown_match = compl_shown_match->cp_prev; ++compl_pending; } else break; } found_end = FALSE; } if ((compl_shown_match->cp_flags & ORIGINAL_TEXT) == 0 && compl_leader != NULL && !ins_compl_equal(compl_shown_match, compl_leader, (int)STRLEN(compl_leader))) ++todo; else /* Remember a matching item. */ found_compl = compl_shown_match; /* Stop at the end of the list when we found a usable match. */ if (found_end) { if (found_compl != NULL) { compl_shown_match = found_compl; break; } todo = 1; /* use first usable match after wrapping around */ } } /* Insert the text of the new completion, or the compl_leader. */ if (insert_match) { if (!compl_get_longest || compl_used_match) ins_compl_insert(); else ins_bytes(compl_leader + ins_compl_len()); } else compl_used_match = FALSE; if (!allow_get_expansion) { /* may undisplay the popup menu first */ ins_compl_upd_pum(); /* redraw to show the user what was inserted */ update_screen(0); /* display the updated popup menu */ ins_compl_show_pum(); #ifdef FEAT_GUI if (gui.in_use) { /* Show the cursor after the match, not after the redrawn text. */ setcursor(); out_flush(); gui_update_cursor(FALSE, FALSE); } #endif /* Delete old text to be replaced, since we're still searching and * don't want to match ourselves! */ ins_compl_delete(); } /* Enter will select a match when the match wasn't inserted and the popup * menu is visible. */ compl_enter_selects = !insert_match && compl_match_array != NULL; /* * Show the file name for the match (if any) * Truncate the file name to avoid a wait for return. */ if (compl_shown_match->cp_fname != NULL) { STRCPY(IObuff, "match in file "); i = (vim_strsize(compl_shown_match->cp_fname) + 16) - sc_col; if (i <= 0) i = 0; else STRCAT(IObuff, "<"); STRCAT(IObuff, compl_shown_match->cp_fname + i); msg(IObuff); redraw_cmdline = FALSE; /* don't overwrite! */ } return num_matches; } /* * Call this while finding completions, to check whether the user has hit a key * that should change the currently displayed completion, or exit completion * mode. Also, when compl_pending is not zero, show a completion as soon as * possible. -- webb * "frequency" specifies out of how many calls we actually check. */ void ins_compl_check_keys(frequency) int frequency; { static int count = 0; int c; /* Don't check when reading keys from a script. That would break the test * scripts */ if (using_script()) return; /* Only do this at regular intervals */ if (++count < frequency) return; count = 0; /* Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key() * can't do its work correctly. */ c = vpeekc_any(); if (c != NUL) { if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R) { c = safe_vgetc(); /* Eat the character */ compl_shows_dir = ins_compl_key2dir(c); (void)ins_compl_next(FALSE, ins_compl_key2count(c), c != K_UP && c != K_DOWN); } else { /* Need to get the character to have KeyTyped set. We'll put it * back with vungetc() below. But skip K_IGNORE. */ c = safe_vgetc(); if (c != K_IGNORE) { /* Don't interrupt completion when the character wasn't typed, * e.g., when doing @q to replay keys. */ if (c != Ctrl_R && KeyTyped) compl_interrupted = TRUE; vungetc(c); } } } if (compl_pending != 0 && !got_int) { int todo = compl_pending > 0 ? compl_pending : -compl_pending; compl_pending = 0; (void)ins_compl_next(FALSE, todo, TRUE); } } /* * Decide the direction of Insert mode complete from the key typed. * Returns BACKWARD or FORWARD. */ static int ins_compl_key2dir(c) int c; { if (c == Ctrl_P || c == Ctrl_L || (pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP))) return BACKWARD; return FORWARD; } /* * Return TRUE for keys that are used for completion only when the popup menu * is visible. */ static int ins_compl_pum_key(c) int c; { return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN || c == K_UP || c == K_DOWN); } /* * Decide the number of completions to move forward. * Returns 1 for most keys, height of the popup menu for page-up/down keys. */ static int ins_compl_key2count(c) int c; { int h; if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN) { h = pum_get_height(); if (h > 3) h -= 2; /* keep some context */ return h; } return 1; } /* * Return TRUE if completion with "c" should insert the match, FALSE if only * to change the currently selected completion. */ static int ins_compl_use_match(c) int c; { switch (c) { case K_UP: case K_DOWN: case K_PAGEDOWN: case K_KPAGEDOWN: case K_S_DOWN: case K_PAGEUP: case K_KPAGEUP: case K_S_UP: return FALSE; } return TRUE; } /* * Do Insert mode completion. * Called when character "c" was typed, which has a meaning for completion. * Returns OK if completion was done, FAIL if something failed (out of mem). */ static int ins_complete(c) int c; { char_u *line; int startcol = 0; /* column where searched text starts */ colnr_T curs_col; /* cursor column */ int n; int save_w_wrow; compl_direction = ins_compl_key2dir(c); if (!compl_started) { /* First time we hit ^N or ^P (in a row, I mean) */ did_ai = FALSE; #ifdef FEAT_SMARTINDENT did_si = FALSE; can_si = FALSE; can_si_back = FALSE; #endif if (stop_arrow() == FAIL) return FAIL; line = ml_get(curwin->w_cursor.lnum); curs_col = curwin->w_cursor.col; compl_pending = 0; /* If this same ctrl_x_mode has been interrupted use the text from * "compl_startpos" to the cursor as a pattern to add a new word * instead of expand the one before the cursor, in word-wise if * "compl_startpos" is not in the same line as the cursor then fix it * (the line has been split because it was longer than 'tw'). if SOL * is set then skip the previous pattern, a word at the beginning of * the line has been inserted, we'll look for that -- Acevedo. */ if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT && compl_cont_mode == ctrl_x_mode) { /* * it is a continued search */ compl_cont_status &= ~CONT_INTRPT; /* remove INTRPT */ if (ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_PATH_PATTERNS || ctrl_x_mode == CTRL_X_PATH_DEFINES) { if (compl_startpos.lnum != curwin->w_cursor.lnum) { /* line (probably) wrapped, set compl_startpos to the * first non_blank in the line, if it is not a wordchar * include it to get a better pattern, but then we don't * want the "\\<" prefix, check it bellow */ compl_col = (colnr_T)(skipwhite(line) - line); compl_startpos.col = compl_col; compl_startpos.lnum = curwin->w_cursor.lnum; compl_cont_status &= ~CONT_SOL; /* clear SOL if present */ } else { /* S_IPOS was set when we inserted a word that was at the * beginning of the line, which means that we'll go to SOL * mode but first we need to redefine compl_startpos */ if (compl_cont_status & CONT_S_IPOS) { compl_cont_status |= CONT_SOL; compl_startpos.col = (colnr_T)(skipwhite( line + compl_length + compl_startpos.col) - line); } compl_col = compl_startpos.col; } compl_length = curwin->w_cursor.col - (int)compl_col; /* IObuff is used to add a "word from the next line" would we * have enough space? just being paranoid */ #define MIN_SPACE 75 if (compl_length > (IOSIZE - MIN_SPACE)) { compl_cont_status &= ~CONT_SOL; compl_length = (IOSIZE - MIN_SPACE); compl_col = curwin->w_cursor.col - compl_length; } compl_cont_status |= CONT_ADDING | CONT_N_ADDS; if (compl_length < 1) compl_cont_status &= CONT_LOCAL; } else if (ctrl_x_mode == CTRL_X_WHOLE_LINE) compl_cont_status = CONT_ADDING | CONT_N_ADDS; else compl_cont_status = 0; } else compl_cont_status &= CONT_LOCAL; if (!(compl_cont_status & CONT_ADDING)) /* normal expansion */ { compl_cont_mode = ctrl_x_mode; if (ctrl_x_mode != 0) /* Remove LOCAL if ctrl_x_mode != 0 */ compl_cont_status = 0; compl_cont_status |= CONT_N_ADDS; compl_startpos = curwin->w_cursor; startcol = (int)curs_col; compl_col = 0; } /* Work out completion pattern and original text -- webb */ if (ctrl_x_mode == 0 || (ctrl_x_mode & CTRL_X_WANT_IDENT)) { if ((compl_cont_status & CONT_SOL) || ctrl_x_mode == CTRL_X_PATH_DEFINES) { if (!(compl_cont_status & CONT_ADDING)) { while (--startcol >= 0 && vim_isIDc(line[startcol])) ; compl_col += ++startcol; compl_length = curs_col - startcol; } if (p_ic) compl_pattern = str_foldcase(line + compl_col, compl_length, NULL, 0); else compl_pattern = vim_strnsave(line + compl_col, compl_length); if (compl_pattern == NULL) return FAIL; } else if (compl_cont_status & CONT_ADDING) { char_u *prefix = (char_u *)"\\<"; /* we need up to 2 extra chars for the prefix */ compl_pattern = alloc(quote_meta(NULL, line + compl_col, compl_length) + 2); if (compl_pattern == NULL) return FAIL; if (!vim_iswordp(line + compl_col) || (compl_col > 0 && ( #ifdef FEAT_MBYTE vim_iswordp(mb_prevptr(line, line + compl_col)) #else vim_iswordc(line[compl_col - 1]) #endif ))) prefix = (char_u *)""; STRCPY((char *)compl_pattern, prefix); (void)quote_meta(compl_pattern + STRLEN(prefix), line + compl_col, compl_length); } else if (--startcol < 0 || #ifdef FEAT_MBYTE !vim_iswordp(mb_prevptr(line, line + startcol + 1)) #else !vim_iswordc(line[startcol]) #endif ) { /* Match any word of at least two chars */ compl_pattern = vim_strsave((char_u *)"\\<\\k\\k"); if (compl_pattern == NULL) return FAIL; compl_col += curs_col; compl_length = 0; } else { #ifdef FEAT_MBYTE /* Search the point of change class of multibyte character * or not a word single byte character backward. */ if (has_mbyte) { int base_class; int head_off; startcol -= (*mb_head_off)(line, line + startcol); base_class = mb_get_class(line + startcol); while (--startcol >= 0) { head_off = (*mb_head_off)(line, line + startcol); if (base_class != mb_get_class(line + startcol - head_off)) break; startcol -= head_off; } } else #endif while (--startcol >= 0 && vim_iswordc(line[startcol])) ; compl_col += ++startcol; compl_length = (int)curs_col - startcol; if (compl_length == 1) { /* Only match word with at least two chars -- webb * there's no need to call quote_meta, * alloc(7) is enough -- Acevedo */ compl_pattern = alloc(7); if (compl_pattern == NULL) return FAIL; STRCPY((char *)compl_pattern, "\\<"); (void)quote_meta(compl_pattern + 2, line + compl_col, 1); STRCAT((char *)compl_pattern, "\\k"); } else { compl_pattern = alloc(quote_meta(NULL, line + compl_col, compl_length) + 2); if (compl_pattern == NULL) return FAIL; STRCPY((char *)compl_pattern, "\\<"); (void)quote_meta(compl_pattern + 2, line + compl_col, compl_length); } } } else if (ctrl_x_mode == CTRL_X_WHOLE_LINE) { compl_col = (colnr_T)(skipwhite(line) - line); compl_length = (int)curs_col - (int)compl_col; if (compl_length < 0) /* cursor in indent: empty pattern */ compl_length = 0; if (p_ic) compl_pattern = str_foldcase(line + compl_col, compl_length, NULL, 0); else compl_pattern = vim_strnsave(line + compl_col, compl_length); if (compl_pattern == NULL) return FAIL; } else if (ctrl_x_mode == CTRL_X_FILES) { while (--startcol >= 0 && vim_isfilec(line[startcol])) ; compl_col += ++startcol; compl_length = (int)curs_col - startcol; compl_pattern = addstar(line + compl_col, compl_length, EXPAND_FILES); if (compl_pattern == NULL) return FAIL; } else if (ctrl_x_mode == CTRL_X_CMDLINE) { compl_pattern = vim_strnsave(line, curs_col); if (compl_pattern == NULL) return FAIL; set_cmd_context(&compl_xp, compl_pattern, (int)STRLEN(compl_pattern), curs_col); if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL || compl_xp.xp_context == EXPAND_NOTHING) /* No completion possible, use an empty pattern to get a * "pattern not found" message. */ compl_col = curs_col; else compl_col = (int)(compl_xp.xp_pattern - compl_pattern); compl_length = curs_col - compl_col; } else if (ctrl_x_mode == CTRL_X_FUNCTION || ctrl_x_mode == CTRL_X_OMNI) { #ifdef FEAT_COMPL_FUNC /* * Call user defined function 'completefunc' with "a:findstart" * set to 1 to obtain the length of text to use for completion. */ char_u *args[2]; int col; char_u *funcname; pos_T pos; win_T *curwin_save; buf_T *curbuf_save; /* Call 'completefunc' or 'omnifunc' and get pattern length as a * string */ funcname = ctrl_x_mode == CTRL_X_FUNCTION ? curbuf->b_p_cfu : curbuf->b_p_ofu; if (*funcname == NUL) { EMSG2(_(e_notset), ctrl_x_mode == CTRL_X_FUNCTION ? "completefunc" : "omnifunc"); return FAIL; } args[0] = (char_u *)"1"; args[1] = NULL; pos = curwin->w_cursor; curwin_save = curwin; curbuf_save = curbuf; col = call_func_retnr(funcname, 2, args, FALSE); if (curwin_save != curwin || curbuf_save != curbuf) { EMSG(_(e_complwin)); return FAIL; } curwin->w_cursor = pos; /* restore the cursor position */ check_cursor(); if (!equalpos(curwin->w_cursor, pos)) { EMSG(_(e_compldel)); return FAIL; } /* Return value -2 means the user complete function wants to * cancel the complete without an error. * Return value -3 does the same as -2 and leaves CTRL-X mode.*/ if (col == -2) return FAIL; if (col == -3) { ctrl_x_mode = 0; edit_submode = NULL; msg_clr_cmdline(); return FAIL; } /* * Reset extended parameters of completion, when start new * completion. */ compl_opt_refresh_always = FALSE; if (col < 0) col = curs_col; compl_col = col; if (compl_col > curs_col) compl_col = curs_col; /* Setup variables for completion. Need to obtain "line" again, * it may have become invalid. */ line = ml_get(curwin->w_cursor.lnum); compl_length = curs_col - compl_col; compl_pattern = vim_strnsave(line + compl_col, compl_length); if (compl_pattern == NULL) #endif return FAIL; } else if (ctrl_x_mode == CTRL_X_SPELL) { #ifdef FEAT_SPELL if (spell_bad_len > 0) compl_col = curs_col - spell_bad_len; else compl_col = spell_word_start(startcol); if (compl_col >= (colnr_T)startcol) { compl_length = 0; compl_col = curs_col; } else { spell_expand_check_cap(compl_col); compl_length = (int)curs_col - compl_col; } /* Need to obtain "line" again, it may have become invalid. */ line = ml_get(curwin->w_cursor.lnum); compl_pattern = vim_strnsave(line + compl_col, compl_length); if (compl_pattern == NULL) #endif return FAIL; } else { EMSG2(_(e_intern2), "ins_complete()"); return FAIL; } if (compl_cont_status & CONT_ADDING) { edit_submode_pre = (char_u *)_(" Adding"); if (ctrl_x_mode == CTRL_X_WHOLE_LINE) { /* Insert a new line, keep indentation but ignore 'comments' */ #ifdef FEAT_COMMENTS char_u *old = curbuf->b_p_com; curbuf->b_p_com = (char_u *)""; #endif compl_startpos.lnum = curwin->w_cursor.lnum; compl_startpos.col = compl_col; ins_eol('\r'); #ifdef FEAT_COMMENTS curbuf->b_p_com = old; #endif compl_length = 0; compl_col = curwin->w_cursor.col; } } else { edit_submode_pre = NULL; compl_startpos.col = compl_col; } if (compl_cont_status & CONT_LOCAL) edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]); else edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode)); /* If any of the original typed text has been changed we need to fix * the redo buffer. */ ins_compl_fixRedoBufForLeader(NULL); /* Always add completion for the original text. */ vim_free(compl_orig_text); compl_orig_text = vim_strnsave(line + compl_col, compl_length); if (compl_orig_text == NULL || ins_compl_add(compl_orig_text, -1, p_ic, NULL, NULL, 0, ORIGINAL_TEXT, FALSE) != OK) { vim_free(compl_pattern); compl_pattern = NULL; vim_free(compl_orig_text); compl_orig_text = NULL; return FAIL; } /* showmode might reset the internal line pointers, so it must * be called before line = ml_get(), or when this address is no * longer needed. -- Acevedo. */ edit_submode_extra = (char_u *)_("-- Searching..."); edit_submode_highl = HLF_COUNT; showmode(); edit_submode_extra = NULL; out_flush(); } compl_shown_match = compl_curr_match; compl_shows_dir = compl_direction; /* * Find next match (and following matches). */ save_w_wrow = curwin->w_wrow; n = ins_compl_next(TRUE, ins_compl_key2count(c), ins_compl_use_match(c)); /* may undisplay the popup menu */ ins_compl_upd_pum(); if (n > 1) /* all matches have been found */ compl_matches = n; compl_curr_match = compl_shown_match; compl_direction = compl_shows_dir; /* Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert * mode. */ if (got_int && !global_busy) { (void)vgetc(); got_int = FALSE; } /* we found no match if the list has only the "compl_orig_text"-entry */ if (compl_first_match == compl_first_match->cp_next) { edit_submode_extra = (compl_cont_status & CONT_ADDING) && compl_length > 1 ? (char_u *)_(e_hitend) : (char_u *)_(e_patnotf); edit_submode_highl = HLF_E; /* remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode, * because we couldn't expand anything at first place, but if we used * ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word * (such as M in M'exico) if not tried already. -- Acevedo */ if ( compl_length > 1 || (compl_cont_status & CONT_ADDING) || (ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_PATH_PATTERNS && ctrl_x_mode != CTRL_X_PATH_DEFINES)) compl_cont_status &= ~CONT_N_ADDS; } if (compl_curr_match->cp_flags & CONT_S_IPOS) compl_cont_status |= CONT_S_IPOS; else compl_cont_status &= ~CONT_S_IPOS; if (edit_submode_extra == NULL) { if (compl_curr_match->cp_flags & ORIGINAL_TEXT) { edit_submode_extra = (char_u *)_("Back at original"); edit_submode_highl = HLF_W; } else if (compl_cont_status & CONT_S_IPOS) { edit_submode_extra = (char_u *)_("Word from other line"); edit_submode_highl = HLF_COUNT; } else if (compl_curr_match->cp_next == compl_curr_match->cp_prev) { edit_submode_extra = (char_u *)_("The only match"); edit_submode_highl = HLF_COUNT; } else { /* Update completion sequence number when needed. */ if (compl_curr_match->cp_number == -1) { int number = 0; compl_T *match; if (compl_direction == FORWARD) { /* search backwards for the first valid (!= -1) number. * This should normally succeed already at the first loop * cycle, so it's fast! */ for (match = compl_curr_match->cp_prev; match != NULL && match != compl_first_match; match = match->cp_prev) if (match->cp_number != -1) { number = match->cp_number; break; } if (match != NULL) /* go up and assign all numbers which are not assigned * yet */ for (match = match->cp_next; match != NULL && match->cp_number == -1; match = match->cp_next) match->cp_number = ++number; } else /* BACKWARD */ { /* search forwards (upwards) for the first valid (!= -1) * number. This should normally succeed already at the * first loop cycle, so it's fast! */ for (match = compl_curr_match->cp_next; match != NULL && match != compl_first_match; match = match->cp_next) if (match->cp_number != -1) { number = match->cp_number; break; } if (match != NULL) /* go down and assign all numbers which are not * assigned yet */ for (match = match->cp_prev; match && match->cp_number == -1; match = match->cp_prev) match->cp_number = ++number; } } /* The match should always have a sequence number now, this is * just a safety check. */ if (compl_curr_match->cp_number != -1) { /* Space for 10 text chars. + 2x10-digit no.s = 31. * Translations may need more than twice that. */ static char_u match_ref[81]; if (compl_matches > 0) vim_snprintf((char *)match_ref, sizeof(match_ref), _("match %d of %d"), compl_curr_match->cp_number, compl_matches); else vim_snprintf((char *)match_ref, sizeof(match_ref), _("match %d"), compl_curr_match->cp_number); edit_submode_extra = match_ref; edit_submode_highl = HLF_R; if (dollar_vcol >= 0) curs_columns(FALSE); } } } /* Show a message about what (completion) mode we're in. */ showmode(); if (edit_submode_extra != NULL) { if (!p_smd) msg_attr(edit_submode_extra, edit_submode_highl < HLF_COUNT ? hl_attr(edit_submode_highl) : 0); } else msg_clr_cmdline(); /* necessary for "noshowmode" */ /* Show the popup menu, unless we got interrupted. */ if (!compl_interrupted) { /* RedrawingDisabled may be set when invoked through complete(). */ n = RedrawingDisabled; RedrawingDisabled = 0; /* If the cursor moved we need to remove the pum first. */ setcursor(); if (save_w_wrow != curwin->w_wrow) ins_compl_del_pum(); ins_compl_show_pum(); setcursor(); RedrawingDisabled = n; } compl_was_interrupted = compl_interrupted; compl_interrupted = FALSE; return OK; } /* * Looks in the first "len" chars. of "src" for search-metachars. * If dest is not NULL the chars. are copied there quoting (with * a backslash) the metachars, and dest would be NUL terminated. * Returns the length (needed) of dest */ static unsigned quote_meta(dest, src, len) char_u *dest; char_u *src; int len; { unsigned m = (unsigned)len + 1; /* one extra for the NUL */ for ( ; --len >= 0; src++) { switch (*src) { case '.': case '*': case '[': if (ctrl_x_mode == CTRL_X_DICTIONARY || ctrl_x_mode == CTRL_X_THESAURUS) break; case '~': if (!p_magic) /* quote these only if magic is set */ break; case '\\': if (ctrl_x_mode == CTRL_X_DICTIONARY || ctrl_x_mode == CTRL_X_THESAURUS) break; case '^': /* currently it's not needed. */ case '$': m++; if (dest != NULL) *dest++ = '\\'; break; } if (dest != NULL) *dest++ = *src; # ifdef FEAT_MBYTE /* Copy remaining bytes of a multibyte character. */ if (has_mbyte) { int i, mb_len; mb_len = (*mb_ptr2len)(src) - 1; if (mb_len > 0 && len >= mb_len) for (i = 0; i < mb_len; ++i) { --len; ++src; if (dest != NULL) *dest++ = *src; } } # endif } if (dest != NULL) *dest = NUL; return m; } #endif /* FEAT_INS_EXPAND */ /* * Next character is interpreted literally. * A one, two or three digit decimal number is interpreted as its byte value. * If one or two digits are entered, the next character is given to vungetc(). * For Unicode a character > 255 may be returned. */ int get_literal() { int cc; int nc; int i; int hex = FALSE; int octal = FALSE; #ifdef FEAT_MBYTE int unicode = 0; #endif if (got_int) return Ctrl_C; #ifdef FEAT_GUI /* * In GUI there is no point inserting the internal code for a special key. * It is more useful to insert the string "<KEY>" instead. This would * probably be useful in a text window too, but it would not be * vi-compatible (maybe there should be an option for it?) -- webb */ if (gui.in_use) ++allow_keys; #endif #ifdef USE_ON_FLY_SCROLL dont_scroll = TRUE; /* disallow scrolling here */ #endif ++no_mapping; /* don't map the next key hits */ cc = 0; i = 0; for (;;) { nc = plain_vgetc(); #ifdef FEAT_CMDL_INFO if (!(State & CMDLINE) # ifdef FEAT_MBYTE && MB_BYTE2LEN_CHECK(nc) == 1 # endif ) add_to_showcmd(nc); #endif if (nc == 'x' || nc == 'X') hex = TRUE; else if (nc == 'o' || nc == 'O') octal = TRUE; #ifdef FEAT_MBYTE else if (nc == 'u' || nc == 'U') unicode = nc; #endif else { if (hex #ifdef FEAT_MBYTE || unicode != 0 #endif ) { if (!vim_isxdigit(nc)) break; cc = cc * 16 + hex2nr(nc); } else if (octal) { if (nc < '0' || nc > '7') break; cc = cc * 8 + nc - '0'; } else { if (!VIM_ISDIGIT(nc)) break; cc = cc * 10 + nc - '0'; } ++i; } if (cc > 255 #ifdef FEAT_MBYTE && unicode == 0 #endif ) cc = 255; /* limit range to 0-255 */ nc = 0; if (hex) /* hex: up to two chars */ { if (i >= 2) break; } #ifdef FEAT_MBYTE else if (unicode) /* Unicode: up to four or eight chars */ { if ((unicode == 'u' && i >= 4) || (unicode == 'U' && i >= 8)) break; } #endif else if (i >= 3) /* decimal or octal: up to three chars */ break; } if (i == 0) /* no number entered */ { if (nc == K_ZERO) /* NUL is stored as NL */ { cc = '\n'; nc = 0; } else { cc = nc; nc = 0; } } if (cc == 0) /* NUL is stored as NL */ cc = '\n'; #ifdef FEAT_MBYTE if (enc_dbcs && (cc & 0xff) == 0) cc = '?'; /* don't accept an illegal DBCS char, the NUL in the second byte will cause trouble! */ #endif --no_mapping; #ifdef FEAT_GUI if (gui.in_use) --allow_keys; #endif if (nc) vungetc(nc); got_int = FALSE; /* CTRL-C typed after CTRL-V is not an interrupt */ return cc; } /* * Insert character, taking care of special keys and mod_mask */ static void insert_special(c, allow_modmask, ctrlv) int c; int allow_modmask; int ctrlv; /* c was typed after CTRL-V */ { char_u *p; int len; /* * Special function key, translate into "<Key>". Up to the last '>' is * inserted with ins_str(), so as not to replace characters in replace * mode. * Only use mod_mask for special keys, to avoid things like <S-Space>, * unless 'allow_modmask' is TRUE. */ #ifdef MACOS /* Command-key never produces a normal key */ if (mod_mask & MOD_MASK_CMD) allow_modmask = TRUE; #endif if (IS_SPECIAL(c) || (mod_mask && allow_modmask)) { p = get_special_key_name(c, mod_mask); len = (int)STRLEN(p); c = p[len - 1]; if (len > 2) { if (stop_arrow() == FAIL) return; p[len - 1] = NUL; ins_str(p); AppendToRedobuffLit(p, -1); ctrlv = FALSE; } } if (stop_arrow() == OK) insertchar(c, ctrlv ? INSCHAR_CTRLV : 0, -1); } /* * Special characters in this context are those that need processing other * than the simple insertion that can be performed here. This includes ESC * which terminates the insert, and CR/NL which need special processing to * open up a new line. This routine tries to optimize insertions performed by * the "redo", "undo" or "put" commands, so it needs to know when it should * stop and defer processing to the "normal" mechanism. * '0' and '^' are special, because they can be followed by CTRL-D. */ #ifdef EBCDIC # define ISSPECIAL(c) ((c) < ' ' || (c) == '0' || (c) == '^') #else # define ISSPECIAL(c) ((c) < ' ' || (c) >= DEL || (c) == '0' || (c) == '^') #endif #ifdef FEAT_MBYTE # define WHITECHAR(cc) (vim_iswhite(cc) && (!enc_utf8 || !utf_iscomposing(utf_ptr2char(ml_get_cursor() + 1)))) #else # define WHITECHAR(cc) vim_iswhite(cc) #endif /* * "flags": INSCHAR_FORMAT - force formatting * INSCHAR_CTRLV - char typed just after CTRL-V * INSCHAR_NO_FEX - don't use 'formatexpr' * * NOTE: passes the flags value straight through to internal_format() which, * beside INSCHAR_FORMAT (above), is also looking for these: * INSCHAR_DO_COM - format comments * INSCHAR_COM_LIST - format comments with num list or 2nd line indent */ void insertchar(c, flags, second_indent) int c; /* character to insert or NUL */ int flags; /* INSCHAR_FORMAT, etc. */ int second_indent; /* indent for second line if >= 0 */ { int textwidth; #ifdef FEAT_COMMENTS char_u *p; #endif int fo_ins_blank; textwidth = comp_textwidth(flags & INSCHAR_FORMAT); fo_ins_blank = has_format_option(FO_INS_BLANK); /* * Try to break the line in two or more pieces when: * - Always do this if we have been called to do formatting only. * - Always do this when 'formatoptions' has the 'a' flag and the line * ends in white space. * - Otherwise: * - Don't do this if inserting a blank * - Don't do this if an existing character is being replaced, unless * we're in VREPLACE mode. * - Do this if the cursor is not on the line where insert started * or - 'formatoptions' doesn't have 'l' or the line was not too long * before the insert. * - 'formatoptions' doesn't have 'b' or a blank was inserted at or * before 'textwidth' */ if (textwidth > 0 && ((flags & INSCHAR_FORMAT) || (!vim_iswhite(c) && !((State & REPLACE_FLAG) #ifdef FEAT_VREPLACE && !(State & VREPLACE_FLAG) #endif && *ml_get_cursor() != NUL) && (curwin->w_cursor.lnum != Insstart.lnum || ((!has_format_option(FO_INS_LONG) || Insstart_textlen <= (colnr_T)textwidth) && (!fo_ins_blank || Insstart_blank_vcol <= (colnr_T)textwidth )))))) { /* Format with 'formatexpr' when it's set. Use internal formatting * when 'formatexpr' isn't set or it returns non-zero. */ #if defined(FEAT_EVAL) int do_internal = TRUE; if (*curbuf->b_p_fex != NUL && (flags & INSCHAR_NO_FEX) == 0) { do_internal = (fex_format(curwin->w_cursor.lnum, 1L, c) != 0); /* It may be required to save for undo again, e.g. when setline() * was called. */ ins_need_undo = TRUE; } if (do_internal) #endif internal_format(textwidth, second_indent, flags, c == NUL, c); } if (c == NUL) /* only formatting was wanted */ return; #ifdef FEAT_COMMENTS /* Check whether this character should end a comment. */ if (did_ai && (int)c == end_comment_pending) { char_u *line; char_u lead_end[COM_MAX_LEN]; /* end-comment string */ int middle_len, end_len; int i; /* * Need to remove existing (middle) comment leader and insert end * comment leader. First, check what comment leader we can find. */ i = get_leader_len(line = ml_get_curline(), &p, FALSE, TRUE); if (i > 0 && vim_strchr(p, COM_MIDDLE) != NULL) /* Just checking */ { /* Skip middle-comment string */ while (*p && p[-1] != ':') /* find end of middle flags */ ++p; middle_len = copy_option_part(&p, lead_end, COM_MAX_LEN, ","); /* Don't count trailing white space for middle_len */ while (middle_len > 0 && vim_iswhite(lead_end[middle_len - 1])) --middle_len; /* Find the end-comment string */ while (*p && p[-1] != ':') /* find end of end flags */ ++p; end_len = copy_option_part(&p, lead_end, COM_MAX_LEN, ","); /* Skip white space before the cursor */ i = curwin->w_cursor.col; while (--i >= 0 && vim_iswhite(line[i])) ; i++; /* Skip to before the middle leader */ i -= middle_len; /* Check some expected things before we go on */ if (i >= 0 && lead_end[end_len - 1] == end_comment_pending) { /* Backspace over all the stuff we want to replace */ backspace_until_column(i); /* * Insert the end-comment string, except for the last * character, which will get inserted as normal later. */ ins_bytes_len(lead_end, end_len - 1); } } } end_comment_pending = NUL; #endif did_ai = FALSE; #ifdef FEAT_SMARTINDENT did_si = FALSE; can_si = FALSE; can_si_back = FALSE; #endif /* * If there's any pending input, grab up to INPUT_BUFLEN at once. * This speeds up normal text input considerably. * Don't do this when 'cindent' or 'indentexpr' is set, because we might * need to re-indent at a ':', or any other character (but not what * 'paste' is set).. * Don't do this when there an InsertCharPre autocommand is defined, * because we need to fire the event for every character. */ #ifdef USE_ON_FLY_SCROLL dont_scroll = FALSE; /* allow scrolling here */ #endif if ( !ISSPECIAL(c) #ifdef FEAT_MBYTE && (!has_mbyte || (*mb_char2len)(c) == 1) #endif && vpeekc() != NUL && !(State & REPLACE_FLAG) #ifdef FEAT_CINDENT && !cindent_on() #endif #ifdef FEAT_RIGHTLEFT && !p_ri #endif #ifdef FEAT_AUTOCMD && !has_insertcharpre() #endif ) { #define INPUT_BUFLEN 100 char_u buf[INPUT_BUFLEN + 1]; int i; colnr_T virtcol = 0; buf[0] = c; i = 1; if (textwidth > 0) virtcol = get_nolist_virtcol(); /* * Stop the string when: * - no more chars available * - finding a special character (command key) * - buffer is full * - running into the 'textwidth' boundary * - need to check for abbreviation: A non-word char after a word-char */ while ( (c = vpeekc()) != NUL && !ISSPECIAL(c) #ifdef FEAT_MBYTE && (!has_mbyte || MB_BYTE2LEN_CHECK(c) == 1) #endif && i < INPUT_BUFLEN && (textwidth == 0 || (virtcol += byte2cells(buf[i - 1])) < (colnr_T)textwidth) && !(!no_abbr && !vim_iswordc(c) && vim_iswordc(buf[i - 1]))) { #ifdef FEAT_RIGHTLEFT c = vgetc(); if (p_hkmap && KeyTyped) c = hkmap(c); /* Hebrew mode mapping */ # ifdef FEAT_FKMAP if (p_fkmap && KeyTyped) c = fkmap(c); /* Farsi mode mapping */ # endif buf[i++] = c; #else buf[i++] = vgetc(); #endif } #ifdef FEAT_DIGRAPHS do_digraph(-1); /* clear digraphs */ do_digraph(buf[i-1]); /* may be the start of a digraph */ #endif buf[i] = NUL; ins_str(buf); if (flags & INSCHAR_CTRLV) { redo_literal(*buf); i = 1; } else i = 0; if (buf[i] != NUL) AppendToRedobuffLit(buf + i, -1); } else { #ifdef FEAT_MBYTE int cc; if (has_mbyte && (cc = (*mb_char2len)(c)) > 1) { char_u buf[MB_MAXBYTES + 1]; (*mb_char2bytes)(c, buf); buf[cc] = NUL; ins_char_bytes(buf, cc); AppendCharToRedobuff(c); } else #endif { ins_char(c); if (flags & INSCHAR_CTRLV) redo_literal(c); else AppendCharToRedobuff(c); } } } /* * Format text at the current insert position. * * If the INSCHAR_COM_LIST flag is present, then the value of second_indent * will be the comment leader length sent to open_line(). */ static void internal_format(textwidth, second_indent, flags, format_only, c) int textwidth; int second_indent; int flags; int format_only; int c; /* character to be inserted (can be NUL) */ { int cc; int save_char = NUL; int haveto_redraw = FALSE; int fo_ins_blank = has_format_option(FO_INS_BLANK); #ifdef FEAT_MBYTE int fo_multibyte = has_format_option(FO_MBYTE_BREAK); #endif int fo_white_par = has_format_option(FO_WHITE_PAR); int first_line = TRUE; #ifdef FEAT_COMMENTS colnr_T leader_len; int no_leader = FALSE; int do_comments = (flags & INSCHAR_DO_COM); #endif /* * When 'ai' is off we don't want a space under the cursor to be * deleted. Replace it with an 'x' temporarily. */ if (!curbuf->b_p_ai #ifdef FEAT_VREPLACE && !(State & VREPLACE_FLAG) #endif ) { cc = gchar_cursor(); if (vim_iswhite(cc)) { save_char = cc; pchar_cursor('x'); } } /* * Repeat breaking lines, until the current line is not too long. */ while (!got_int) { int startcol; /* Cursor column at entry */ int wantcol; /* column at textwidth border */ int foundcol; /* column for start of spaces */ int end_foundcol = 0; /* column for start of word */ colnr_T len; colnr_T virtcol; #ifdef FEAT_VREPLACE int orig_col = 0; char_u *saved_text = NULL; #endif colnr_T col; colnr_T end_col; virtcol = get_nolist_virtcol() + char2cells(c != NUL ? c : gchar_cursor()); if (virtcol <= (colnr_T)textwidth) break; #ifdef FEAT_COMMENTS if (no_leader) do_comments = FALSE; else if (!(flags & INSCHAR_FORMAT) && has_format_option(FO_WRAP_COMS)) do_comments = TRUE; /* Don't break until after the comment leader */ if (do_comments) leader_len = get_leader_len(ml_get_curline(), NULL, FALSE, TRUE); else leader_len = 0; /* If the line doesn't start with a comment leader, then don't * start one in a following broken line. Avoids that a %word * moved to the start of the next line causes all following lines * to start with %. */ if (leader_len == 0) no_leader = TRUE; #endif if (!(flags & INSCHAR_FORMAT) #ifdef FEAT_COMMENTS && leader_len == 0 #endif && !has_format_option(FO_WRAP)) break; if ((startcol = curwin->w_cursor.col) == 0) break; /* find column of textwidth border */ coladvance((colnr_T)textwidth); wantcol = curwin->w_cursor.col; curwin->w_cursor.col = startcol; foundcol = 0; /* * Find position to break at. * Stop at first entered white when 'formatoptions' has 'v' */ while ((!fo_ins_blank && !has_format_option(FO_INS_VI)) || (flags & INSCHAR_FORMAT) || curwin->w_cursor.lnum != Insstart.lnum || curwin->w_cursor.col >= Insstart.col) { if (curwin->w_cursor.col == startcol && c != NUL) cc = c; else cc = gchar_cursor(); if (WHITECHAR(cc)) { /* remember position of blank just before text */ end_col = curwin->w_cursor.col; /* find start of sequence of blanks */ while (curwin->w_cursor.col > 0 && WHITECHAR(cc)) { dec_cursor(); cc = gchar_cursor(); } if (curwin->w_cursor.col == 0 && WHITECHAR(cc)) break; /* only spaces in front of text */ #ifdef FEAT_COMMENTS /* Don't break until after the comment leader */ if (curwin->w_cursor.col < leader_len) break; #endif if (has_format_option(FO_ONE_LETTER)) { /* do not break after one-letter words */ if (curwin->w_cursor.col == 0) break; /* one-letter word at begin */ #ifdef FEAT_COMMENTS /* do not break "#a b" when 'tw' is 2 */ if (curwin->w_cursor.col <= leader_len) break; #endif col = curwin->w_cursor.col; dec_cursor(); cc = gchar_cursor(); if (WHITECHAR(cc)) continue; /* one-letter, continue */ curwin->w_cursor.col = col; } inc_cursor(); end_foundcol = end_col + 1; foundcol = curwin->w_cursor.col; if (curwin->w_cursor.col <= (colnr_T)wantcol) break; } #ifdef FEAT_MBYTE else if (cc >= 0x100 && fo_multibyte) { /* Break after or before a multi-byte character. */ if (curwin->w_cursor.col != startcol) { #ifdef FEAT_COMMENTS /* Don't break until after the comment leader */ if (curwin->w_cursor.col < leader_len) break; #endif col = curwin->w_cursor.col; inc_cursor(); /* Don't change end_foundcol if already set. */ if (foundcol != curwin->w_cursor.col) { foundcol = curwin->w_cursor.col; end_foundcol = foundcol; if (curwin->w_cursor.col <= (colnr_T)wantcol) break; } curwin->w_cursor.col = col; } if (curwin->w_cursor.col == 0) break; col = curwin->w_cursor.col; dec_cursor(); cc = gchar_cursor(); if (WHITECHAR(cc)) continue; /* break with space */ #ifdef FEAT_COMMENTS /* Don't break until after the comment leader */ if (curwin->w_cursor.col < leader_len) break; #endif curwin->w_cursor.col = col; foundcol = curwin->w_cursor.col; end_foundcol = foundcol; if (curwin->w_cursor.col <= (colnr_T)wantcol) break; } #endif if (curwin->w_cursor.col == 0) break; dec_cursor(); } if (foundcol == 0) /* no spaces, cannot break line */ { curwin->w_cursor.col = startcol; break; } /* Going to break the line, remove any "$" now. */ undisplay_dollar(); /* * Offset between cursor position and line break is used by replace * stack functions. VREPLACE does not use this, and backspaces * over the text instead. */ #ifdef FEAT_VREPLACE if (State & VREPLACE_FLAG) orig_col = startcol; /* Will start backspacing from here */ else #endif replace_offset = startcol - end_foundcol; /* * adjust startcol for spaces that will be deleted and * characters that will remain on top line */ curwin->w_cursor.col = foundcol; while ((cc = gchar_cursor(), WHITECHAR(cc)) && (!fo_white_par || curwin->w_cursor.col < startcol)) inc_cursor(); startcol -= curwin->w_cursor.col; if (startcol < 0) startcol = 0; #ifdef FEAT_VREPLACE if (State & VREPLACE_FLAG) { /* * In VREPLACE mode, we will backspace over the text to be * wrapped, so save a copy now to put on the next line. */ saved_text = vim_strsave(ml_get_cursor()); curwin->w_cursor.col = orig_col; if (saved_text == NULL) break; /* Can't do it, out of memory */ saved_text[startcol] = NUL; /* Backspace over characters that will move to the next line */ if (!fo_white_par) backspace_until_column(foundcol); } else #endif { /* put cursor after pos. to break line */ if (!fo_white_par) curwin->w_cursor.col = foundcol; } /* * Split the line just before the margin. * Only insert/delete lines, but don't really redraw the window. */ open_line(FORWARD, OPENLINE_DELSPACES + OPENLINE_MARKFIX + (fo_white_par ? OPENLINE_KEEPTRAIL : 0) #ifdef FEAT_COMMENTS + (do_comments ? OPENLINE_DO_COM : 0) + ((flags & INSCHAR_COM_LIST) ? OPENLINE_COM_LIST : 0) #endif , ((flags & INSCHAR_COM_LIST) ? second_indent : old_indent)); if (!(flags & INSCHAR_COM_LIST)) old_indent = 0; replace_offset = 0; if (first_line) { if (!(flags & INSCHAR_COM_LIST)) { /* * This section is for numeric lists w/o comments. If comment * indents are needed with numeric lists (formatoptions=nq), * then the INSCHAR_COM_LIST flag will cause the corresponding * OPENLINE_COM_LIST flag to be passed through to open_line() * (as seen above)... */ if (second_indent < 0 && has_format_option(FO_Q_NUMBER)) second_indent = get_number_indent(curwin->w_cursor.lnum -1); if (second_indent >= 0) { #ifdef FEAT_VREPLACE if (State & VREPLACE_FLAG) change_indent(INDENT_SET, second_indent, FALSE, NUL, TRUE); else #endif (void)set_indent(second_indent, SIN_CHANGED); } } first_line = FALSE; } #ifdef FEAT_VREPLACE if (State & VREPLACE_FLAG) { /* * In VREPLACE mode we have backspaced over the text to be * moved, now we re-insert it into the new line. */ ins_bytes(saved_text); vim_free(saved_text); } else #endif { /* * Check if cursor is not past the NUL off the line, cindent * may have added or removed indent. */ curwin->w_cursor.col += startcol; len = (colnr_T)STRLEN(ml_get_curline()); if (curwin->w_cursor.col > len) curwin->w_cursor.col = len; } haveto_redraw = TRUE; #ifdef FEAT_CINDENT can_cindent = TRUE; #endif /* moved the cursor, don't autoindent or cindent now */ did_ai = FALSE; #ifdef FEAT_SMARTINDENT did_si = FALSE; can_si = FALSE; can_si_back = FALSE; #endif line_breakcheck(); } if (save_char != NUL) /* put back space after cursor */ pchar_cursor(save_char); if (!format_only && haveto_redraw) { update_topline(); redraw_curbuf_later(VALID); } } /* * Called after inserting or deleting text: When 'formatoptions' includes the * 'a' flag format from the current line until the end of the paragraph. * Keep the cursor at the same position relative to the text. * The caller must have saved the cursor line for undo, following ones will be * saved here. */ void auto_format(trailblank, prev_line) int trailblank; /* when TRUE also format with trailing blank */ int prev_line; /* may start in previous line */ { pos_T pos; colnr_T len; char_u *old; char_u *new, *pnew; int wasatend; int cc; if (!has_format_option(FO_AUTO)) return; pos = curwin->w_cursor; old = ml_get_curline(); /* may remove added space */ check_auto_format(FALSE); /* Don't format in Insert mode when the cursor is on a trailing blank, the * user might insert normal text next. Also skip formatting when "1" is * in 'formatoptions' and there is a single character before the cursor. * Otherwise the line would be broken and when typing another non-white * next they are not joined back together. */ wasatend = (pos.col == (colnr_T)STRLEN(old)); if (*old != NUL && !trailblank && wasatend) { dec_cursor(); cc = gchar_cursor(); if (!WHITECHAR(cc) && curwin->w_cursor.col > 0 && has_format_option(FO_ONE_LETTER)) dec_cursor(); cc = gchar_cursor(); if (WHITECHAR(cc)) { curwin->w_cursor = pos; return; } curwin->w_cursor = pos; } #ifdef FEAT_COMMENTS /* With the 'c' flag in 'formatoptions' and 't' missing: only format * comments. */ if (has_format_option(FO_WRAP_COMS) && !has_format_option(FO_WRAP) && get_leader_len(old, NULL, FALSE, TRUE) == 0) return; #endif /* * May start formatting in a previous line, so that after "x" a word is * moved to the previous line if it fits there now. Only when this is not * the start of a paragraph. */ if (prev_line && !paragraph_start(curwin->w_cursor.lnum)) { --curwin->w_cursor.lnum; if (u_save_cursor() == FAIL) return; } /* * Do the formatting and restore the cursor position. "saved_cursor" will * be adjusted for the text formatting. */ saved_cursor = pos; format_lines((linenr_T)-1, FALSE); curwin->w_cursor = saved_cursor; saved_cursor.lnum = 0; if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) { /* "cannot happen" */ curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; coladvance((colnr_T)MAXCOL); } else check_cursor_col(); /* Insert mode: If the cursor is now after the end of the line while it * previously wasn't, the line was broken. Because of the rule above we * need to add a space when 'w' is in 'formatoptions' to keep a paragraph * formatted. */ if (!wasatend && has_format_option(FO_WHITE_PAR)) { new = ml_get_curline(); len = (colnr_T)STRLEN(new); if (curwin->w_cursor.col == len) { pnew = vim_strnsave(new, len + 2); pnew[len] = ' '; pnew[len + 1] = NUL; ml_replace(curwin->w_cursor.lnum, pnew, FALSE); /* remove the space later */ did_add_space = TRUE; } else /* may remove added space */ check_auto_format(FALSE); } check_cursor(); } /* * When an extra space was added to continue a paragraph for auto-formatting, * delete it now. The space must be under the cursor, just after the insert * position. */ static void check_auto_format(end_insert) int end_insert; /* TRUE when ending Insert mode */ { int c = ' '; int cc; if (did_add_space) { cc = gchar_cursor(); if (!WHITECHAR(cc)) /* Somehow the space was removed already. */ did_add_space = FALSE; else { if (!end_insert) { inc_cursor(); c = gchar_cursor(); dec_cursor(); } if (c != NUL) { /* The space is no longer at the end of the line, delete it. */ del_char(FALSE); did_add_space = FALSE; } } } } /* * Find out textwidth to be used for formatting: * if 'textwidth' option is set, use it * else if 'wrapmargin' option is set, use W_WIDTH(curwin) - 'wrapmargin' * if invalid value, use 0. * Set default to window width (maximum 79) for "gq" operator. */ int comp_textwidth(ff) int ff; /* force formatting (for "gq" command) */ { int textwidth; textwidth = curbuf->b_p_tw; if (textwidth == 0 && curbuf->b_p_wm) { /* The width is the window width minus 'wrapmargin' minus all the * things that add to the margin. */ textwidth = W_WIDTH(curwin) - curbuf->b_p_wm; #ifdef FEAT_CMDWIN if (cmdwin_type != 0) textwidth -= 1; #endif #ifdef FEAT_FOLDING textwidth -= curwin->w_p_fdc; #endif #ifdef FEAT_SIGNS if (curwin->w_buffer->b_signlist != NULL # ifdef FEAT_NETBEANS_INTG || netbeans_active() # endif ) textwidth -= 1; #endif if (curwin->w_p_nu || curwin->w_p_rnu) textwidth -= 8; } if (textwidth < 0) textwidth = 0; if (ff && textwidth == 0) { textwidth = W_WIDTH(curwin) - 1; if (textwidth > 79) textwidth = 79; } return textwidth; } /* * Put a character in the redo buffer, for when just after a CTRL-V. */ static void redo_literal(c) int c; { char_u buf[10]; /* Only digits need special treatment. Translate them into a string of * three digits. */ if (VIM_ISDIGIT(c)) { vim_snprintf((char *)buf, sizeof(buf), "%03d", c); AppendToRedobuff(buf); } else AppendCharToRedobuff(c); } /* * start_arrow() is called when an arrow key is used in insert mode. * For undo/redo it resembles hitting the <ESC> key. */ static void start_arrow(end_insert_pos) pos_T *end_insert_pos; /* can be NULL */ { if (!arrow_used) /* something has been inserted */ { AppendToRedobuff(ESC_STR); stop_insert(end_insert_pos, FALSE); arrow_used = TRUE; /* this means we stopped the current insert */ } #ifdef FEAT_SPELL check_spell_redraw(); #endif } #ifdef FEAT_SPELL /* * If we skipped highlighting word at cursor, do it now. * It may be skipped again, thus reset spell_redraw_lnum first. */ static void check_spell_redraw() { if (spell_redraw_lnum != 0) { linenr_T lnum = spell_redraw_lnum; spell_redraw_lnum = 0; redrawWinline(lnum, FALSE); } } /* * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly * spelled word, if there is one. */ static void spell_back_to_badword() { pos_T tpos = curwin->w_cursor; spell_bad_len = spell_move_to(curwin, BACKWARD, TRUE, TRUE, NULL); if (curwin->w_cursor.col != tpos.col) start_arrow(&tpos); } #endif /* * stop_arrow() is called before a change is made in insert mode. * If an arrow key has been used, start a new insertion. * Returns FAIL if undo is impossible, shouldn't insert then. */ int stop_arrow() { if (arrow_used) { if (u_save_cursor() == OK) { arrow_used = FALSE; ins_need_undo = FALSE; } Insstart = curwin->w_cursor; /* new insertion starts here */ Insstart_textlen = (colnr_T)linetabsize(ml_get_curline()); ai_col = 0; #ifdef FEAT_VREPLACE if (State & VREPLACE_FLAG) { orig_line_count = curbuf->b_ml.ml_line_count; vr_lines_changed = 1; } #endif ResetRedobuff(); AppendToRedobuff((char_u *)"1i"); /* pretend we start an insertion */ new_insert_skip = 2; } else if (ins_need_undo) { if (u_save_cursor() == OK) ins_need_undo = FALSE; } #ifdef FEAT_FOLDING /* Always open fold at the cursor line when inserting something. */ foldOpenCursor(); #endif return (arrow_used || ins_need_undo ? FAIL : OK); } /* * Do a few things to stop inserting. * "end_insert_pos" is where insert ended. It is NULL when we already jumped * to another window/buffer. */ static void stop_insert(end_insert_pos, esc) pos_T *end_insert_pos; int esc; /* called by ins_esc() */ { int cc; char_u *ptr; stop_redo_ins(); replace_flush(); /* abandon replace stack */ /* * Save the inserted text for later redo with ^@ and CTRL-A. * Don't do it when "restart_edit" was set and nothing was inserted, * otherwise CTRL-O w and then <Left> will clear "last_insert". */ ptr = get_inserted(); if (did_restart_edit == 0 || (ptr != NULL && (int)STRLEN(ptr) > new_insert_skip)) { vim_free(last_insert); last_insert = ptr; last_insert_skip = new_insert_skip; } else vim_free(ptr); if (!arrow_used && end_insert_pos != NULL) { /* Auto-format now. It may seem strange to do this when stopping an * insertion (or moving the cursor), but it's required when appending * a line and having it end in a space. But only do it when something * was actually inserted, otherwise undo won't work. */ if (!ins_need_undo && has_format_option(FO_AUTO)) { pos_T tpos = curwin->w_cursor; /* When the cursor is at the end of the line after a space the * formatting will move it to the following word. Avoid that by * moving the cursor onto the space. */ cc = 'x'; if (curwin->w_cursor.col > 0 && gchar_cursor() == NUL) { dec_cursor(); cc = gchar_cursor(); if (!vim_iswhite(cc)) curwin->w_cursor = tpos; } auto_format(TRUE, FALSE); if (vim_iswhite(cc)) { if (gchar_cursor() != NUL) inc_cursor(); #ifdef FEAT_VIRTUALEDIT /* If the cursor is still at the same character, also keep * the "coladd". */ if (gchar_cursor() == NUL && curwin->w_cursor.lnum == tpos.lnum && curwin->w_cursor.col == tpos.col) curwin->w_cursor.coladd = tpos.coladd; #endif } } /* If a space was inserted for auto-formatting, remove it now. */ check_auto_format(TRUE); /* If we just did an auto-indent, remove the white space from the end * of the line, and put the cursor back. * Do this when ESC was used or moving the cursor up/down. * Check for the old position still being valid, just in case the text * got changed unexpectedly. */ if (did_ai && (esc || (vim_strchr(p_cpo, CPO_INDENT) == NULL && curwin->w_cursor.lnum != end_insert_pos->lnum)) && end_insert_pos->lnum <= curbuf->b_ml.ml_line_count) { pos_T tpos = curwin->w_cursor; curwin->w_cursor = *end_insert_pos; check_cursor_col(); /* make sure it is not past the line */ for (;;) { if (gchar_cursor() == NUL && curwin->w_cursor.col > 0) --curwin->w_cursor.col; cc = gchar_cursor(); if (!vim_iswhite(cc)) break; if (del_char(TRUE) == FAIL) break; /* should not happen */ } if (curwin->w_cursor.lnum != tpos.lnum) curwin->w_cursor = tpos; else if (cc != NUL) ++curwin->w_cursor.col; /* put cursor back on the NUL */ #ifdef FEAT_VISUAL /* <C-S-Right> may have started Visual mode, adjust the position for * deleted characters. */ if (VIsual_active && VIsual.lnum == curwin->w_cursor.lnum) { int len = (int)STRLEN(ml_get_curline()); if (VIsual.col > len) { VIsual.col = len; # ifdef FEAT_VIRTUALEDIT VIsual.coladd = 0; # endif } } #endif } } did_ai = FALSE; #ifdef FEAT_SMARTINDENT did_si = FALSE; can_si = FALSE; can_si_back = FALSE; #endif /* Set '[ and '] to the inserted text. When end_insert_pos is NULL we are * now in a different buffer. */ if (end_insert_pos != NULL) { curbuf->b_op_start = Insstart; curbuf->b_op_end = *end_insert_pos; } } /* * Set the last inserted text to a single character. * Used for the replace command. */ void set_last_insert(c) int c; { char_u *s; vim_free(last_insert); last_insert = alloc(MB_MAXBYTES * 3 + 5); if (last_insert != NULL) { s = last_insert; /* Use the CTRL-V only when entering a special char */ if (c < ' ' || c == DEL) *s++ = Ctrl_V; s = add_char2buf(c, s); *s++ = ESC; *s++ = NUL; last_insert_skip = 0; } } #if defined(EXITFREE) || defined(PROTO) void free_last_insert() { vim_free(last_insert); last_insert = NULL; # ifdef FEAT_INS_EXPAND vim_free(compl_orig_text); compl_orig_text = NULL; # endif } #endif /* * Add character "c" to buffer "s". Escape the special meaning of K_SPECIAL * and CSI. Handle multi-byte characters. * Returns a pointer to after the added bytes. */ char_u * add_char2buf(c, s) int c; char_u *s; { #ifdef FEAT_MBYTE char_u temp[MB_MAXBYTES + 1]; int i; int len; len = (*mb_char2bytes)(c, temp); for (i = 0; i < len; ++i) { c = temp[i]; #endif /* Need to escape K_SPECIAL and CSI like in the typeahead buffer. */ if (c == K_SPECIAL) { *s++ = K_SPECIAL; *s++ = KS_SPECIAL; *s++ = KE_FILLER; } #ifdef FEAT_GUI else if (c == CSI) { *s++ = CSI; *s++ = KS_EXTRA; *s++ = (int)KE_CSI; } #endif else *s++ = c; #ifdef FEAT_MBYTE } #endif return s; } /* * move cursor to start of line * if flags & BL_WHITE move to first non-white * if flags & BL_SOL move to first non-white if startofline is set, * otherwise keep "curswant" column * if flags & BL_FIX don't leave the cursor on a NUL. */ void beginline(flags) int flags; { if ((flags & BL_SOL) && !p_sol) coladvance(curwin->w_curswant); else { curwin->w_cursor.col = 0; #ifdef FEAT_VIRTUALEDIT curwin->w_cursor.coladd = 0; #endif if (flags & (BL_WHITE | BL_SOL)) { char_u *ptr; for (ptr = ml_get_curline(); vim_iswhite(*ptr) && !((flags & BL_FIX) && ptr[1] == NUL); ++ptr) ++curwin->w_cursor.col; } curwin->w_set_curswant = TRUE; } } /* * oneright oneleft cursor_down cursor_up * * Move one char {right,left,down,up}. * Doesn't move onto the NUL past the end of the line, unless it is allowed. * Return OK when successful, FAIL when we hit a line of file boundary. */ int oneright() { char_u *ptr; int l; #ifdef FEAT_VIRTUALEDIT if (virtual_active()) { pos_T prevpos = curwin->w_cursor; /* Adjust for multi-wide char (excluding TAB) */ ptr = ml_get_cursor(); coladvance(getviscol() + ((*ptr != TAB && vim_isprintc( # ifdef FEAT_MBYTE (*mb_ptr2char)(ptr) # else *ptr # endif )) ? ptr2cells(ptr) : 1)); curwin->w_set_curswant = TRUE; /* Return OK if the cursor moved, FAIL otherwise (at window edge). */ return (prevpos.col != curwin->w_cursor.col || prevpos.coladd != curwin->w_cursor.coladd) ? OK : FAIL; } #endif ptr = ml_get_cursor(); if (*ptr == NUL) return FAIL; /* already at the very end */ #ifdef FEAT_MBYTE if (has_mbyte) l = (*mb_ptr2len)(ptr); else #endif l = 1; /* move "l" bytes right, but don't end up on the NUL, unless 'virtualedit' * contains "onemore". */ if (ptr[l] == NUL #ifdef FEAT_VIRTUALEDIT && (ve_flags & VE_ONEMORE) == 0 #endif ) return FAIL; curwin->w_cursor.col += l; curwin->w_set_curswant = TRUE; return OK; } int oneleft() { #ifdef FEAT_VIRTUALEDIT if (virtual_active()) { int width; int v = getviscol(); if (v == 0) return FAIL; # ifdef FEAT_LINEBREAK /* We might get stuck on 'showbreak', skip over it. */ width = 1; for (;;) { coladvance(v - width); /* getviscol() is slow, skip it when 'showbreak' is empty and * there are no multi-byte characters */ if ((*p_sbr == NUL # ifdef FEAT_MBYTE && !has_mbyte # endif ) || getviscol() < v) break; ++width; } # else coladvance(v - 1); # endif if (curwin->w_cursor.coladd == 1) { char_u *ptr; /* Adjust for multi-wide char (not a TAB) */ ptr = ml_get_cursor(); if (*ptr != TAB && vim_isprintc( # ifdef FEAT_MBYTE (*mb_ptr2char)(ptr) # else *ptr # endif ) && ptr2cells(ptr) > 1) curwin->w_cursor.coladd = 0; } curwin->w_set_curswant = TRUE; return OK; } #endif if (curwin->w_cursor.col == 0) return FAIL; curwin->w_set_curswant = TRUE; --curwin->w_cursor.col; #ifdef FEAT_MBYTE /* if the character on the left of the current cursor is a multi-byte * character, move to its first byte */ if (has_mbyte) mb_adjust_cursor(); #endif return OK; } int cursor_up(n, upd_topline) long n; int upd_topline; /* When TRUE: update topline */ { linenr_T lnum; if (n > 0) { lnum = curwin->w_cursor.lnum; /* This fails if the cursor is already in the first line or the count * is larger than the line number and '-' is in 'cpoptions' */ if (lnum <= 1 || (n >= lnum && vim_strchr(p_cpo, CPO_MINUS) != NULL)) return FAIL; if (n >= lnum) lnum = 1; else #ifdef FEAT_FOLDING if (hasAnyFolding(curwin)) { /* * Count each sequence of folded lines as one logical line. */ /* go to the the start of the current fold */ (void)hasFolding(lnum, &lnum, NULL); while (n--) { /* move up one line */ --lnum; if (lnum <= 1) break; /* If we entered a fold, move to the beginning, unless in * Insert mode or when 'foldopen' contains "all": it will open * in a moment. */ if (n > 0 || !((State & INSERT) || (fdo_flags & FDO_ALL))) (void)hasFolding(lnum, &lnum, NULL); } if (lnum < 1) lnum = 1; } else #endif lnum -= n; curwin->w_cursor.lnum = lnum; } /* try to advance to the column we want to be at */ coladvance(curwin->w_curswant); if (upd_topline) update_topline(); /* make sure curwin->w_topline is valid */ return OK; } /* * Cursor down a number of logical lines. */ int cursor_down(n, upd_topline) long n; int upd_topline; /* When TRUE: update topline */ { linenr_T lnum; if (n > 0) { lnum = curwin->w_cursor.lnum; #ifdef FEAT_FOLDING /* Move to last line of fold, will fail if it's the end-of-file. */ (void)hasFolding(lnum, NULL, &lnum); #endif /* This fails if the cursor is already in the last line or would move * beyound the last line and '-' is in 'cpoptions' */ if (lnum >= curbuf->b_ml.ml_line_count || (lnum + n > curbuf->b_ml.ml_line_count && vim_strchr(p_cpo, CPO_MINUS) != NULL)) return FAIL; if (lnum + n >= curbuf->b_ml.ml_line_count) lnum = curbuf->b_ml.ml_line_count; else #ifdef FEAT_FOLDING if (hasAnyFolding(curwin)) { linenr_T last; /* count each sequence of folded lines as one logical line */ while (n--) { if (hasFolding(lnum, NULL, &last)) lnum = last + 1; else ++lnum; if (lnum >= curbuf->b_ml.ml_line_count) break; } if (lnum > curbuf->b_ml.ml_line_count) lnum = curbuf->b_ml.ml_line_count; } else #endif lnum += n; curwin->w_cursor.lnum = lnum; } /* try to advance to the column we want to be at */ coladvance(curwin->w_curswant); if (upd_topline) update_topline(); /* make sure curwin->w_topline is valid */ return OK; } /* * Stuff the last inserted text in the read buffer. * Last_insert actually is a copy of the redo buffer, so we * first have to remove the command. */ int stuff_inserted(c, count, no_esc) int c; /* Command character to be inserted */ long count; /* Repeat this many times */ int no_esc; /* Don't add an ESC at the end */ { char_u *esc_ptr; char_u *ptr; char_u *last_ptr; char_u last = NUL; ptr = get_last_insert(); if (ptr == NULL) { EMSG(_(e_noinstext)); return FAIL; } /* may want to stuff the command character, to start Insert mode */ if (c != NUL) stuffcharReadbuff(c); if ((esc_ptr = (char_u *)vim_strrchr(ptr, ESC)) != NULL) *esc_ptr = NUL; /* remove the ESC */ /* when the last char is either "0" or "^" it will be quoted if no ESC * comes after it OR if it will inserted more than once and "ptr" * starts with ^D. -- Acevedo */ last_ptr = (esc_ptr ? esc_ptr : ptr + STRLEN(ptr)) - 1; if (last_ptr >= ptr && (*last_ptr == '0' || *last_ptr == '^') && (no_esc || (*ptr == Ctrl_D && count > 1))) { last = *last_ptr; *last_ptr = NUL; } do { stuffReadbuff(ptr); /* a trailing "0" is inserted as "<C-V>048", "^" as "<C-V>^" */ if (last) stuffReadbuff((char_u *)(last == '0' ? IF_EB("\026\060\064\070", CTRL_V_STR "xf0") : IF_EB("\026^", CTRL_V_STR "^"))); } while (--count > 0); if (last) *last_ptr = last; if (esc_ptr != NULL) *esc_ptr = ESC; /* put the ESC back */ /* may want to stuff a trailing ESC, to get out of Insert mode */ if (!no_esc) stuffcharReadbuff(ESC); return OK; } char_u * get_last_insert() { if (last_insert == NULL) return NULL; return last_insert + last_insert_skip; } /* * Get last inserted string, and remove trailing <Esc>. * Returns pointer to allocated memory (must be freed) or NULL. */ char_u * get_last_insert_save() { char_u *s; int len; if (last_insert == NULL) return NULL; s = vim_strsave(last_insert + last_insert_skip); if (s != NULL) { len = (int)STRLEN(s); if (len > 0 && s[len - 1] == ESC) /* remove trailing ESC */ s[len - 1] = NUL; } return s; } /* * Check the word in front of the cursor for an abbreviation. * Called when the non-id character "c" has been entered. * When an abbreviation is recognized it is removed from the text and * the replacement string is inserted in typebuf.tb_buf[], followed by "c". */ static int echeck_abbr(c) int c; { /* Don't check for abbreviation in paste mode, when disabled and just * after moving around with cursor keys. */ if (p_paste || no_abbr || arrow_used) return FALSE; return check_abbr(c, ml_get_curline(), curwin->w_cursor.col, curwin->w_cursor.lnum == Insstart.lnum ? Insstart.col : 0); } /* * replace-stack functions * * When replacing characters, the replaced characters are remembered for each * new character. This is used to re-insert the old text when backspacing. * * There is a NUL headed list of characters for each character that is * currently in the file after the insertion point. When BS is used, one NUL * headed list is put back for the deleted character. * * For a newline, there are two NUL headed lists. One contains the characters * that the NL replaced. The extra one stores the characters after the cursor * that were deleted (always white space). * * Replace_offset is normally 0, in which case replace_push will add a new * character at the end of the stack. If replace_offset is not 0, that many * characters will be left on the stack above the newly inserted character. */ static char_u *replace_stack = NULL; static long replace_stack_nr = 0; /* next entry in replace stack */ static long replace_stack_len = 0; /* max. number of entries */ void replace_push(c) int c; /* character that is replaced (NUL is none) */ { char_u *p; if (replace_stack_nr < replace_offset) /* nothing to do */ return; if (replace_stack_len <= replace_stack_nr) { replace_stack_len += 50; p = lalloc(sizeof(char_u) * replace_stack_len, TRUE); if (p == NULL) /* out of memory */ { replace_stack_len -= 50; return; } if (replace_stack != NULL) { mch_memmove(p, replace_stack, (size_t)(replace_stack_nr * sizeof(char_u))); vim_free(replace_stack); } replace_stack = p; } p = replace_stack + replace_stack_nr - replace_offset; if (replace_offset) mch_memmove(p + 1, p, (size_t)(replace_offset * sizeof(char_u))); *p = c; ++replace_stack_nr; } #if defined(FEAT_MBYTE) || defined(PROTO) /* * Push a character onto the replace stack. Handles a multi-byte character in * reverse byte order, so that the first byte is popped off first. * Return the number of bytes done (includes composing characters). */ int replace_push_mb(p) char_u *p; { int l = (*mb_ptr2len)(p); int j; for (j = l - 1; j >= 0; --j) replace_push(p[j]); return l; } #endif /* * Pop one item from the replace stack. * return -1 if stack empty * return replaced character or NUL otherwise */ static int replace_pop() { if (replace_stack_nr == 0) return -1; return (int)replace_stack[--replace_stack_nr]; } /* * Join the top two items on the replace stack. This removes to "off"'th NUL * encountered. */ static void replace_join(off) int off; /* offset for which NUL to remove */ { int i; for (i = replace_stack_nr; --i >= 0; ) if (replace_stack[i] == NUL && off-- <= 0) { --replace_stack_nr; mch_memmove(replace_stack + i, replace_stack + i + 1, (size_t)(replace_stack_nr - i)); return; } } /* * Pop bytes from the replace stack until a NUL is found, and insert them * before the cursor. Can only be used in REPLACE or VREPLACE mode. */ static void replace_pop_ins() { int cc; int oldState = State; State = NORMAL; /* don't want REPLACE here */ while ((cc = replace_pop()) > 0) { #ifdef FEAT_MBYTE mb_replace_pop_ins(cc); #else ins_char(cc); #endif dec_cursor(); } State = oldState; } #ifdef FEAT_MBYTE /* * Insert bytes popped from the replace stack. "cc" is the first byte. If it * indicates a multi-byte char, pop the other bytes too. */ static void mb_replace_pop_ins(cc) int cc; { int n; char_u buf[MB_MAXBYTES + 1]; int i; int c; if (has_mbyte && (n = MB_BYTE2LEN(cc)) > 1) { buf[0] = cc; for (i = 1; i < n; ++i) buf[i] = replace_pop(); ins_bytes_len(buf, n); } else ins_char(cc); if (enc_utf8) /* Handle composing chars. */ for (;;) { c = replace_pop(); if (c == -1) /* stack empty */ break; if ((n = MB_BYTE2LEN(c)) == 1) { /* Not a multi-byte char, put it back. */ replace_push(c); break; } else { buf[0] = c; for (i = 1; i < n; ++i) buf[i] = replace_pop(); if (utf_iscomposing(utf_ptr2char(buf))) ins_bytes_len(buf, n); else { /* Not a composing char, put it back. */ for (i = n - 1; i >= 0; --i) replace_push(buf[i]); break; } } } } #endif /* * make the replace stack empty * (called when exiting replace mode) */ static void replace_flush() { vim_free(replace_stack); replace_stack = NULL; replace_stack_len = 0; replace_stack_nr = 0; } /* * Handle doing a BS for one character. * cc < 0: replace stack empty, just move cursor * cc == 0: character was inserted, delete it * cc > 0: character was replaced, put cc (first byte of original char) back * and check for more characters to be put back * When "limit_col" is >= 0, don't delete before this column. Matters when * using composing characters, use del_char_after_col() instead of del_char(). */ static void replace_do_bs(limit_col) int limit_col; { int cc; #ifdef FEAT_VREPLACE int orig_len = 0; int ins_len; int orig_vcols = 0; colnr_T start_vcol; char_u *p; int i; int vcol; #endif cc = replace_pop(); if (cc > 0) { #ifdef FEAT_VREPLACE if (State & VREPLACE_FLAG) { /* Get the number of screen cells used by the character we are * going to delete. */ getvcol(curwin, &curwin->w_cursor, NULL, &start_vcol, NULL); orig_vcols = chartabsize(ml_get_cursor(), start_vcol); } #endif #ifdef FEAT_MBYTE if (has_mbyte) { (void)del_char_after_col(limit_col); # ifdef FEAT_VREPLACE if (State & VREPLACE_FLAG) orig_len = (int)STRLEN(ml_get_cursor()); # endif replace_push(cc); } else #endif { pchar_cursor(cc); #ifdef FEAT_VREPLACE if (State & VREPLACE_FLAG) orig_len = (int)STRLEN(ml_get_cursor()) - 1; #endif } replace_pop_ins(); #ifdef FEAT_VREPLACE if (State & VREPLACE_FLAG) { /* Get the number of screen cells used by the inserted characters */ p = ml_get_cursor(); ins_len = (int)STRLEN(p) - orig_len; vcol = start_vcol; for (i = 0; i < ins_len; ++i) { vcol += chartabsize(p + i, vcol); #ifdef FEAT_MBYTE i += (*mb_ptr2len)(p) - 1; #endif } vcol -= start_vcol; /* Delete spaces that were inserted after the cursor to keep the * text aligned. */ curwin->w_cursor.col += ins_len; while (vcol > orig_vcols && gchar_cursor() == ' ') { del_char(FALSE); ++orig_vcols; } curwin->w_cursor.col -= ins_len; } #endif /* mark the buffer as changed and prepare for displaying */ changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col); } else if (cc == 0) (void)del_char_after_col(limit_col); } #ifdef FEAT_CINDENT /* * Return TRUE if C-indenting is on. */ static int cindent_on() { return (!p_paste && (curbuf->b_p_cin # ifdef FEAT_EVAL || *curbuf->b_p_inde != NUL # endif )); } #endif #if defined(FEAT_LISP) || defined(FEAT_CINDENT) || defined(PROTO) /* * Re-indent the current line, based on the current contents of it and the * surrounding lines. Fixing the cursor position seems really easy -- I'm very * confused what all the part that handles Control-T is doing that I'm not. * "get_the_indent" should be get_c_indent, get_expr_indent or get_lisp_indent. */ void fixthisline(get_the_indent) int (*get_the_indent) __ARGS((void)); { change_indent(INDENT_SET, get_the_indent(), FALSE, 0, TRUE); if (linewhite(curwin->w_cursor.lnum)) did_ai = TRUE; /* delete the indent if the line stays empty */ } void fix_indent() { if (p_paste) return; # ifdef FEAT_LISP if (curbuf->b_p_lisp && curbuf->b_p_ai) fixthisline(get_lisp_indent); # endif # if defined(FEAT_LISP) && defined(FEAT_CINDENT) else # endif # ifdef FEAT_CINDENT if (cindent_on()) do_c_expr_indent(); # endif } #endif #ifdef FEAT_CINDENT /* * return TRUE if 'cinkeys' contains the key "keytyped", * when == '*': Only if key is preceded with '*' (indent before insert) * when == '!': Only if key is prededed with '!' (don't insert) * when == ' ': Only if key is not preceded with '*'(indent afterwards) * * "keytyped" can have a few special values: * KEY_OPEN_FORW * KEY_OPEN_BACK * KEY_COMPLETE just finished completion. * * If line_is_empty is TRUE accept keys with '0' before them. */ int in_cinkeys(keytyped, when, line_is_empty) int keytyped; int when; int line_is_empty; { char_u *look; int try_match; int try_match_word; char_u *p; char_u *line; int icase; int i; if (keytyped == NUL) /* Can happen with CTRL-Y and CTRL-E on a short line. */ return FALSE; #ifdef FEAT_EVAL if (*curbuf->b_p_inde != NUL) look = curbuf->b_p_indk; /* 'indentexpr' set: use 'indentkeys' */ else #endif look = curbuf->b_p_cink; /* 'indentexpr' empty: use 'cinkeys' */ while (*look) { /* * Find out if we want to try a match with this key, depending on * 'when' and a '*' or '!' before the key. */ switch (when) { case '*': try_match = (*look == '*'); break; case '!': try_match = (*look == '!'); break; default: try_match = (*look != '*'); break; } if (*look == '*' || *look == '!') ++look; /* * If there is a '0', only accept a match if the line is empty. * But may still match when typing last char of a word. */ if (*look == '0') { try_match_word = try_match; if (!line_is_empty) try_match = FALSE; ++look; } else try_match_word = FALSE; /* * does it look like a control character? */ if (*look == '^' #ifdef EBCDIC && (Ctrl_chr(look[1]) != 0) #else && look[1] >= '?' && look[1] <= '_' #endif ) { if (try_match && keytyped == Ctrl_chr(look[1])) return TRUE; look += 2; } /* * 'o' means "o" command, open forward. * 'O' means "O" command, open backward. */ else if (*look == 'o') { if (try_match && keytyped == KEY_OPEN_FORW) return TRUE; ++look; } else if (*look == 'O') { if (try_match && keytyped == KEY_OPEN_BACK) return TRUE; ++look; } /* * 'e' means to check for "else" at start of line and just before the * cursor. */ else if (*look == 'e') { if (try_match && keytyped == 'e' && curwin->w_cursor.col >= 4) { p = ml_get_curline(); if (skipwhite(p) == p + curwin->w_cursor.col - 4 && STRNCMP(p + curwin->w_cursor.col - 4, "else", 4) == 0) return TRUE; } ++look; } /* * ':' only causes an indent if it is at the end of a label or case * statement, or when it was before typing the ':' (to fix * class::method for C++). */ else if (*look == ':') { if (try_match && keytyped == ':') { p = ml_get_curline(); if (cin_iscase(p, FALSE) || cin_isscopedecl(p) || cin_islabel(30)) return TRUE; /* Need to get the line again after cin_islabel(). */ p = ml_get_curline(); if (curwin->w_cursor.col > 2 && p[curwin->w_cursor.col - 1] == ':' && p[curwin->w_cursor.col - 2] == ':') { p[curwin->w_cursor.col - 1] = ' '; i = (cin_iscase(p, FALSE) || cin_isscopedecl(p) || cin_islabel(30)); p = ml_get_curline(); p[curwin->w_cursor.col - 1] = ':'; if (i) return TRUE; } } ++look; } /* * Is it a key in <>, maybe? */ else if (*look == '<') { if (try_match) { /* * make up some named keys <o>, <O>, <e>, <0>, <>>, <<>, <*>, * <:> and <!> so that people can re-indent on o, O, e, 0, <, * >, *, : and ! keys if they really really want to. */ if (vim_strchr((char_u *)"<>!*oOe0:", look[1]) != NULL && keytyped == look[1]) return TRUE; if (keytyped == get_special_key_code(look + 1)) return TRUE; } while (*look && *look != '>') look++; while (*look == '>') look++; } /* * Is it a word: "=word"? */ else if (*look == '=' && look[1] != ',' && look[1] != NUL) { ++look; if (*look == '~') { icase = TRUE; ++look; } else icase = FALSE; p = vim_strchr(look, ','); if (p == NULL) p = look + STRLEN(look); if ((try_match || try_match_word) && curwin->w_cursor.col >= (colnr_T)(p - look)) { int match = FALSE; #ifdef FEAT_INS_EXPAND if (keytyped == KEY_COMPLETE) { char_u *s; /* Just completed a word, check if it starts with "look". * search back for the start of a word. */ line = ml_get_curline(); # ifdef FEAT_MBYTE if (has_mbyte) { char_u *n; for (s = line + curwin->w_cursor.col; s > line; s = n) { n = mb_prevptr(line, s); if (!vim_iswordp(n)) break; } } else # endif for (s = line + curwin->w_cursor.col; s > line; --s) if (!vim_iswordc(s[-1])) break; if (s + (p - look) <= line + curwin->w_cursor.col && (icase ? MB_STRNICMP(s, look, p - look) : STRNCMP(s, look, p - look)) == 0) match = TRUE; } else #endif /* TODO: multi-byte */ if (keytyped == (int)p[-1] || (icase && keytyped < 256 && TOLOWER_LOC(keytyped) == TOLOWER_LOC((int)p[-1]))) { line = ml_get_cursor(); if ((curwin->w_cursor.col == (colnr_T)(p - look) || !vim_iswordc(line[-(p - look) - 1])) && (icase ? MB_STRNICMP(line - (p - look), look, p - look) : STRNCMP(line - (p - look), look, p - look)) == 0) match = TRUE; } if (match && try_match_word && !try_match) { /* "0=word": Check if there are only blanks before the * word. */ line = ml_get_curline(); if ((int)(skipwhite(line) - line) != (int)(curwin->w_cursor.col - (p - look))) match = FALSE; } if (match) return TRUE; } look = p; } /* * ok, it's a boring generic character. */ else { if (try_match && *look == keytyped) return TRUE; ++look; } /* * Skip over ", ". */ look = skip_to_option_part(look); } return FALSE; } #endif /* FEAT_CINDENT */ #if defined(FEAT_RIGHTLEFT) || defined(PROTO) /* * Map Hebrew keyboard when in hkmap mode. */ int hkmap(c) int c; { if (p_hkmapp) /* phonetic mapping, by Ilya Dogolazky */ { enum {hALEF=0, BET, GIMEL, DALET, HEI, VAV, ZAIN, HET, TET, IUD, KAFsofit, hKAF, LAMED, MEMsofit, MEM, NUNsofit, NUN, SAMEH, AIN, PEIsofit, PEI, ZADIsofit, ZADI, KOF, RESH, hSHIN, TAV}; static char_u map[26] = {(char_u)hALEF/*a*/, (char_u)BET /*b*/, (char_u)hKAF /*c*/, (char_u)DALET/*d*/, (char_u)-1 /*e*/, (char_u)PEIsofit/*f*/, (char_u)GIMEL/*g*/, (char_u)HEI /*h*/, (char_u)IUD /*i*/, (char_u)HET /*j*/, (char_u)KOF /*k*/, (char_u)LAMED /*l*/, (char_u)MEM /*m*/, (char_u)NUN /*n*/, (char_u)SAMEH /*o*/, (char_u)PEI /*p*/, (char_u)-1 /*q*/, (char_u)RESH /*r*/, (char_u)ZAIN /*s*/, (char_u)TAV /*t*/, (char_u)TET /*u*/, (char_u)VAV /*v*/, (char_u)hSHIN/*w*/, (char_u)-1 /*x*/, (char_u)AIN /*y*/, (char_u)ZADI /*z*/}; if (c == 'N' || c == 'M' || c == 'P' || c == 'C' || c == 'Z') return (int)(map[CharOrd(c)] - 1 + p_aleph); /* '-1'='sofit' */ else if (c == 'x') return 'X'; else if (c == 'q') return '\''; /* {geresh}={'} */ else if (c == 246) return ' '; /* \"o --> ' ' for a german keyboard */ else if (c == 228) return ' '; /* \"a --> ' ' -- / -- */ else if (c == 252) return ' '; /* \"u --> ' ' -- / -- */ #ifdef EBCDIC else if (islower(c)) #else /* NOTE: islower() does not do the right thing for us on Linux so we * do this the same was as 5.7 and previous, so it works correctly on * all systems. Specifically, the e.g. Delete and Arrow keys are * munged and won't work if e.g. searching for Hebrew text. */ else if (c >= 'a' && c <= 'z') #endif return (int)(map[CharOrdLow(c)] + p_aleph); else return c; } else { switch (c) { case '`': return ';'; case '/': return '.'; case '\'': return ','; case 'q': return '/'; case 'w': return '\''; /* Hebrew letters - set offset from 'a' */ case ',': c = '{'; break; case '.': c = 'v'; break; case ';': c = 't'; break; default: { static char str[] = "zqbcxlsjphmkwonu ydafe rig"; #ifdef EBCDIC /* see note about islower() above */ if (!islower(c)) #else if (c < 'a' || c > 'z') #endif return c; c = str[CharOrdLow(c)]; break; } } return (int)(CharOrdLow(c) + p_aleph); } } #endif static void ins_reg() { int need_redraw = FALSE; int regname; int literally = 0; #ifdef FEAT_VISUAL int vis_active = VIsual_active; #endif /* * If we are going to wait for a character, show a '"'. */ pc_status = PC_STATUS_UNSET; if (redrawing() && !char_avail()) { /* may need to redraw when no more chars available now */ ins_redraw(FALSE); edit_putchar('"', TRUE); #ifdef FEAT_CMDL_INFO add_to_showcmd_c(Ctrl_R); #endif } #ifdef USE_ON_FLY_SCROLL dont_scroll = TRUE; /* disallow scrolling here */ #endif /* * Don't map the register name. This also prevents the mode message to be * deleted when ESC is hit. */ ++no_mapping; regname = plain_vgetc(); LANGMAP_ADJUST(regname, TRUE); if (regname == Ctrl_R || regname == Ctrl_O || regname == Ctrl_P) { /* Get a third key for literal register insertion */ literally = regname; #ifdef FEAT_CMDL_INFO add_to_showcmd_c(literally); #endif regname = plain_vgetc(); LANGMAP_ADJUST(regname, TRUE); } --no_mapping; #ifdef FEAT_EVAL /* * Don't call u_sync() while getting the expression, * evaluating it or giving an error message for it! */ ++no_u_sync; if (regname == '=') { # ifdef USE_IM_CONTROL int im_on = im_get_status(); # endif regname = get_expr_register(); # ifdef USE_IM_CONTROL /* Restore the Input Method. */ if (im_on) im_set_active(TRUE); # endif } if (regname == NUL || !valid_yank_reg(regname, FALSE)) { vim_beep(); need_redraw = TRUE; /* remove the '"' */ } else { #endif if (literally == Ctrl_O || literally == Ctrl_P) { /* Append the command to the redo buffer. */ AppendCharToRedobuff(Ctrl_R); AppendCharToRedobuff(literally); AppendCharToRedobuff(regname); do_put(regname, BACKWARD, 1L, (literally == Ctrl_P ? PUT_FIXINDENT : 0) | PUT_CURSEND); } else if (insert_reg(regname, literally) == FAIL) { vim_beep(); need_redraw = TRUE; /* remove the '"' */ } else if (stop_insert_mode) /* When the '=' register was used and a function was invoked that * did ":stopinsert" then stuff_empty() returns FALSE but we won't * insert anything, need to remove the '"' */ need_redraw = TRUE; #ifdef FEAT_EVAL } --no_u_sync; #endif #ifdef FEAT_CMDL_INFO clear_showcmd(); #endif /* If the inserted register is empty, we need to remove the '"' */ if (need_redraw || stuff_empty()) edit_unputchar(); #ifdef FEAT_VISUAL /* Disallow starting Visual mode here, would get a weird mode. */ if (!vis_active && VIsual_active) end_visual_mode(); #endif } /* * CTRL-G commands in Insert mode. */ static void ins_ctrl_g() { int c; #ifdef FEAT_INS_EXPAND /* Right after CTRL-X the cursor will be after the ruler. */ setcursor(); #endif /* * Don't map the second key. This also prevents the mode message to be * deleted when ESC is hit. */ ++no_mapping; c = plain_vgetc(); --no_mapping; switch (c) { /* CTRL-G k and CTRL-G <Up>: cursor up to Insstart.col */ case K_UP: case Ctrl_K: case 'k': ins_up(TRUE); break; /* CTRL-G j and CTRL-G <Down>: cursor down to Insstart.col */ case K_DOWN: case Ctrl_J: case 'j': ins_down(TRUE); break; /* CTRL-G u: start new undoable edit */ case 'u': u_sync(TRUE); ins_need_undo = TRUE; /* Need to reset Insstart, esp. because a BS that joins * a line to the previous one must save for undo. */ Insstart = curwin->w_cursor; break; /* Unknown CTRL-G command, reserved for future expansion. */ default: vim_beep(); } } /* * CTRL-^ in Insert mode. */ static void ins_ctrl_hat() { if (map_to_exists_mode((char_u *)"", LANGMAP, FALSE)) { /* ":lmap" mappings exists, Toggle use of ":lmap" mappings. */ if (State & LANGMAP) { curbuf->b_p_iminsert = B_IMODE_NONE; State &= ~LANGMAP; } else { curbuf->b_p_iminsert = B_IMODE_LMAP; State |= LANGMAP; #ifdef USE_IM_CONTROL im_set_active(FALSE); #endif } } #ifdef USE_IM_CONTROL else { /* There are no ":lmap" mappings, toggle IM */ if (im_get_status()) { curbuf->b_p_iminsert = B_IMODE_NONE; im_set_active(FALSE); } else { curbuf->b_p_iminsert = B_IMODE_IM; State &= ~LANGMAP; im_set_active(TRUE); } } #endif set_iminsert_global(); showmode(); #ifdef FEAT_GUI /* may show different cursor shape or color */ if (gui.in_use) gui_update_cursor(TRUE, FALSE); #endif #if defined(FEAT_WINDOWS) && defined(FEAT_KEYMAP) /* Show/unshow value of 'keymap' in status lines. */ status_redraw_curbuf(); #endif } /* * Handle ESC in insert mode. * Returns TRUE when leaving insert mode, FALSE when going to repeat the * insert. */ static int ins_esc(count, cmdchar, nomove) long *count; int cmdchar; int nomove; /* don't move cursor */ { int temp; static int disabled_redraw = FALSE; #ifdef FEAT_SPELL check_spell_redraw(); #endif #if defined(FEAT_HANGULIN) # if defined(ESC_CHG_TO_ENG_MODE) hangul_input_state_set(0); # endif if (composing_hangul) { push_raw_key(composing_hangul_buffer, 2); composing_hangul = 0; } #endif temp = curwin->w_cursor.col; if (disabled_redraw) { --RedrawingDisabled; disabled_redraw = FALSE; } if (!arrow_used) { /* * Don't append the ESC for "r<CR>" and "grx". * When 'insertmode' is set only CTRL-L stops Insert mode. Needed for * when "count" is non-zero. */ if (cmdchar != 'r' && cmdchar != 'v') AppendToRedobuff(p_im ? (char_u *)"\014" : ESC_STR); /* * Repeating insert may take a long time. Check for * interrupt now and then. */ if (*count > 0) { line_breakcheck(); if (got_int) *count = 0; } if (--*count > 0) /* repeat what was typed */ { /* Vi repeats the insert without replacing characters. */ if (vim_strchr(p_cpo, CPO_REPLCNT) != NULL) State &= ~REPLACE_FLAG; (void)start_redo_ins(); if (cmdchar == 'r' || cmdchar == 'v') stuffReadbuff(ESC_STR); /* no ESC in redo buffer */ ++RedrawingDisabled; disabled_redraw = TRUE; return FALSE; /* repeat the insert */ } stop_insert(&curwin->w_cursor, TRUE); undisplay_dollar(); } /* When an autoindent was removed, curswant stays after the * indent */ if (restart_edit == NUL && (colnr_T)temp == curwin->w_cursor.col) curwin->w_set_curswant = TRUE; /* Remember the last Insert position in the '^ mark. */ if (!cmdmod.keepjumps) curbuf->b_last_insert = curwin->w_cursor; /* * The cursor should end up on the last inserted character. * Don't do it for CTRL-O, unless past the end of the line. */ if (!nomove && (curwin->w_cursor.col != 0 #ifdef FEAT_VIRTUALEDIT || curwin->w_cursor.coladd > 0 #endif ) && (restart_edit == NUL || (gchar_cursor() == NUL #ifdef FEAT_VISUAL && !VIsual_active #endif )) #ifdef FEAT_RIGHTLEFT && !revins_on #endif ) { #ifdef FEAT_VIRTUALEDIT if (curwin->w_cursor.coladd > 0 || ve_flags == VE_ALL) { oneleft(); if (restart_edit != NUL) ++curwin->w_cursor.coladd; } else #endif { --curwin->w_cursor.col; #ifdef FEAT_MBYTE /* Correct cursor for multi-byte character. */ if (has_mbyte) mb_adjust_cursor(); #endif } } #ifdef USE_IM_CONTROL /* Disable IM to allow typing English directly for Normal mode commands. * When ":lmap" is enabled don't change 'iminsert' (IM can be enabled as * well). */ if (!(State & LANGMAP)) im_save_status(&curbuf->b_p_iminsert); im_set_active(FALSE); #endif State = NORMAL; /* need to position cursor again (e.g. when on a TAB ) */ changed_cline_bef_curs(); #ifdef FEAT_MOUSE setmouse(); #endif #ifdef CURSOR_SHAPE ui_cursor_shape(); /* may show different cursor shape */ #endif /* * When recording or for CTRL-O, need to display the new mode. * Otherwise remove the mode message. */ if (Recording || restart_edit != NUL) showmode(); else if (p_smd) MSG(""); return TRUE; /* exit Insert mode */ } #ifdef FEAT_RIGHTLEFT /* * Toggle language: hkmap and revins_on. * Move to end of reverse inserted text. */ static void ins_ctrl_() { if (revins_on && revins_chars && revins_scol >= 0) { while (gchar_cursor() != NUL && revins_chars--) ++curwin->w_cursor.col; } p_ri = !p_ri; revins_on = (State == INSERT && p_ri); if (revins_on) { revins_scol = curwin->w_cursor.col; revins_legal++; revins_chars = 0; undisplay_dollar(); } else revins_scol = -1; #ifdef FEAT_FKMAP if (p_altkeymap) { /* * to be consistent also for redo command, using '.' * set arrow_used to true and stop it - causing to redo * characters entered in one mode (normal/reverse insert). */ arrow_used = TRUE; (void)stop_arrow(); p_fkmap = curwin->w_p_rl ^ p_ri; if (p_fkmap && p_ri) State = INSERT; } else #endif p_hkmap = curwin->w_p_rl ^ p_ri; /* be consistent! */ showmode(); } #endif #ifdef FEAT_VISUAL /* * If 'keymodel' contains "startsel", may start selection. * Returns TRUE when a CTRL-O and other keys stuffed. */ static int ins_start_select(c) int c; { if (km_startsel) switch (c) { case K_KHOME: case K_KEND: case K_PAGEUP: case K_KPAGEUP: case K_PAGEDOWN: case K_KPAGEDOWN: # ifdef MACOS case K_LEFT: case K_RIGHT: case K_UP: case K_DOWN: case K_END: case K_HOME: # endif if (!(mod_mask & MOD_MASK_SHIFT)) break; /* FALLTHROUGH */ case K_S_LEFT: case K_S_RIGHT: case K_S_UP: case K_S_DOWN: case K_S_END: case K_S_HOME: /* Start selection right away, the cursor can move with * CTRL-O when beyond the end of the line. */ start_selection(); /* Execute the key in (insert) Select mode. */ stuffcharReadbuff(Ctrl_O); if (mod_mask) { char_u buf[4]; buf[0] = K_SPECIAL; buf[1] = KS_MODIFIER; buf[2] = mod_mask; buf[3] = NUL; stuffReadbuff(buf); } stuffcharReadbuff(c); return TRUE; } return FALSE; } #endif /* * <Insert> key in Insert mode: toggle insert/remplace mode. */ static void ins_insert(replaceState) int replaceState; { #ifdef FEAT_FKMAP if (p_fkmap && p_ri) { beep_flush(); EMSG(farsi_text_3); /* encoded in Farsi */ return; } #endif #ifdef FEAT_AUTOCMD # ifdef FEAT_EVAL set_vim_var_string(VV_INSERTMODE, (char_u *)((State & REPLACE_FLAG) ? "i" : # ifdef FEAT_VREPLACE replaceState == VREPLACE ? "v" : # endif "r"), 1); # endif apply_autocmds(EVENT_INSERTCHANGE, NULL, NULL, FALSE, curbuf); #endif if (State & REPLACE_FLAG) State = INSERT | (State & LANGMAP); else State = replaceState | (State & LANGMAP); AppendCharToRedobuff(K_INS); showmode(); #ifdef CURSOR_SHAPE ui_cursor_shape(); /* may show different cursor shape */ #endif } /* * Pressed CTRL-O in Insert mode. */ static void ins_ctrl_o() { #ifdef FEAT_VREPLACE if (State & VREPLACE_FLAG) restart_edit = 'V'; else #endif if (State & REPLACE_FLAG) restart_edit = 'R'; else restart_edit = 'I'; #ifdef FEAT_VIRTUALEDIT if (virtual_active()) ins_at_eol = FALSE; /* cursor always keeps its column */ else #endif ins_at_eol = (gchar_cursor() == NUL); } /* * If the cursor is on an indent, ^T/^D insert/delete one * shiftwidth. Otherwise ^T/^D behave like a "<<" or ">>". * Always round the indent to 'shiftwidth', this is compatible * with vi. But vi only supports ^T and ^D after an * autoindent, we support it everywhere. */ static void ins_shift(c, lastc) int c; int lastc; { if (stop_arrow() == FAIL) return; AppendCharToRedobuff(c); /* * 0^D and ^^D: remove all indent. */ if (c == Ctrl_D && (lastc == '0' || lastc == '^') && curwin->w_cursor.col > 0) { --curwin->w_cursor.col; (void)del_char(FALSE); /* delete the '^' or '0' */ /* In Replace mode, restore the characters that '^' or '0' replaced. */ if (State & REPLACE_FLAG) replace_pop_ins(); if (lastc == '^') old_indent = get_indent(); /* remember curr. indent */ change_indent(INDENT_SET, 0, TRUE, 0, TRUE); } else change_indent(c == Ctrl_D ? INDENT_DEC : INDENT_INC, 0, TRUE, 0, TRUE); if (did_ai && *skipwhite(ml_get_curline()) != NUL) did_ai = FALSE; #ifdef FEAT_SMARTINDENT did_si = FALSE; can_si = FALSE; can_si_back = FALSE; #endif #ifdef FEAT_CINDENT can_cindent = FALSE; /* no cindenting after ^D or ^T */ #endif } static void ins_del() { int temp; if (stop_arrow() == FAIL) return; if (gchar_cursor() == NUL) /* delete newline */ { temp = curwin->w_cursor.col; if (!can_bs(BS_EOL) /* only if "eol" included */ || do_join(2, FALSE, TRUE, FALSE) == FAIL) vim_beep(); else curwin->w_cursor.col = temp; } else if (del_char(FALSE) == FAIL) /* delete char under cursor */ vim_beep(); did_ai = FALSE; #ifdef FEAT_SMARTINDENT did_si = FALSE; can_si = FALSE; can_si_back = FALSE; #endif AppendCharToRedobuff(K_DEL); } static void ins_bs_one __ARGS((colnr_T *vcolp)); /* * Delete one character for ins_bs(). */ static void ins_bs_one(vcolp) colnr_T *vcolp; { dec_cursor(); getvcol(curwin, &curwin->w_cursor, vcolp, NULL, NULL); if (State & REPLACE_FLAG) { /* Don't delete characters before the insert point when in * Replace mode */ if (curwin->w_cursor.lnum != Insstart.lnum || curwin->w_cursor.col >= Insstart.col) replace_do_bs(-1); } else (void)del_char(FALSE); } /* * Handle Backspace, delete-word and delete-line in Insert mode. * Return TRUE when backspace was actually used. */ static int ins_bs(c, mode, inserted_space_p) int c; int mode; int *inserted_space_p; { linenr_T lnum; int cc; int temp = 0; /* init for GCC */ colnr_T save_col; colnr_T mincol; int did_backspace = FALSE; int in_indent; int oldState; #ifdef FEAT_MBYTE int cpc[MAX_MCO]; /* composing characters */ #endif /* * can't delete anything in an empty file * can't backup past first character in buffer * can't backup past starting point unless 'backspace' > 1 * can backup to a previous line if 'backspace' == 0 */ if ( bufempty() || ( #ifdef FEAT_RIGHTLEFT !revins_on && #endif ((curwin->w_cursor.lnum == 1 && curwin->w_cursor.col == 0) || (!can_bs(BS_START) && (arrow_used || (curwin->w_cursor.lnum == Insstart.lnum && curwin->w_cursor.col <= Insstart.col))) || (!can_bs(BS_INDENT) && !arrow_used && ai_col > 0 && curwin->w_cursor.col <= ai_col) || (!can_bs(BS_EOL) && curwin->w_cursor.col == 0)))) { vim_beep(); return FALSE; } if (stop_arrow() == FAIL) return FALSE; in_indent = inindent(0); #ifdef FEAT_CINDENT if (in_indent) can_cindent = FALSE; #endif #ifdef FEAT_COMMENTS end_comment_pending = NUL; /* After BS, don't auto-end comment */ #endif #ifdef FEAT_RIGHTLEFT if (revins_on) /* put cursor after last inserted char */ inc_cursor(); #endif #ifdef FEAT_VIRTUALEDIT /* Virtualedit: * BACKSPACE_CHAR eats a virtual space * BACKSPACE_WORD eats all coladd * BACKSPACE_LINE eats all coladd and keeps going */ if (curwin->w_cursor.coladd > 0) { if (mode == BACKSPACE_CHAR) { --curwin->w_cursor.coladd; return TRUE; } if (mode == BACKSPACE_WORD) { curwin->w_cursor.coladd = 0; return TRUE; } curwin->w_cursor.coladd = 0; } #endif /* * delete newline! */ if (curwin->w_cursor.col == 0) { lnum = Insstart.lnum; if (curwin->w_cursor.lnum == Insstart.lnum #ifdef FEAT_RIGHTLEFT || revins_on #endif ) { if (u_save((linenr_T)(curwin->w_cursor.lnum - 2), (linenr_T)(curwin->w_cursor.lnum + 1)) == FAIL) return FALSE; --Insstart.lnum; Insstart.col = MAXCOL; } /* * In replace mode: * cc < 0: NL was inserted, delete it * cc >= 0: NL was replaced, put original characters back */ cc = -1; if (State & REPLACE_FLAG) cc = replace_pop(); /* returns -1 if NL was inserted */ /* * In replace mode, in the line we started replacing, we only move the * cursor. */ if ((State & REPLACE_FLAG) && curwin->w_cursor.lnum <= lnum) { dec_cursor(); } else { #ifdef FEAT_VREPLACE if (!(State & VREPLACE_FLAG) || curwin->w_cursor.lnum > orig_line_count) #endif { temp = gchar_cursor(); /* remember current char */ --curwin->w_cursor.lnum; /* When "aw" is in 'formatoptions' we must delete the space at * the end of the line, otherwise the line will be broken * again when auto-formatting. */ if (has_format_option(FO_AUTO) && has_format_option(FO_WHITE_PAR)) { char_u *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE); int len; len = (int)STRLEN(ptr); if (len > 0 && ptr[len - 1] == ' ') ptr[len - 1] = NUL; } (void)do_join(2, FALSE, FALSE, FALSE); if (temp == NUL && gchar_cursor() != NUL) inc_cursor(); } #ifdef FEAT_VREPLACE else dec_cursor(); #endif /* * In REPLACE mode we have to put back the text that was replaced * by the NL. On the replace stack is first a NUL-terminated * sequence of characters that were deleted and then the * characters that NL replaced. */ if (State & REPLACE_FLAG) { /* * Do the next ins_char() in NORMAL state, to * prevent ins_char() from replacing characters and * avoiding showmatch(). */ oldState = State; State = NORMAL; /* * restore characters (blanks) deleted after cursor */ while (cc > 0) { save_col = curwin->w_cursor.col; #ifdef FEAT_MBYTE mb_replace_pop_ins(cc); #else ins_char(cc); #endif curwin->w_cursor.col = save_col; cc = replace_pop(); } /* restore the characters that NL replaced */ replace_pop_ins(); State = oldState; } } did_ai = FALSE; } else { /* * Delete character(s) before the cursor. */ #ifdef FEAT_RIGHTLEFT if (revins_on) /* put cursor on last inserted char */ dec_cursor(); #endif mincol = 0; /* keep indent */ if (mode == BACKSPACE_LINE && (curbuf->b_p_ai #ifdef FEAT_CINDENT || cindent_on() #endif ) #ifdef FEAT_RIGHTLEFT && !revins_on #endif ) { save_col = curwin->w_cursor.col; beginline(BL_WHITE); if (curwin->w_cursor.col < save_col) mincol = curwin->w_cursor.col; curwin->w_cursor.col = save_col; } /* * Handle deleting one 'shiftwidth' or 'softtabstop'. */ if ( mode == BACKSPACE_CHAR && ((p_sta && in_indent) || (curbuf->b_p_sts != 0 && curwin->w_cursor.col > 0 && (*(ml_get_cursor() - 1) == TAB || (*(ml_get_cursor() - 1) == ' ' && (!*inserted_space_p || arrow_used)))))) { int ts; colnr_T vcol; colnr_T want_vcol; colnr_T start_vcol; *inserted_space_p = FALSE; if (p_sta && in_indent) ts = curbuf->b_p_sw; else ts = curbuf->b_p_sts; /* Compute the virtual column where we want to be. Since * 'showbreak' may get in the way, need to get the last column of * the previous character. */ getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL); start_vcol = vcol; dec_cursor(); getvcol(curwin, &curwin->w_cursor, NULL, NULL, &want_vcol); inc_cursor(); want_vcol = (want_vcol / ts) * ts; /* delete characters until we are at or before want_vcol */ while (vcol > want_vcol && (cc = *(ml_get_cursor() - 1), vim_iswhite(cc))) ins_bs_one(&vcol); /* insert extra spaces until we are at want_vcol */ while (vcol < want_vcol) { /* Remember the first char we inserted */ if (curwin->w_cursor.lnum == Insstart.lnum && curwin->w_cursor.col < Insstart.col) Insstart.col = curwin->w_cursor.col; #ifdef FEAT_VREPLACE if (State & VREPLACE_FLAG) ins_char(' '); else #endif { ins_str((char_u *)" "); if ((State & REPLACE_FLAG)) replace_push(NUL); } getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL); } /* If we are now back where we started delete one character. Can * happen when using 'sts' and 'linebreak'. */ if (vcol >= start_vcol) ins_bs_one(&vcol); } /* * Delete upto starting point, start of line or previous word. */ else do { #ifdef FEAT_RIGHTLEFT if (!revins_on) /* put cursor on char to be deleted */ #endif dec_cursor(); /* start of word? */ if (mode == BACKSPACE_WORD && !vim_isspace(gchar_cursor())) { mode = BACKSPACE_WORD_NOT_SPACE; temp = vim_iswordc(gchar_cursor()); } /* end of word? */ else if (mode == BACKSPACE_WORD_NOT_SPACE && (vim_isspace(cc = gchar_cursor()) || vim_iswordc(cc) != temp)) { #ifdef FEAT_RIGHTLEFT if (!revins_on) #endif inc_cursor(); #ifdef FEAT_RIGHTLEFT else if (State & REPLACE_FLAG) dec_cursor(); #endif break; } if (State & REPLACE_FLAG) replace_do_bs(-1); else { #ifdef FEAT_MBYTE if (enc_utf8 && p_deco) (void)utfc_ptr2char(ml_get_cursor(), cpc); #endif (void)del_char(FALSE); #ifdef FEAT_MBYTE /* * If there are combining characters and 'delcombine' is set * move the cursor back. Don't back up before the base * character. */ if (enc_utf8 && p_deco && cpc[0] != NUL) inc_cursor(); #endif #ifdef FEAT_RIGHTLEFT if (revins_chars) { revins_chars--; revins_legal++; } if (revins_on && gchar_cursor() == NUL) break; #endif } /* Just a single backspace?: */ if (mode == BACKSPACE_CHAR) break; } while ( #ifdef FEAT_RIGHTLEFT revins_on || #endif (curwin->w_cursor.col > mincol && (curwin->w_cursor.lnum != Insstart.lnum || curwin->w_cursor.col != Insstart.col))); did_backspace = TRUE; } #ifdef FEAT_SMARTINDENT did_si = FALSE; can_si = FALSE; can_si_back = FALSE; #endif if (curwin->w_cursor.col <= 1) did_ai = FALSE; /* * It's a little strange to put backspaces into the redo * buffer, but it makes auto-indent a lot easier to deal * with. */ AppendCharToRedobuff(c); /* If deleted before the insertion point, adjust it */ if (curwin->w_cursor.lnum == Insstart.lnum && curwin->w_cursor.col < Insstart.col) Insstart.col = curwin->w_cursor.col; /* vi behaviour: the cursor moves backward but the character that * was there remains visible * Vim behaviour: the cursor moves backward and the character that * was there is erased from the screen. * We can emulate the vi behaviour by pretending there is a dollar * displayed even when there isn't. * --pkv Sun Jan 19 01:56:40 EST 2003 */ if (vim_strchr(p_cpo, CPO_BACKSPACE) != NULL && dollar_vcol == -1) dollar_vcol = curwin->w_virtcol; #ifdef FEAT_FOLDING /* When deleting a char the cursor line must never be in a closed fold. * E.g., when 'foldmethod' is indent and deleting the first non-white * char before a Tab. */ if (did_backspace) foldOpenCursor(); #endif return did_backspace; } #ifdef FEAT_MOUSE static void ins_mouse(c) int c; { pos_T tpos; win_T *old_curwin = curwin; # ifdef FEAT_GUI /* When GUI is active, also move/paste when 'mouse' is empty */ if (!gui.in_use) # endif if (!mouse_has(MOUSE_INSERT)) return; undisplay_dollar(); tpos = curwin->w_cursor; if (do_mouse(NULL, c, BACKWARD, 1L, 0)) { #ifdef FEAT_WINDOWS win_T *new_curwin = curwin; if (curwin != old_curwin && win_valid(old_curwin)) { /* Mouse took us to another window. We need to go back to the * previous one to stop insert there properly. */ curwin = old_curwin; curbuf = curwin->w_buffer; } #endif start_arrow(curwin == old_curwin ? &tpos : NULL); #ifdef FEAT_WINDOWS if (curwin != new_curwin && win_valid(new_curwin)) { curwin = new_curwin; curbuf = curwin->w_buffer; } #endif # ifdef FEAT_CINDENT can_cindent = TRUE; # endif } #ifdef FEAT_WINDOWS /* redraw status lines (in case another window became active) */ redraw_statuslines(); #endif } static void ins_mousescroll(dir) int dir; { pos_T tpos; # if defined(FEAT_WINDOWS) win_T *old_curwin = curwin; # endif # ifdef FEAT_INS_EXPAND int did_scroll = FALSE; # endif tpos = curwin->w_cursor; # if defined(FEAT_GUI) && defined(FEAT_WINDOWS) /* Currently the mouse coordinates are only known in the GUI. */ if (gui.in_use && mouse_row >= 0 && mouse_col >= 0) { int row, col; row = mouse_row; col = mouse_col; /* find the window at the pointer coordinates */ curwin = mouse_find_win(&row, &col); curbuf = curwin->w_buffer; } if (curwin == old_curwin) # endif undisplay_dollar(); # ifdef FEAT_INS_EXPAND /* Don't scroll the window in which completion is being done. */ if (!pum_visible() # if defined(FEAT_WINDOWS) || curwin != old_curwin # endif ) # endif { if (dir == MSCR_DOWN || dir == MSCR_UP) { if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)) scroll_redraw(dir, (long)(curwin->w_botline - curwin->w_topline)); else scroll_redraw(dir, 3L); } #ifdef FEAT_GUI else { int val, step = 6; if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)) step = W_WIDTH(curwin); val = curwin->w_leftcol + (dir == MSCR_RIGHT ? -step : step); if (val < 0) val = 0; gui_do_horiz_scroll(val, TRUE); } #endif # ifdef FEAT_INS_EXPAND did_scroll = TRUE; # endif } # if defined(FEAT_GUI) && defined(FEAT_WINDOWS) curwin->w_redr_status = TRUE; curwin = old_curwin; curbuf = curwin->w_buffer; # endif # ifdef FEAT_INS_EXPAND /* The popup menu may overlay the window, need to redraw it. * TODO: Would be more efficient to only redraw the windows that are * overlapped by the popup menu. */ if (pum_visible() && did_scroll) { redraw_all_later(NOT_VALID); ins_compl_show_pum(); } # endif if (!equalpos(curwin->w_cursor, tpos)) { start_arrow(&tpos); # ifdef FEAT_CINDENT can_cindent = TRUE; # endif } } #endif #if defined(FEAT_GUI_TABLINE) || defined(PROTO) static void ins_tabline(c) int c; { /* We will be leaving the current window, unless closing another tab. */ if (c != K_TABMENU || current_tabmenu != TABLINE_MENU_CLOSE || (current_tab != 0 && current_tab != tabpage_index(curtab))) { undisplay_dollar(); start_arrow(&curwin->w_cursor); # ifdef FEAT_CINDENT can_cindent = TRUE; # endif } if (c == K_TABLINE) goto_tabpage(current_tab); else { handle_tabmenu(); redraw_statuslines(); /* will redraw the tabline when needed */ } } #endif #if defined(FEAT_GUI) || defined(PROTO) void ins_scroll() { pos_T tpos; undisplay_dollar(); tpos = curwin->w_cursor; if (gui_do_scroll()) { start_arrow(&tpos); # ifdef FEAT_CINDENT can_cindent = TRUE; # endif } } void ins_horscroll() { pos_T tpos; undisplay_dollar(); tpos = curwin->w_cursor; if (gui_do_horiz_scroll(scrollbar_value, FALSE)) { start_arrow(&tpos); # ifdef FEAT_CINDENT can_cindent = TRUE; # endif } } #endif static void ins_left() { pos_T tpos; #ifdef FEAT_FOLDING if ((fdo_flags & FDO_HOR) && KeyTyped) foldOpenCursor(); #endif undisplay_dollar(); tpos = curwin->w_cursor; if (oneleft() == OK) { #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK) /* Only call start_arrow() when not busy with preediting, it will * break undo. K_LEFT is inserted in im_correct_cursor(). */ if (!im_is_preediting()) #endif start_arrow(&tpos); #ifdef FEAT_RIGHTLEFT /* If exit reversed string, position is fixed */ if (revins_scol != -1 && (int)curwin->w_cursor.col >= revins_scol) revins_legal++; revins_chars++; #endif } /* * if 'whichwrap' set for cursor in insert mode may go to * previous line */ else if (vim_strchr(p_ww, '[') != NULL && curwin->w_cursor.lnum > 1) { start_arrow(&tpos); --(curwin->w_cursor.lnum); coladvance((colnr_T)MAXCOL); curwin->w_set_curswant = TRUE; /* so we stay at the end */ } else vim_beep(); } static void ins_home(c) int c; { pos_T tpos; #ifdef FEAT_FOLDING if ((fdo_flags & FDO_HOR) && KeyTyped) foldOpenCursor(); #endif undisplay_dollar(); tpos = curwin->w_cursor; if (c == K_C_HOME) curwin->w_cursor.lnum = 1; curwin->w_cursor.col = 0; #ifdef FEAT_VIRTUALEDIT curwin->w_cursor.coladd = 0; #endif curwin->w_curswant = 0; start_arrow(&tpos); } static void ins_end(c) int c; { pos_T tpos; #ifdef FEAT_FOLDING if ((fdo_flags & FDO_HOR) && KeyTyped) foldOpenCursor(); #endif undisplay_dollar(); tpos = curwin->w_cursor; if (c == K_C_END) curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; coladvance((colnr_T)MAXCOL); curwin->w_curswant = MAXCOL; start_arrow(&tpos); } static void ins_s_left() { #ifdef FEAT_FOLDING if ((fdo_flags & FDO_HOR) && KeyTyped) foldOpenCursor(); #endif undisplay_dollar(); if (curwin->w_cursor.lnum > 1 || curwin->w_cursor.col > 0) { start_arrow(&curwin->w_cursor); (void)bck_word(1L, FALSE, FALSE); curwin->w_set_curswant = TRUE; } else vim_beep(); } static void ins_right() { #ifdef FEAT_FOLDING if ((fdo_flags & FDO_HOR) && KeyTyped) foldOpenCursor(); #endif undisplay_dollar(); if (gchar_cursor() != NUL #ifdef FEAT_VIRTUALEDIT || virtual_active() #endif ) { start_arrow(&curwin->w_cursor); curwin->w_set_curswant = TRUE; #ifdef FEAT_VIRTUALEDIT if (virtual_active()) oneright(); else #endif { #ifdef FEAT_MBYTE if (has_mbyte) curwin->w_cursor.col += (*mb_ptr2len)(ml_get_cursor()); else #endif ++curwin->w_cursor.col; } #ifdef FEAT_RIGHTLEFT revins_legal++; if (revins_chars) revins_chars--; #endif } /* if 'whichwrap' set for cursor in insert mode, may move the * cursor to the next line */ else if (vim_strchr(p_ww, ']') != NULL && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count) { start_arrow(&curwin->w_cursor); curwin->w_set_curswant = TRUE; ++curwin->w_cursor.lnum; curwin->w_cursor.col = 0; } else vim_beep(); } static void ins_s_right() { #ifdef FEAT_FOLDING if ((fdo_flags & FDO_HOR) && KeyTyped) foldOpenCursor(); #endif undisplay_dollar(); if (curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count || gchar_cursor() != NUL) { start_arrow(&curwin->w_cursor); (void)fwd_word(1L, FALSE, 0); curwin->w_set_curswant = TRUE; } else vim_beep(); } static void ins_up(startcol) int startcol; /* when TRUE move to Insstart.col */ { pos_T tpos; linenr_T old_topline = curwin->w_topline; #ifdef FEAT_DIFF int old_topfill = curwin->w_topfill; #endif undisplay_dollar(); tpos = curwin->w_cursor; if (cursor_up(1L, TRUE) == OK) { if (startcol) coladvance(getvcol_nolist(&Insstart)); if (old_topline != curwin->w_topline #ifdef FEAT_DIFF || old_topfill != curwin->w_topfill #endif ) redraw_later(VALID); start_arrow(&tpos); #ifdef FEAT_CINDENT can_cindent = TRUE; #endif } else vim_beep(); } static void ins_pageup() { pos_T tpos; undisplay_dollar(); #ifdef FEAT_WINDOWS if (mod_mask & MOD_MASK_CTRL) { /* <C-PageUp>: tab page back */ if (first_tabpage->tp_next != NULL) { start_arrow(&curwin->w_cursor); goto_tabpage(-1); } return; } #endif tpos = curwin->w_cursor; if (onepage(BACKWARD, 1L) == OK) { start_arrow(&tpos); #ifdef FEAT_CINDENT can_cindent = TRUE; #endif } else vim_beep(); } static void ins_down(startcol) int startcol; /* when TRUE move to Insstart.col */ { pos_T tpos; linenr_T old_topline = curwin->w_topline; #ifdef FEAT_DIFF int old_topfill = curwin->w_topfill; #endif undisplay_dollar(); tpos = curwin->w_cursor; if (cursor_down(1L, TRUE) == OK) { if (startcol) coladvance(getvcol_nolist(&Insstart)); if (old_topline != curwin->w_topline #ifdef FEAT_DIFF || old_topfill != curwin->w_topfill #endif ) redraw_later(VALID); start_arrow(&tpos); #ifdef FEAT_CINDENT can_cindent = TRUE; #endif } else vim_beep(); } static void ins_pagedown() { pos_T tpos; undisplay_dollar(); #ifdef FEAT_WINDOWS if (mod_mask & MOD_MASK_CTRL) { /* <C-PageDown>: tab page forward */ if (first_tabpage->tp_next != NULL) { start_arrow(&curwin->w_cursor); goto_tabpage(0); } return; } #endif tpos = curwin->w_cursor; if (onepage(FORWARD, 1L) == OK) { start_arrow(&tpos); #ifdef FEAT_CINDENT can_cindent = TRUE; #endif } else vim_beep(); } #ifdef FEAT_DND static void ins_drop() { do_put('~', BACKWARD, 1L, PUT_CURSEND); } #endif /* * Handle TAB in Insert or Replace mode. * Return TRUE when the TAB needs to be inserted like a normal character. */ static int ins_tab() { int ind; int i; int temp; if (Insstart_blank_vcol == MAXCOL && curwin->w_cursor.lnum == Insstart.lnum) Insstart_blank_vcol = get_nolist_virtcol(); if (echeck_abbr(TAB + ABBR_OFF)) return FALSE; ind = inindent(0); #ifdef FEAT_CINDENT if (ind) can_cindent = FALSE; #endif /* * When nothing special, insert TAB like a normal character */ if (!curbuf->b_p_et && !(p_sta && ind && curbuf->b_p_ts != curbuf->b_p_sw) && curbuf->b_p_sts == 0) return TRUE; if (stop_arrow() == FAIL) return TRUE; did_ai = FALSE; #ifdef FEAT_SMARTINDENT did_si = FALSE; can_si = FALSE; can_si_back = FALSE; #endif AppendToRedobuff((char_u *)"\t"); if (p_sta && ind) /* insert tab in indent, use 'shiftwidth' */ temp = (int)curbuf->b_p_sw; else if (curbuf->b_p_sts > 0) /* use 'softtabstop' when set */ temp = (int)curbuf->b_p_sts; else /* otherwise use 'tabstop' */ temp = (int)curbuf->b_p_ts; temp -= get_nolist_virtcol() % temp; /* * Insert the first space with ins_char(). It will delete one char in * replace mode. Insert the rest with ins_str(); it will not delete any * chars. For VREPLACE mode, we use ins_char() for all characters. */ ins_char(' '); while (--temp > 0) { #ifdef FEAT_VREPLACE if (State & VREPLACE_FLAG) ins_char(' '); else #endif { ins_str((char_u *)" "); if (State & REPLACE_FLAG) /* no char replaced */ replace_push(NUL); } } /* * When 'expandtab' not set: Replace spaces by TABs where possible. */ if (!curbuf->b_p_et && (curbuf->b_p_sts || (p_sta && ind))) { char_u *ptr; #ifdef FEAT_VREPLACE char_u *saved_line = NULL; /* init for GCC */ pos_T pos; #endif pos_T fpos; pos_T *cursor; colnr_T want_vcol, vcol; int change_col = -1; int save_list = curwin->w_p_list; /* * Get the current line. For VREPLACE mode, don't make real changes * yet, just work on a copy of the line. */ #ifdef FEAT_VREPLACE if (State & VREPLACE_FLAG) { pos = curwin->w_cursor; cursor = &pos; saved_line = vim_strsave(ml_get_curline()); if (saved_line == NULL) return FALSE; ptr = saved_line + pos.col; } else #endif { ptr = ml_get_cursor(); cursor = &curwin->w_cursor; } /* When 'L' is not in 'cpoptions' a tab always takes up 'ts' spaces. */ if (vim_strchr(p_cpo, CPO_LISTWM) == NULL) curwin->w_p_list = FALSE; /* Find first white before the cursor */ fpos = curwin->w_cursor; while (fpos.col > 0 && vim_iswhite(ptr[-1])) { --fpos.col; --ptr; } /* In Replace mode, don't change characters before the insert point. */ if ((State & REPLACE_FLAG) && fpos.lnum == Insstart.lnum && fpos.col < Insstart.col) { ptr += Insstart.col - fpos.col; fpos.col = Insstart.col; } /* compute virtual column numbers of first white and cursor */ getvcol(curwin, &fpos, &vcol, NULL, NULL); getvcol(curwin, cursor, &want_vcol, NULL, NULL); /* Use as many TABs as possible. Beware of 'showbreak' and * 'linebreak' adding extra virtual columns. */ while (vim_iswhite(*ptr)) { i = lbr_chartabsize((char_u *)"\t", vcol); if (vcol + i > want_vcol) break; if (*ptr != TAB) { *ptr = TAB; if (change_col < 0) { change_col = fpos.col; /* Column of first change */ /* May have to adjust Insstart */ if (fpos.lnum == Insstart.lnum && fpos.col < Insstart.col) Insstart.col = fpos.col; } } ++fpos.col; ++ptr; vcol += i; } if (change_col >= 0) { int repl_off = 0; /* Skip over the spaces we need. */ while (vcol < want_vcol && *ptr == ' ') { vcol += lbr_chartabsize(ptr, vcol); ++ptr; ++repl_off; } if (vcol > want_vcol) { /* Must have a char with 'showbreak' just before it. */ --ptr; --repl_off; } fpos.col += repl_off; /* Delete following spaces. */ i = cursor->col - fpos.col; if (i > 0) { STRMOVE(ptr, ptr + i); /* correct replace stack. */ if ((State & REPLACE_FLAG) #ifdef FEAT_VREPLACE && !(State & VREPLACE_FLAG) #endif ) for (temp = i; --temp >= 0; ) replace_join(repl_off); } #ifdef FEAT_NETBEANS_INTG if (netbeans_active()) { netbeans_removed(curbuf, fpos.lnum, cursor->col, (long)(i + 1)); netbeans_inserted(curbuf, fpos.lnum, cursor->col, (char_u *)"\t", 1); } #endif cursor->col -= i; #ifdef FEAT_VREPLACE /* * In VREPLACE mode, we haven't changed anything yet. Do it now by * backspacing over the changed spacing and then inserting the new * spacing. */ if (State & VREPLACE_FLAG) { /* Backspace from real cursor to change_col */ backspace_until_column(change_col); /* Insert each char in saved_line from changed_col to * ptr-cursor */ ins_bytes_len(saved_line + change_col, cursor->col - change_col); } #endif } #ifdef FEAT_VREPLACE if (State & VREPLACE_FLAG) vim_free(saved_line); #endif curwin->w_p_list = save_list; } return FALSE; } /* * Handle CR or NL in insert mode. * Return TRUE when out of memory or can't undo. */ static int ins_eol(c) int c; { int i; if (echeck_abbr(c + ABBR_OFF)) return FALSE; if (stop_arrow() == FAIL) return TRUE; undisplay_dollar(); /* * Strange Vi behaviour: In Replace mode, typing a NL will not delete the * character under the cursor. Only push a NUL on the replace stack, * nothing to put back when the NL is deleted. */ if ((State & REPLACE_FLAG) #ifdef FEAT_VREPLACE && !(State & VREPLACE_FLAG) #endif ) replace_push(NUL); /* * In VREPLACE mode, a NL replaces the rest of the line, and starts * replacing the next line, so we push all of the characters left on the * line onto the replace stack. This is not done here though, it is done * in open_line(). */ #ifdef FEAT_VIRTUALEDIT /* Put cursor on NUL if on the last char and coladd is 1 (happens after * CTRL-O). */ if (virtual_active() && curwin->w_cursor.coladd > 0) coladvance(getviscol()); #endif #ifdef FEAT_RIGHTLEFT # ifdef FEAT_FKMAP if (p_altkeymap && p_fkmap) fkmap(NL); # endif /* NL in reverse insert will always start in the end of * current line. */ if (revins_on) curwin->w_cursor.col += (colnr_T)STRLEN(ml_get_cursor()); #endif AppendToRedobuff(NL_STR); i = open_line(FORWARD, #ifdef FEAT_COMMENTS has_format_option(FO_RET_COMS) ? OPENLINE_DO_COM : #endif 0, old_indent); old_indent = 0; #ifdef FEAT_CINDENT can_cindent = TRUE; #endif #ifdef FEAT_FOLDING /* When inserting a line the cursor line must never be in a closed fold. */ foldOpenCursor(); #endif return (!i); } #ifdef FEAT_DIGRAPHS /* * Handle digraph in insert mode. * Returns character still to be inserted, or NUL when nothing remaining to be * done. */ static int ins_digraph() { int c; int cc; int did_putchar = FALSE; pc_status = PC_STATUS_UNSET; if (redrawing() && !char_avail()) { /* may need to redraw when no more chars available now */ ins_redraw(FALSE); edit_putchar('?', TRUE); did_putchar = TRUE; #ifdef FEAT_CMDL_INFO add_to_showcmd_c(Ctrl_K); #endif } #ifdef USE_ON_FLY_SCROLL dont_scroll = TRUE; /* disallow scrolling here */ #endif /* don't map the digraph chars. This also prevents the * mode message to be deleted when ESC is hit */ ++no_mapping; ++allow_keys; c = plain_vgetc(); --no_mapping; --allow_keys; if (did_putchar) /* when the line fits in 'columns' the '?' is at the start of the next * line and will not be removed by the redraw */ edit_unputchar(); if (IS_SPECIAL(c) || mod_mask) /* special key */ { #ifdef FEAT_CMDL_INFO clear_showcmd(); #endif insert_special(c, TRUE, FALSE); return NUL; } if (c != ESC) { did_putchar = FALSE; if (redrawing() && !char_avail()) { /* may need to redraw when no more chars available now */ ins_redraw(FALSE); if (char2cells(c) == 1) { ins_redraw(FALSE); edit_putchar(c, TRUE); did_putchar = TRUE; } #ifdef FEAT_CMDL_INFO add_to_showcmd_c(c); #endif } ++no_mapping; ++allow_keys; cc = plain_vgetc(); --no_mapping; --allow_keys; if (did_putchar) /* when the line fits in 'columns' the '?' is at the start of the * next line and will not be removed by a redraw */ edit_unputchar(); if (cc != ESC) { AppendToRedobuff((char_u *)CTRL_V_STR); c = getdigraph(c, cc, TRUE); #ifdef FEAT_CMDL_INFO clear_showcmd(); #endif return c; } } #ifdef FEAT_CMDL_INFO clear_showcmd(); #endif return NUL; } #endif /* * Handle CTRL-E and CTRL-Y in Insert mode: copy char from other line. * Returns the char to be inserted, or NUL if none found. */ int ins_copychar(lnum) linenr_T lnum; { int c; int temp; char_u *ptr, *prev_ptr; if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count) { vim_beep(); return NUL; } /* try to advance to the cursor column */ temp = 0; ptr = ml_get(lnum); prev_ptr = ptr; validate_virtcol(); while ((colnr_T)temp < curwin->w_virtcol && *ptr != NUL) { prev_ptr = ptr; temp += lbr_chartabsize_adv(&ptr, (colnr_T)temp); } if ((colnr_T)temp > curwin->w_virtcol) ptr = prev_ptr; #ifdef FEAT_MBYTE c = (*mb_ptr2char)(ptr); #else c = *ptr; #endif if (c == NUL) vim_beep(); return c; } /* * CTRL-Y or CTRL-E typed in Insert mode. */ static int ins_ctrl_ey(tc) int tc; { int c = tc; #ifdef FEAT_INS_EXPAND if (ctrl_x_mode == CTRL_X_SCROLL) { if (c == Ctrl_Y) scrolldown_clamp(); else scrollup_clamp(); redraw_later(VALID); } else #endif { c = ins_copychar(curwin->w_cursor.lnum + (c == Ctrl_Y ? -1 : 1)); if (c != NUL) { long tw_save; /* The character must be taken literally, insert like it * was typed after a CTRL-V, and pretend 'textwidth' * wasn't set. Digits, 'o' and 'x' are special after a * CTRL-V, don't use it for these. */ if (c < 256 && !isalnum(c)) AppendToRedobuff((char_u *)CTRL_V_STR); /* CTRL-V */ tw_save = curbuf->b_p_tw; curbuf->b_p_tw = -1; insert_special(c, TRUE, FALSE); curbuf->b_p_tw = tw_save; #ifdef FEAT_RIGHTLEFT revins_chars++; revins_legal++; #endif c = Ctrl_V; /* pretend CTRL-V is last character */ auto_format(FALSE, TRUE); } } return c; } #ifdef FEAT_SMARTINDENT /* * Try to do some very smart auto-indenting. * Used when inserting a "normal" character. */ static void ins_try_si(c) int c; { pos_T *pos, old_pos; char_u *ptr; int i; int temp; /* * do some very smart indenting when entering '{' or '}' */ if (((did_si || can_si_back) && c == '{') || (can_si && c == '}')) { /* * for '}' set indent equal to indent of line containing matching '{' */ if (c == '}' && (pos = findmatch(NULL, '{')) != NULL) { old_pos = curwin->w_cursor; /* * If the matching '{' has a ')' immediately before it (ignoring * white-space), then line up with the start of the line * containing the matching '(' if there is one. This handles the * case where an "if (..\n..) {" statement continues over multiple * lines -- webb */ ptr = ml_get(pos->lnum); i = pos->col; if (i > 0) /* skip blanks before '{' */ while (--i > 0 && vim_iswhite(ptr[i])) ; curwin->w_cursor.lnum = pos->lnum; curwin->w_cursor.col = i; if (ptr[i] == ')' && (pos = findmatch(NULL, '(')) != NULL) curwin->w_cursor = *pos; i = get_indent(); curwin->w_cursor = old_pos; #ifdef FEAT_VREPLACE if (State & VREPLACE_FLAG) change_indent(INDENT_SET, i, FALSE, NUL, TRUE); else #endif (void)set_indent(i, SIN_CHANGED); } else if (curwin->w_cursor.col > 0) { /* * when inserting '{' after "O" reduce indent, but not * more than indent of previous line */ temp = TRUE; if (c == '{' && can_si_back && curwin->w_cursor.lnum > 1) { old_pos = curwin->w_cursor; i = get_indent(); while (curwin->w_cursor.lnum > 1) { ptr = skipwhite(ml_get(--(curwin->w_cursor.lnum))); /* ignore empty lines and lines starting with '#'. */ if (*ptr != '#' && *ptr != NUL) break; } if (get_indent() >= i) temp = FALSE; curwin->w_cursor = old_pos; } if (temp) shift_line(TRUE, FALSE, 1, TRUE); } } /* * set indent of '#' always to 0 */ if (curwin->w_cursor.col > 0 && can_si && c == '#') { /* remember current indent for next line */ old_indent = get_indent(); (void)set_indent(0, SIN_CHANGED); } /* Adjust ai_col, the char at this position can be deleted. */ if (ai_col > curwin->w_cursor.col) ai_col = curwin->w_cursor.col; } #endif /* * Get the value that w_virtcol would have when 'list' is off. * Unless 'cpo' contains the 'L' flag. */ static colnr_T get_nolist_virtcol() { if (curwin->w_p_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL) return getvcol_nolist(&curwin->w_cursor); validate_virtcol(); return curwin->w_virtcol; } #ifdef FEAT_AUTOCMD /* * Handle the InsertCharPre autocommand. * "c" is the character that was typed. * Return a pointer to allocated memory with the replacement string. * Return NULL to continue inserting "c". */ static char_u * do_insert_char_pre(c) int c; { char_u *res; char_u buf[MB_MAXBYTES + 1]; /* Return quickly when there is nothing to do. */ if (!has_insertcharpre()) return NULL; #ifdef FEAT_MBYTE if (has_mbyte) buf[(*mb_char2bytes)(c, buf)] = NUL; else #endif { buf[0] = c; buf[1] = NUL; } /* Lock the text to avoid weird things from happening. */ ++textlock; set_vim_var_string(VV_CHAR, buf, -1); /* set v:char */ res = NULL; if (apply_autocmds(EVENT_INSERTCHARPRE, NULL, NULL, FALSE, curbuf)) { /* Get the value of v:char. It may be empty or more than one * character. Only use it when changed, otherwise continue with the * original character to avoid breaking autoindent. */ if (STRCMP(buf, get_vim_var_str(VV_CHAR)) != 0) res = vim_strsave(get_vim_var_str(VV_CHAR)); } set_vim_var_string(VV_CHAR, NULL, -1); /* clear v:char */ --textlock; return res; } #endif
zyz2011-vim
src/edit.c
C
gpl2
252,815
:: command to build big Vim with OLE, Perl, Python, Ruby and Tcl nmake -f Make_mvc.mak GUI=yes OLE=yes PERL=E:\perl512 DYNAMIC_PERL=yes PERL_VER=512 PYTHON=e:\python27 DYNAMIC_PYTHON=yes PYTHON_VER=27 PYTHON3=e:\python31 DYNAMIC_PYTHON3=yes PYTHON3_VER=31 RUBY=e:\ruby191 DYNAMIC_RUBY=yes RUBY_VER=191 RUBY_VER_LONG=1.9.1 TCL=e:\tcl DYNAMIC_TCL=yes %1 IME=yes CSCOPE=yes XPM=e:\xpm
zyz2011-vim
src/bigvim.bat
Batchfile
gpl2
383
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Ruby interface by Shugo Maeda * with improvements by SegPhault (Ryan Paul) * with improvements by Jon Maken * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ #ifdef HAVE_CONFIG_H # include "auto/config.h" #endif #include <stdio.h> #include <string.h> #ifdef _WIN32 # if !defined(DYNAMIC_RUBY_VER) || (DYNAMIC_RUBY_VER < 18) # define NT # endif # ifndef DYNAMIC_RUBY # define IMPORT /* For static dll usage __declspec(dllimport) */ # define RUBYEXTERN __declspec(dllimport) # endif #endif #ifndef RUBYEXTERN # define RUBYEXTERN extern #endif #ifdef DYNAMIC_RUBY /* * This is tricky. In ruby.h there is (inline) function rb_class_of() * definition. This function use these variables. But we want function to * use dll_* variables. */ # define rb_cFalseClass (*dll_rb_cFalseClass) # define rb_cFixnum (*dll_rb_cFixnum) # define rb_cNilClass (*dll_rb_cNilClass) # define rb_cSymbol (*dll_rb_cSymbol) # define rb_cTrueClass (*dll_rb_cTrueClass) # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18 /* * On ver 1.8, all Ruby functions are exported with "__declspec(dllimport)" * in ruby.h. But it causes trouble for these variables, because it is * defined in this file. When defined this RUBY_EXPORT it modified to * "extern" and be able to avoid this problem. */ # define RUBY_EXPORT # endif #if !(defined(WIN32) || defined(_WIN64)) # include <dlfcn.h> # define HINSTANCE void* # define RUBY_PROC void* # define load_dll(n) dlopen((n), RTLD_LAZY|RTLD_GLOBAL) # define symbol_from_dll dlsym # define close_dll dlclose #else # define RUBY_PROC FARPROC # define load_dll vimLoadLib # define symbol_from_dll GetProcAddress # define close_dll FreeLibrary #endif #endif /* ifdef DYNAMIC_RUBY */ /* suggested by Ariya Mizutani */ #if (_MSC_VER == 1200) # undef _WIN32_WINNT #endif #if (defined(RUBY_VERSION) && RUBY_VERSION >= 19) \ || (defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 19) # define RUBY19_OR_LATER 1 #endif #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 19 /* Ruby 1.9 defines a number of static functions which use rb_num2long and * rb_int2big */ # define rb_num2long rb_num2long_stub # define rb_int2big rb_int2big_stub #endif #include <ruby.h> #ifdef RUBY19_OR_LATER # include <ruby/encoding.h> #endif #undef off_t /* ruby defines off_t as _int64, Mingw uses long */ #undef EXTERN #undef _ /* T_DATA defined both by Ruby and Mac header files, hack around it... */ #if defined(MACOS_X_UNIX) || defined(macintosh) # define __OPENTRANSPORT__ # define __OPENTRANSPORTPROTOCOL__ # define __OPENTRANSPORTPROVIDERS__ #endif /* * Backward compatiblity for Ruby 1.8 and earlier. * Ruby 1.9 does not provide STR2CSTR, instead StringValuePtr is provided. * Ruby 1.9 does not provide RXXX(s)->len and RXXX(s)->ptr, instead * RXXX_LEN(s) and RXXX_PTR(s) are provided. */ #ifndef StringValuePtr # define StringValuePtr(s) STR2CSTR(s) #endif #ifndef RARRAY_LEN # define RARRAY_LEN(s) RARRAY(s)->len #endif #ifndef RARRAY_PTR # define RARRAY_PTR(s) RARRAY(s)->ptr #endif #ifndef RSTRING_LEN # define RSTRING_LEN(s) RSTRING(s)->len #endif #ifndef RSTRING_PTR # define RSTRING_PTR(s) RSTRING(s)->ptr #endif #include "vim.h" #include "version.h" #if defined(PROTO) && !defined(FEAT_RUBY) /* Define these to be able to generate the function prototypes. */ # define VALUE int # define RUBY_DATA_FUNC int #endif static int ruby_initialized = 0; static VALUE objtbl; static VALUE mVIM; static VALUE cBuffer; static VALUE cVimWindow; static VALUE eDeletedBufferError; static VALUE eDeletedWindowError; static int ensure_ruby_initialized(void); static void error_print(int); static void ruby_io_init(void); static void ruby_vim_init(void); #if defined(DYNAMIC_RUBY) || defined(PROTO) #ifdef PROTO # define HINSTANCE int /* for generating prototypes */ #endif /* * Wrapper defines */ #define rb_assoc_new dll_rb_assoc_new #define rb_cObject (*dll_rb_cObject) #define rb_check_type dll_rb_check_type #define rb_class_path dll_rb_class_path #define rb_data_object_alloc dll_rb_data_object_alloc #define rb_define_class_under dll_rb_define_class_under #define rb_define_const dll_rb_define_const #define rb_define_global_function dll_rb_define_global_function #define rb_define_method dll_rb_define_method #define rb_define_module dll_rb_define_module #define rb_define_module_function dll_rb_define_module_function #define rb_define_singleton_method dll_rb_define_singleton_method #define rb_define_virtual_variable dll_rb_define_virtual_variable #define rb_stdout (*dll_rb_stdout) #define rb_eArgError (*dll_rb_eArgError) #define rb_eIndexError (*dll_rb_eIndexError) #define rb_eRuntimeError (*dll_rb_eRuntimeError) #define rb_eStandardError (*dll_rb_eStandardError) #define rb_eval_string_protect dll_rb_eval_string_protect #define rb_global_variable dll_rb_global_variable #define rb_hash_aset dll_rb_hash_aset #define rb_hash_new dll_rb_hash_new #define rb_inspect dll_rb_inspect #define rb_int2inum dll_rb_int2inum #define rb_lastline_get dll_rb_lastline_get #define rb_lastline_set dll_rb_lastline_set #define rb_load_protect dll_rb_load_protect #ifndef RUBY19_OR_LATER #define rb_num2long dll_rb_num2long #endif #define rb_num2ulong dll_rb_num2ulong #define rb_obj_alloc dll_rb_obj_alloc #define rb_obj_as_string dll_rb_obj_as_string #define rb_obj_id dll_rb_obj_id #define rb_raise dll_rb_raise #define rb_str_cat dll_rb_str_cat #define rb_str_concat dll_rb_str_concat #define rb_str_new dll_rb_str_new #ifdef rb_str_new2 /* Ruby may #define rb_str_new2 to use rb_str_new_cstr. */ # define need_rb_str_new_cstr 1 /* Ruby's headers #define rb_str_new_cstr to make use of GCC's * __builtin_constant_p extension. */ # undef rb_str_new_cstr # define rb_str_new_cstr dll_rb_str_new_cstr #else # define rb_str_new2 dll_rb_str_new2 #endif #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18 # define rb_string_value dll_rb_string_value # define rb_string_value_ptr dll_rb_string_value_ptr # define rb_float_new dll_rb_float_new # define rb_ary_new dll_rb_ary_new # define rb_ary_push dll_rb_ary_push #else # define rb_str2cstr dll_rb_str2cstr #endif #ifdef RUBY19_OR_LATER # define rb_errinfo dll_rb_errinfo #else # define ruby_errinfo (*dll_ruby_errinfo) #endif #define ruby_init dll_ruby_init #define ruby_init_loadpath dll_ruby_init_loadpath #ifdef WIN3264 # define NtInitialize dll_NtInitialize # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18 # define rb_w32_snprintf dll_rb_w32_snprintf # endif #endif #ifdef RUBY19_OR_LATER # define ruby_script dll_ruby_script # define rb_enc_find_index dll_rb_enc_find_index # define rb_enc_find dll_rb_enc_find # define rb_enc_str_new dll_rb_enc_str_new # define rb_sprintf dll_rb_sprintf # define rb_require dll_rb_require # define ruby_init_stack dll_ruby_init_stack # define ruby_process_options dll_ruby_process_options #endif /* * Pointers for dynamic link */ static VALUE (*dll_rb_assoc_new) (VALUE, VALUE); VALUE *dll_rb_cFalseClass; VALUE *dll_rb_cFixnum; VALUE *dll_rb_cNilClass; static VALUE *dll_rb_cObject; VALUE *dll_rb_cSymbol; VALUE *dll_rb_cTrueClass; static void (*dll_rb_check_type) (VALUE,int); static VALUE (*dll_rb_class_path) (VALUE); static VALUE (*dll_rb_data_object_alloc) (VALUE, void*, RUBY_DATA_FUNC, RUBY_DATA_FUNC); static VALUE (*dll_rb_define_class_under) (VALUE, const char*, VALUE); static void (*dll_rb_define_const) (VALUE,const char*,VALUE); static void (*dll_rb_define_global_function) (const char*,VALUE(*)(),int); static void (*dll_rb_define_method) (VALUE,const char*,VALUE(*)(),int); static VALUE (*dll_rb_define_module) (const char*); static void (*dll_rb_define_module_function) (VALUE,const char*,VALUE(*)(),int); static void (*dll_rb_define_singleton_method) (VALUE,const char*,VALUE(*)(),int); static void (*dll_rb_define_virtual_variable) (const char*,VALUE(*)(),void(*)()); static VALUE *dll_rb_stdout; static VALUE *dll_rb_eArgError; static VALUE *dll_rb_eIndexError; static VALUE *dll_rb_eRuntimeError; static VALUE *dll_rb_eStandardError; static VALUE (*dll_rb_eval_string_protect) (const char*, int*); static void (*dll_rb_global_variable) (VALUE*); static VALUE (*dll_rb_hash_aset) (VALUE, VALUE, VALUE); static VALUE (*dll_rb_hash_new) (void); static VALUE (*dll_rb_inspect) (VALUE); static VALUE (*dll_rb_int2inum) (long); static VALUE (*dll_rb_int2inum) (long); static VALUE (*dll_rb_lastline_get) (void); static void (*dll_rb_lastline_set) (VALUE); static void (*dll_rb_load_protect) (VALUE, int, int*); static long (*dll_rb_num2long) (VALUE); static unsigned long (*dll_rb_num2ulong) (VALUE); static VALUE (*dll_rb_obj_alloc) (VALUE); static VALUE (*dll_rb_obj_as_string) (VALUE); static VALUE (*dll_rb_obj_id) (VALUE); static void (*dll_rb_raise) (VALUE, const char*, ...); #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18 static VALUE (*dll_rb_string_value) (volatile VALUE*); #else static char *(*dll_rb_str2cstr) (VALUE,int*); #endif static VALUE (*dll_rb_str_cat) (VALUE, const char*, long); static VALUE (*dll_rb_str_concat) (VALUE, VALUE); static VALUE (*dll_rb_str_new) (const char*, long); #ifdef need_rb_str_new_cstr /* Ruby may #define rb_str_new2 to use rb_str_new_cstr. */ static VALUE (*dll_rb_str_new_cstr) (const char*); #else static VALUE (*dll_rb_str_new2) (const char*); #endif #ifdef RUBY19_OR_LATER static VALUE (*dll_rb_errinfo) (void); #else static VALUE *dll_ruby_errinfo; #endif static void (*dll_ruby_init) (void); static void (*dll_ruby_init_loadpath) (void); #ifdef WIN3264 static void (*dll_NtInitialize) (int*, char***); # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18 static int (*dll_rb_w32_snprintf)(char*, size_t, const char*, ...); # endif #endif #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18 static char * (*dll_rb_string_value_ptr) (volatile VALUE*); static VALUE (*dll_rb_float_new) (double); static VALUE (*dll_rb_ary_new) (void); static VALUE (*dll_rb_ary_push) (VALUE, VALUE); #endif #ifdef RUBY19_OR_LATER static VALUE (*dll_rb_int2big)(SIGNED_VALUE); #endif #ifdef RUBY19_OR_LATER static void (*dll_ruby_script) (const char*); static int (*dll_rb_enc_find_index) (const char*); static rb_encoding* (*dll_rb_enc_find) (const char*); static VALUE (*dll_rb_enc_str_new) (const char*, long, rb_encoding*); static VALUE (*dll_rb_sprintf) (const char*, ...); static VALUE (*dll_rb_require) (const char*); static void (*ruby_init_stack)(VALUE*); static void* (*ruby_process_options)(int, char**); #endif #ifdef RUBY19_OR_LATER SIGNED_VALUE rb_num2long_stub(VALUE x) { return dll_rb_num2long(x); } VALUE rb_int2big_stub(SIGNED_VALUE x) { return dll_rb_int2big(x); } #endif static HINSTANCE hinstRuby = NULL; /* Instance of ruby.dll */ /* * Table of name to function pointer of ruby. */ static struct { char *name; RUBY_PROC *ptr; } ruby_funcname_table[] = { {"rb_assoc_new", (RUBY_PROC*)&dll_rb_assoc_new}, {"rb_cFalseClass", (RUBY_PROC*)&dll_rb_cFalseClass}, {"rb_cFixnum", (RUBY_PROC*)&dll_rb_cFixnum}, {"rb_cNilClass", (RUBY_PROC*)&dll_rb_cNilClass}, {"rb_cObject", (RUBY_PROC*)&dll_rb_cObject}, {"rb_cSymbol", (RUBY_PROC*)&dll_rb_cSymbol}, {"rb_cTrueClass", (RUBY_PROC*)&dll_rb_cTrueClass}, {"rb_check_type", (RUBY_PROC*)&dll_rb_check_type}, {"rb_class_path", (RUBY_PROC*)&dll_rb_class_path}, {"rb_data_object_alloc", (RUBY_PROC*)&dll_rb_data_object_alloc}, {"rb_define_class_under", (RUBY_PROC*)&dll_rb_define_class_under}, {"rb_define_const", (RUBY_PROC*)&dll_rb_define_const}, {"rb_define_global_function", (RUBY_PROC*)&dll_rb_define_global_function}, {"rb_define_method", (RUBY_PROC*)&dll_rb_define_method}, {"rb_define_module", (RUBY_PROC*)&dll_rb_define_module}, {"rb_define_module_function", (RUBY_PROC*)&dll_rb_define_module_function}, {"rb_define_singleton_method", (RUBY_PROC*)&dll_rb_define_singleton_method}, {"rb_define_virtual_variable", (RUBY_PROC*)&dll_rb_define_virtual_variable}, {"rb_stdout", (RUBY_PROC*)&dll_rb_stdout}, {"rb_eArgError", (RUBY_PROC*)&dll_rb_eArgError}, {"rb_eIndexError", (RUBY_PROC*)&dll_rb_eIndexError}, {"rb_eRuntimeError", (RUBY_PROC*)&dll_rb_eRuntimeError}, {"rb_eStandardError", (RUBY_PROC*)&dll_rb_eStandardError}, {"rb_eval_string_protect", (RUBY_PROC*)&dll_rb_eval_string_protect}, {"rb_global_variable", (RUBY_PROC*)&dll_rb_global_variable}, {"rb_hash_aset", (RUBY_PROC*)&dll_rb_hash_aset}, {"rb_hash_new", (RUBY_PROC*)&dll_rb_hash_new}, {"rb_inspect", (RUBY_PROC*)&dll_rb_inspect}, {"rb_int2inum", (RUBY_PROC*)&dll_rb_int2inum}, {"rb_lastline_get", (RUBY_PROC*)&dll_rb_lastline_get}, {"rb_lastline_set", (RUBY_PROC*)&dll_rb_lastline_set}, {"rb_load_protect", (RUBY_PROC*)&dll_rb_load_protect}, {"rb_num2long", (RUBY_PROC*)&dll_rb_num2long}, {"rb_num2ulong", (RUBY_PROC*)&dll_rb_num2ulong}, {"rb_obj_alloc", (RUBY_PROC*)&dll_rb_obj_alloc}, {"rb_obj_as_string", (RUBY_PROC*)&dll_rb_obj_as_string}, {"rb_obj_id", (RUBY_PROC*)&dll_rb_obj_id}, {"rb_raise", (RUBY_PROC*)&dll_rb_raise}, #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18 {"rb_string_value", (RUBY_PROC*)&dll_rb_string_value}, #else {"rb_str2cstr", (RUBY_PROC*)&dll_rb_str2cstr}, #endif {"rb_str_cat", (RUBY_PROC*)&dll_rb_str_cat}, {"rb_str_concat", (RUBY_PROC*)&dll_rb_str_concat}, {"rb_str_new", (RUBY_PROC*)&dll_rb_str_new}, #ifdef need_rb_str_new_cstr {"rb_str_new_cstr", (RUBY_PROC*)&dll_rb_str_new_cstr}, #else {"rb_str_new2", (RUBY_PROC*)&dll_rb_str_new2}, #endif #ifdef RUBY19_OR_LATER {"rb_errinfo", (RUBY_PROC*)&dll_rb_errinfo}, #else {"ruby_errinfo", (RUBY_PROC*)&dll_ruby_errinfo}, #endif {"ruby_init", (RUBY_PROC*)&dll_ruby_init}, {"ruby_init_loadpath", (RUBY_PROC*)&dll_ruby_init_loadpath}, #ifdef WIN3264 { # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER < 19 "NtInitialize", # else "ruby_sysinit", # endif (RUBY_PROC*)&dll_NtInitialize}, # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18 {"rb_w32_snprintf", (RUBY_PROC*)&dll_rb_w32_snprintf}, # endif #endif #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18 {"rb_string_value_ptr", (RUBY_PROC*)&dll_rb_string_value_ptr}, {"rb_float_new", (RUBY_PROC*)&dll_rb_float_new}, {"rb_ary_new", (RUBY_PROC*)&dll_rb_ary_new}, {"rb_ary_push", (RUBY_PROC*)&dll_rb_ary_push}, #endif #ifdef RUBY19_OR_LATER {"rb_int2big", (RUBY_PROC*)&dll_rb_int2big}, {"ruby_script", (RUBY_PROC*)&dll_ruby_script}, {"rb_enc_find_index", (RUBY_PROC*)&dll_rb_enc_find_index}, {"rb_enc_find", (RUBY_PROC*)&dll_rb_enc_find}, {"rb_enc_str_new", (RUBY_PROC*)&dll_rb_enc_str_new}, {"rb_sprintf", (RUBY_PROC*)&dll_rb_sprintf}, {"rb_require", (RUBY_PROC*)&dll_rb_require}, {"ruby_init_stack", (RUBY_PROC*)&dll_ruby_init_stack}, {"ruby_process_options", (RUBY_PROC*)&dll_ruby_process_options}, #endif {"", NULL}, }; /* * Free ruby.dll */ static void end_dynamic_ruby() { if (hinstRuby) { close_dll(hinstRuby); hinstRuby = NULL; } } /* * Load library and get all pointers. * Parameter 'libname' provides name of DLL. * Return OK or FAIL. */ static int ruby_runtime_link_init(char *libname, int verbose) { int i; if (hinstRuby) return OK; hinstRuby = load_dll(libname); if (!hinstRuby) { if (verbose) EMSG2(_(e_loadlib), libname); return FAIL; } for (i = 0; ruby_funcname_table[i].ptr; ++i) { if (!(*ruby_funcname_table[i].ptr = symbol_from_dll(hinstRuby, ruby_funcname_table[i].name))) { close_dll(hinstRuby); hinstRuby = NULL; if (verbose) EMSG2(_(e_loadfunc), ruby_funcname_table[i].name); return FAIL; } } return OK; } /* * If ruby is enabled (there is installed ruby on Windows system) return TRUE, * else FALSE. */ int ruby_enabled(verbose) int verbose; { return ruby_runtime_link_init(DYNAMIC_RUBY_DLL, verbose) == OK; } #endif /* defined(DYNAMIC_RUBY) || defined(PROTO) */ void ruby_end() { #ifdef DYNAMIC_RUBY end_dynamic_ruby(); #endif } void ex_ruby(exarg_T *eap) { int state; char *script = NULL; script = (char *)script_get(eap, eap->arg); if (!eap->skip && ensure_ruby_initialized()) { if (script == NULL) rb_eval_string_protect((char *)eap->arg, &state); else rb_eval_string_protect(script, &state); if (state) error_print(state); } vim_free(script); } /* * In Ruby 1.9 or later, ruby String object has encoding. * conversion buffer string of vim to ruby String object using * VIM encoding option. */ static VALUE vim_str2rb_enc_str(const char *s) { #ifdef RUBY19_OR_LATER int isnum; long lval; char_u *sval; rb_encoding *enc; isnum = get_option_value((char_u *)"enc", &lval, &sval, 0); if (isnum == 0) { enc = rb_enc_find((char *)sval); vim_free(sval); if (enc) { return rb_enc_str_new(s, strlen(s), enc); } } #endif return rb_str_new2(s); } static VALUE eval_enc_string_protect(const char *str, int *state) { #ifdef RUBY19_OR_LATER int isnum; long lval; char_u *sval; rb_encoding *enc; VALUE v; isnum = get_option_value((char_u *)"enc", &lval, &sval, 0); if (isnum == 0) { enc = rb_enc_find((char *)sval); vim_free(sval); if (enc) { v = rb_sprintf("#-*- coding:%s -*-\n%s", rb_enc_name(enc), str); return rb_eval_string_protect(StringValuePtr(v), state); } } #endif return rb_eval_string_protect(str, state); } void ex_rubydo(exarg_T *eap) { int state; linenr_T i; if (ensure_ruby_initialized()) { if (u_save(eap->line1 - 1, eap->line2 + 1) != OK) return; for (i = eap->line1; i <= eap->line2; i++) { VALUE line; line = vim_str2rb_enc_str((char *)ml_get(i)); rb_lastline_set(line); eval_enc_string_protect((char *) eap->arg, &state); if (state) { error_print(state); break; } line = rb_lastline_get(); if (!NIL_P(line)) { if (TYPE(line) != T_STRING) { EMSG(_("E265: $_ must be an instance of String")); return; } ml_replace(i, (char_u *) StringValuePtr(line), 1); changed(); #ifdef SYNTAX_HL syn_changed(i); /* recompute syntax hl. for this line */ #endif } } check_cursor(); update_curbuf(NOT_VALID); } } void ex_rubyfile(exarg_T *eap) { int state; if (ensure_ruby_initialized()) { rb_load_protect(rb_str_new2((char *) eap->arg), 0, &state); if (state) error_print(state); } } void ruby_buffer_free(buf_T *buf) { if (buf->b_ruby_ref) { rb_hash_aset(objtbl, rb_obj_id((VALUE) buf->b_ruby_ref), Qnil); RDATA(buf->b_ruby_ref)->data = NULL; } } void ruby_window_free(win_T *win) { if (win->w_ruby_ref) { rb_hash_aset(objtbl, rb_obj_id((VALUE) win->w_ruby_ref), Qnil); RDATA(win->w_ruby_ref)->data = NULL; } } static int ensure_ruby_initialized(void) { if (!ruby_initialized) { #ifdef DYNAMIC_RUBY if (ruby_enabled(TRUE)) { #endif #ifdef _WIN32 /* suggested by Ariya Mizutani */ int argc = 1; char *argv[] = {"gvim.exe"}; NtInitialize(&argc, &argv); #endif { #ifdef RUBY19_OR_LATER RUBY_INIT_STACK; #endif ruby_init(); } #ifdef RUBY19_OR_LATER { int dummy_argc = 2; char *dummy_argv[] = {"vim-ruby", "-e0"}; ruby_process_options(dummy_argc, dummy_argv); } ruby_script("vim-ruby"); #else ruby_init_loadpath(); #endif ruby_io_init(); ruby_vim_init(); ruby_initialized = 1; #ifdef DYNAMIC_RUBY } else { EMSG(_("E266: Sorry, this command is disabled, the Ruby library could not be loaded.")); return 0; } #endif } return ruby_initialized; } static void error_print(int state) { #ifndef DYNAMIC_RUBY #if !(defined(RUBY_VERSION) && RUBY_VERSION >= 19) \ && !(defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 19) RUBYEXTERN VALUE ruby_errinfo; #endif #endif VALUE eclass; VALUE einfo; char buff[BUFSIZ]; #define TAG_RETURN 0x1 #define TAG_BREAK 0x2 #define TAG_NEXT 0x3 #define TAG_RETRY 0x4 #define TAG_REDO 0x5 #define TAG_RAISE 0x6 #define TAG_THROW 0x7 #define TAG_FATAL 0x8 #define TAG_MASK 0xf switch (state) { case TAG_RETURN: EMSG(_("E267: unexpected return")); break; case TAG_NEXT: EMSG(_("E268: unexpected next")); break; case TAG_BREAK: EMSG(_("E269: unexpected break")); break; case TAG_REDO: EMSG(_("E270: unexpected redo")); break; case TAG_RETRY: EMSG(_("E271: retry outside of rescue clause")); break; case TAG_RAISE: case TAG_FATAL: #ifdef RUBY19_OR_LATER eclass = CLASS_OF(rb_errinfo()); einfo = rb_obj_as_string(rb_errinfo()); #else eclass = CLASS_OF(ruby_errinfo); einfo = rb_obj_as_string(ruby_errinfo); #endif if (eclass == rb_eRuntimeError && RSTRING_LEN(einfo) == 0) { EMSG(_("E272: unhandled exception")); } else { VALUE epath; char *p; epath = rb_class_path(eclass); vim_snprintf(buff, BUFSIZ, "%s: %s", RSTRING_PTR(epath), RSTRING_PTR(einfo)); p = strchr(buff, '\n'); if (p) *p = '\0'; EMSG(buff); } break; default: vim_snprintf(buff, BUFSIZ, _("E273: unknown longjmp status %d"), state); EMSG(buff); break; } } static VALUE vim_message(VALUE self UNUSED, VALUE str) { char *buff, *p; str = rb_obj_as_string(str); if (RSTRING_LEN(str) > 0) { /* Only do this when the string isn't empty, alloc(0) causes trouble. */ buff = ALLOCA_N(char, RSTRING_LEN(str)); strcpy(buff, RSTRING_PTR(str)); p = strchr(buff, '\n'); if (p) *p = '\0'; MSG(buff); } else { MSG(""); } return Qnil; } static VALUE vim_set_option(VALUE self UNUSED, VALUE str) { do_set((char_u *)StringValuePtr(str), 0); update_screen(NOT_VALID); return Qnil; } static VALUE vim_command(VALUE self UNUSED, VALUE str) { do_cmdline_cmd((char_u *)StringValuePtr(str)); return Qnil; } #ifdef FEAT_EVAL static VALUE vim_to_ruby(typval_T *tv) { VALUE result = Qnil; if (tv->v_type == VAR_STRING) { result = rb_str_new2(tv->vval.v_string == NULL ? "" : (char *)(tv->vval.v_string)); } else if (tv->v_type == VAR_NUMBER) { result = INT2NUM(tv->vval.v_number); } # ifdef FEAT_FLOAT else if (tv->v_type == VAR_FLOAT) { result = rb_float_new(tv->vval.v_float); } # endif else if (tv->v_type == VAR_LIST) { list_T *list = tv->vval.v_list; listitem_T *curr; result = rb_ary_new(); if (list != NULL) { for (curr = list->lv_first; curr != NULL; curr = curr->li_next) { rb_ary_push(result, vim_to_ruby(&curr->li_tv)); } } } else if (tv->v_type == VAR_DICT) { result = rb_hash_new(); if (tv->vval.v_dict != NULL) { hashtab_T *ht = &tv->vval.v_dict->dv_hashtab; long_u todo = ht->ht_used; hashitem_T *hi; dictitem_T *di; for (hi = ht->ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; di = dict_lookup(hi); rb_hash_aset(result, rb_str_new2((char *)hi->hi_key), vim_to_ruby(&di->di_tv)); } } } } /* else return Qnil; */ return result; } #endif static VALUE vim_evaluate(VALUE self UNUSED, VALUE str) { #ifdef FEAT_EVAL typval_T *tv; VALUE result; tv = eval_expr((char_u *)StringValuePtr(str), NULL); if (tv == NULL) { return Qnil; } result = vim_to_ruby(tv); free_tv(tv); return result; #else return Qnil; #endif } static VALUE buffer_new(buf_T *buf) { if (buf->b_ruby_ref) { return (VALUE) buf->b_ruby_ref; } else { VALUE obj = Data_Wrap_Struct(cBuffer, 0, 0, buf); buf->b_ruby_ref = (void *) obj; rb_hash_aset(objtbl, rb_obj_id(obj), obj); return obj; } } static buf_T *get_buf(VALUE obj) { buf_T *buf; Data_Get_Struct(obj, buf_T, buf); if (buf == NULL) rb_raise(eDeletedBufferError, "attempt to refer to deleted buffer"); return buf; } static VALUE buffer_s_current() { return buffer_new(curbuf); } static VALUE buffer_s_count() { buf_T *b; int n = 0; for (b = firstbuf; b != NULL; b = b->b_next) { /* Deleted buffers should not be counted * SegPhault - 01/07/05 */ if (b->b_p_bl) n++; } return INT2NUM(n); } static VALUE buffer_s_aref(VALUE self UNUSED, VALUE num) { buf_T *b; int n = NUM2INT(num); for (b = firstbuf; b != NULL; b = b->b_next) { /* Deleted buffers should not be counted * SegPhault - 01/07/05 */ if (!b->b_p_bl) continue; if (n == 0) return buffer_new(b); n--; } return Qnil; } static VALUE buffer_name(VALUE self) { buf_T *buf = get_buf(self); return buf->b_ffname ? rb_str_new2((char *)buf->b_ffname) : Qnil; } static VALUE buffer_number(VALUE self) { buf_T *buf = get_buf(self); return INT2NUM(buf->b_fnum); } static VALUE buffer_count(VALUE self) { buf_T *buf = get_buf(self); return INT2NUM(buf->b_ml.ml_line_count); } static VALUE get_buffer_line(buf_T *buf, linenr_T n) { if (n <= 0 || n > buf->b_ml.ml_line_count) rb_raise(rb_eIndexError, "line number %ld out of range", (long)n); return vim_str2rb_enc_str((char *)ml_get_buf(buf, n, FALSE)); } static VALUE buffer_aref(VALUE self, VALUE num) { buf_T *buf = get_buf(self); if (buf != NULL) return get_buffer_line(buf, (linenr_T)NUM2LONG(num)); return Qnil; /* For stop warning */ } static VALUE set_buffer_line(buf_T *buf, linenr_T n, VALUE str) { char *line = StringValuePtr(str); aco_save_T aco; if (n > 0 && n <= buf->b_ml.ml_line_count && line != NULL) { /* set curwin/curbuf for "buf" and save some things */ aucmd_prepbuf(&aco, buf); if (u_savesub(n) == OK) { ml_replace(n, (char_u *)line, TRUE); changed(); #ifdef SYNTAX_HL syn_changed(n); /* recompute syntax hl. for this line */ #endif } /* restore curwin/curbuf and a few other things */ aucmd_restbuf(&aco); /* Careful: autocommands may have made "buf" invalid! */ update_curbuf(NOT_VALID); } else { rb_raise(rb_eIndexError, "line number %ld out of range", (long)n); } return str; } static VALUE buffer_aset(VALUE self, VALUE num, VALUE str) { buf_T *buf = get_buf(self); if (buf != NULL) return set_buffer_line(buf, (linenr_T)NUM2LONG(num), str); return str; } static VALUE buffer_delete(VALUE self, VALUE num) { buf_T *buf = get_buf(self); long n = NUM2LONG(num); aco_save_T aco; if (n > 0 && n <= buf->b_ml.ml_line_count) { /* set curwin/curbuf for "buf" and save some things */ aucmd_prepbuf(&aco, buf); if (u_savedel(n, 1) == OK) { ml_delete(n, 0); /* Changes to non-active buffers should properly refresh * SegPhault - 01/09/05 */ deleted_lines_mark(n, 1L); changed(); } /* restore curwin/curbuf and a few other things */ aucmd_restbuf(&aco); /* Careful: autocommands may have made "buf" invalid! */ update_curbuf(NOT_VALID); } else { rb_raise(rb_eIndexError, "line number %ld out of range", n); } return Qnil; } static VALUE buffer_append(VALUE self, VALUE num, VALUE str) { buf_T *buf = get_buf(self); char *line = StringValuePtr(str); long n = NUM2LONG(num); aco_save_T aco; if (line == NULL) { rb_raise(rb_eIndexError, "NULL line"); } else if (n >= 0 && n <= buf->b_ml.ml_line_count) { /* set curwin/curbuf for "buf" and save some things */ aucmd_prepbuf(&aco, buf); if (u_inssub(n + 1) == OK) { ml_append(n, (char_u *) line, (colnr_T) 0, FALSE); /* Changes to non-active buffers should properly refresh screen * SegPhault - 12/20/04 */ appended_lines_mark(n, 1L); changed(); } /* restore curwin/curbuf and a few other things */ aucmd_restbuf(&aco); /* Careful: autocommands may have made "buf" invalid! */ update_curbuf(NOT_VALID); } else { rb_raise(rb_eIndexError, "line number %ld out of range", n); } return str; } static VALUE window_new(win_T *win) { if (win->w_ruby_ref) { return (VALUE) win->w_ruby_ref; } else { VALUE obj = Data_Wrap_Struct(cVimWindow, 0, 0, win); win->w_ruby_ref = (void *) obj; rb_hash_aset(objtbl, rb_obj_id(obj), obj); return obj; } } static win_T *get_win(VALUE obj) { win_T *win; Data_Get_Struct(obj, win_T, win); if (win == NULL) rb_raise(eDeletedWindowError, "attempt to refer to deleted window"); return win; } static VALUE window_s_current() { return window_new(curwin); } /* * Added line manipulation functions * SegPhault - 03/07/05 */ static VALUE line_s_current() { return get_buffer_line(curbuf, curwin->w_cursor.lnum); } static VALUE set_current_line(VALUE self UNUSED, VALUE str) { return set_buffer_line(curbuf, curwin->w_cursor.lnum, str); } static VALUE current_line_number() { return INT2FIX((int)curwin->w_cursor.lnum); } static VALUE window_s_count() { #ifdef FEAT_WINDOWS win_T *w; int n = 0; for (w = firstwin; w != NULL; w = w->w_next) n++; return INT2NUM(n); #else return INT2NUM(1); #endif } static VALUE window_s_aref(VALUE self UNUSED, VALUE num) { win_T *w; int n = NUM2INT(num); #ifndef FEAT_WINDOWS w = curwin; #else for (w = firstwin; w != NULL; w = w->w_next, --n) #endif if (n == 0) return window_new(w); return Qnil; } static VALUE window_buffer(VALUE self) { win_T *win = get_win(self); return buffer_new(win->w_buffer); } static VALUE window_height(VALUE self) { win_T *win = get_win(self); return INT2NUM(win->w_height); } static VALUE window_set_height(VALUE self, VALUE height) { win_T *win = get_win(self); win_T *savewin = curwin; curwin = win; win_setheight(NUM2INT(height)); curwin = savewin; return height; } static VALUE window_width(VALUE self) { win_T *win = get_win(self); return INT2NUM(win->w_width); } static VALUE window_set_width(VALUE self, VALUE width) { win_T *win = get_win(self); win_T *savewin = curwin; curwin = win; win_setwidth(NUM2INT(width)); curwin = savewin; return width; } static VALUE window_cursor(VALUE self) { win_T *win = get_win(self); return rb_assoc_new(INT2NUM(win->w_cursor.lnum), INT2NUM(win->w_cursor.col)); } static VALUE window_set_cursor(VALUE self, VALUE pos) { VALUE lnum, col; win_T *win = get_win(self); Check_Type(pos, T_ARRAY); if (RARRAY_LEN(pos) != 2) rb_raise(rb_eArgError, "array length must be 2"); lnum = RARRAY_PTR(pos)[0]; col = RARRAY_PTR(pos)[1]; win->w_cursor.lnum = NUM2LONG(lnum); win->w_cursor.col = NUM2UINT(col); check_cursor(); /* put cursor on an existing line */ update_screen(NOT_VALID); return Qnil; } static VALUE f_nop(VALUE self UNUSED) { return Qnil; } static VALUE f_p(int argc, VALUE *argv, VALUE self UNUSED) { int i; VALUE str = rb_str_new("", 0); for (i = 0; i < argc; i++) { if (i > 0) rb_str_cat(str, ", ", 2); rb_str_concat(str, rb_inspect(argv[i])); } MSG(RSTRING_PTR(str)); return Qnil; } static void ruby_io_init(void) { #ifndef DYNAMIC_RUBY RUBYEXTERN VALUE rb_stdout; #endif rb_stdout = rb_obj_alloc(rb_cObject); rb_define_singleton_method(rb_stdout, "write", vim_message, 1); rb_define_singleton_method(rb_stdout, "flush", f_nop, 0); rb_define_global_function("p", f_p, -1); } static void ruby_vim_init(void) { objtbl = rb_hash_new(); rb_global_variable(&objtbl); /* The Vim module used to be called "VIM", but "Vim" is better. Make an * alias "VIM" for backwards compatiblity. */ mVIM = rb_define_module("Vim"); rb_define_const(rb_cObject, "VIM", mVIM); rb_define_const(mVIM, "VERSION_MAJOR", INT2NUM(VIM_VERSION_MAJOR)); rb_define_const(mVIM, "VERSION_MINOR", INT2NUM(VIM_VERSION_MINOR)); rb_define_const(mVIM, "VERSION_BUILD", INT2NUM(VIM_VERSION_BUILD)); rb_define_const(mVIM, "VERSION_PATCHLEVEL", INT2NUM(VIM_VERSION_PATCHLEVEL)); rb_define_const(mVIM, "VERSION_SHORT", rb_str_new2(VIM_VERSION_SHORT)); rb_define_const(mVIM, "VERSION_MEDIUM", rb_str_new2(VIM_VERSION_MEDIUM)); rb_define_const(mVIM, "VERSION_LONG", rb_str_new2(VIM_VERSION_LONG)); rb_define_const(mVIM, "VERSION_LONG_DATE", rb_str_new2(VIM_VERSION_LONG_DATE)); rb_define_module_function(mVIM, "message", vim_message, 1); rb_define_module_function(mVIM, "set_option", vim_set_option, 1); rb_define_module_function(mVIM, "command", vim_command, 1); rb_define_module_function(mVIM, "evaluate", vim_evaluate, 1); eDeletedBufferError = rb_define_class_under(mVIM, "DeletedBufferError", rb_eStandardError); eDeletedWindowError = rb_define_class_under(mVIM, "DeletedWindowError", rb_eStandardError); cBuffer = rb_define_class_under(mVIM, "Buffer", rb_cObject); rb_define_singleton_method(cBuffer, "current", buffer_s_current, 0); rb_define_singleton_method(cBuffer, "count", buffer_s_count, 0); rb_define_singleton_method(cBuffer, "[]", buffer_s_aref, 1); rb_define_method(cBuffer, "name", buffer_name, 0); rb_define_method(cBuffer, "number", buffer_number, 0); rb_define_method(cBuffer, "count", buffer_count, 0); rb_define_method(cBuffer, "length", buffer_count, 0); rb_define_method(cBuffer, "[]", buffer_aref, 1); rb_define_method(cBuffer, "[]=", buffer_aset, 2); rb_define_method(cBuffer, "delete", buffer_delete, 1); rb_define_method(cBuffer, "append", buffer_append, 2); /* Added line manipulation functions * SegPhault - 03/07/05 */ rb_define_method(cBuffer, "line_number", current_line_number, 0); rb_define_method(cBuffer, "line", line_s_current, 0); rb_define_method(cBuffer, "line=", set_current_line, 1); cVimWindow = rb_define_class_under(mVIM, "Window", rb_cObject); rb_define_singleton_method(cVimWindow, "current", window_s_current, 0); rb_define_singleton_method(cVimWindow, "count", window_s_count, 0); rb_define_singleton_method(cVimWindow, "[]", window_s_aref, 1); rb_define_method(cVimWindow, "buffer", window_buffer, 0); rb_define_method(cVimWindow, "height", window_height, 0); rb_define_method(cVimWindow, "height=", window_set_height, 1); rb_define_method(cVimWindow, "width", window_width, 0); rb_define_method(cVimWindow, "width=", window_set_width, 1); rb_define_method(cVimWindow, "cursor", window_cursor, 0); rb_define_method(cVimWindow, "cursor=", window_set_cursor, 1); rb_define_virtual_variable("$curbuf", buffer_s_current, 0); rb_define_virtual_variable("$curwin", window_s_current, 0); }
zyz2011-vim
src/if_ruby.c
C
gpl2
35,016
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * GUI support by Robert Webb * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * gui_w16.c * * GUI support for Microsoft Windows 3.1x * * George V. Reilly <george@reilly.org> wrote the original Win32 GUI. * Robert Webb reworked it to use the existing GUI stuff and added menu, * scrollbars, etc. * * Vince Negri then butchered the code to get it compiling for * 16-bit windows. * */ /* Win16 doesn't use the "W" methods. */ #define pDispatchMessage DispatchMessage #define pGetMessage GetMessage #define pIsDialogMessage IsDialogMessage #define pPeekMessage PeekMessage /* * Include the common stuff for MS-Windows GUI. */ #include "gui_w48.c" #include "guiw16rc.h" /* Undocumented Windows Message - not even defined in some SDK headers */ #define WM_EXITSIZEMOVE 0x0232 #ifdef FEAT_TOOLBAR # define CMD_TB_BASE (99) # include <vimtbar.h> #endif #ifdef PROTO # define WINAPI #endif #define HANDLE_WM_DROPFILES(hwnd, wParam, lParam, fn) \ ((fn)((hwnd), (HDROP)(wParam)), 0L) /* Local variables: */ #ifdef FEAT_MENU static UINT s_menu_id = 100; #endif #define VIM_NAME "vim" #define VIM_CLASS "Vim" #define DLG_ALLOC_SIZE 16 * 1024 /* * stuff for dialogs, menus, tearoffs etc. */ #if defined(FEAT_GUI_DIALOG) || defined(PROTO) static BOOL CALLBACK dialog_callback(HWND, UINT, WPARAM, LPARAM); static LPWORD add_dialog_element( LPWORD p, DWORD lStyle, WORD x, WORD y, WORD w, WORD h, WORD Id, BYTE clss, const char *caption); static int dialog_default_button = -1; #endif static void get_dialog_font_metrics(void); #ifdef FEAT_TOOLBAR static void initialise_toolbar(void); #endif #ifdef FEAT_MENU /* * Figure out how high the menu bar is at the moment. */ static int gui_mswin_get_menu_height( int fix_window) /* If TRUE, resize window if menu height changed */ { static int old_menu_height = -1; int num; int menu_height; if (gui.menu_is_active) num = GetMenuItemCount(s_menuBar); else num = 0; if (num == 0) menu_height = 0; else if (gui.starting) menu_height = GetSystemMetrics(SM_CYMENU); else { RECT r1, r2; int frameht = GetSystemMetrics(SM_CYFRAME); int capht = GetSystemMetrics(SM_CYCAPTION); /* get window rect of s_hwnd * get client rect of s_hwnd * get cap height * subtract from window rect, the sum of client height, * (if not maximized)frame thickness, and caption height. */ GetWindowRect(s_hwnd, &r1); GetClientRect(s_hwnd, &r2); menu_height = r1.bottom - r1.top - (r2.bottom-r2.top + 2 * frameht * (!IsZoomed(s_hwnd)) + capht); } if (fix_window && menu_height != old_menu_height) { old_menu_height = menu_height; gui_set_shellsize(FALSE, FALSE, RESIZE_VERT); } return menu_height; } #endif /*FEAT_MENU*/ /* * Even though we have _DuringSizing() which makes the rubber band a valid * size, we need this for when the user maximises the window. * TODO: Doesn't seem to adjust the width though for some reason. */ static BOOL _OnWindowPosChanging( HWND hwnd, LPWINDOWPOS lpwpos) { if (!IsIconic(hwnd) && !(lpwpos->flags & SWP_NOSIZE)) { gui_mswin_get_valid_dimensions(lpwpos->cx, lpwpos->cy, &lpwpos->cx, &lpwpos->cy); } return 0; } static LRESULT CALLBACK _WndProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { /* TRACE("WndProc: hwnd = %08x, msg = %x, wParam = %x, lParam = %x\n", hwnd, uMsg, wParam, lParam); */ HandleMouseHide(uMsg, lParam); s_uMsg = uMsg; s_wParam = wParam; s_lParam = lParam; switch (uMsg) { HANDLE_MSG(hwnd, WM_DEADCHAR, _OnDeadChar); HANDLE_MSG(hwnd, WM_SYSDEADCHAR, _OnDeadChar); /* HANDLE_MSG(hwnd, WM_ACTIVATE, _OnActivate); */ HANDLE_MSG(hwnd, WM_CHAR, _OnChar); HANDLE_MSG(hwnd, WM_CLOSE, _OnClose); /* HANDLE_MSG(hwnd, WM_COMMAND, _OnCommand); */ HANDLE_MSG(hwnd, WM_DESTROY, _OnDestroy); HANDLE_MSG(hwnd, WM_DROPFILES, _OnDropFiles); HANDLE_MSG(hwnd, WM_HSCROLL, _OnScroll); HANDLE_MSG(hwnd, WM_KILLFOCUS, _OnKillFocus); #ifdef FEAT_MENU HANDLE_MSG(hwnd, WM_COMMAND, _OnMenu); #endif /* HANDLE_MSG(hwnd, WM_MOVE, _OnMove); */ /* HANDLE_MSG(hwnd, WM_NCACTIVATE, _OnNCActivate); */ HANDLE_MSG(hwnd, WM_SETFOCUS, _OnSetFocus); HANDLE_MSG(hwnd, WM_SIZE, _OnSize); /* HANDLE_MSG(hwnd, WM_SYSCOMMAND, _OnSysCommand); */ /* HANDLE_MSG(hwnd, WM_SYSKEYDOWN, _OnAltKey); */ HANDLE_MSG(hwnd, WM_VSCROLL, _OnScroll); HANDLE_MSG(hwnd, WM_WINDOWPOSCHANGING, _OnWindowPosChanging); HANDLE_MSG(hwnd, WM_ACTIVATEAPP, _OnActivateApp); case WM_QUERYENDSESSION: /* System wants to go down. */ gui_shell_closed(); /* Will exit when no changed buffers. */ return FALSE; /* Do NOT allow system to go down. */ case WM_ENDSESSION: if (wParam) /* system only really goes down when wParam is TRUE */ _OnEndSession(); break; case WM_SYSCHAR: /* * if 'winaltkeys' is "no", or it's "menu" and it's not a menu * shortcut key, handle like a typed ALT key, otherwise call Windows * ALT key handling. */ #ifdef FEAT_MENU if ( !gui.menu_is_active || p_wak[0] == 'n' || (p_wak[0] == 'm' && !gui_is_menu_shortcut((int)wParam)) ) #endif return HANDLE_WM_SYSCHAR((hwnd), (wParam), (lParam), (_OnSysChar)); #ifdef FEAT_MENU else return MyWindowProc(hwnd, uMsg, wParam, lParam); #endif case WM_SYSKEYUP: #ifdef FEAT_MENU /* Only when menu is active, ALT key is used for that. */ if (gui.menu_is_active) { return MyWindowProc(hwnd, uMsg, wParam, lParam); } else #endif return 0; #if defined(MENUHINTS) && defined(FEAT_MENU) case WM_MENUSELECT: if (((UINT) LOWORD(lParam) & (0xffff ^ (MF_MOUSESELECT + MF_BITMAP + MF_POPUP))) == MF_HILITE && (State & CMDLINE) == 0) { UINT idButton; int idx; vimmenu_T *pMenu; idButton = (UINT)LOWORD(wParam); pMenu = gui_mswin_find_menu(root_menu, idButton); if (pMenu) { idx = MENU_INDEX_TIP; msg_clr_cmdline(); if (pMenu->strings[idx]) msg(pMenu->strings[idx]); else msg(""); setcursor(); out_flush(); } } break; #endif case WM_NCHITTEST: { LRESULT result; int x, y; int xPos = GET_X_LPARAM(lParam); result = MyWindowProc(hwnd, uMsg, wParam, lParam); if (result == HTCLIENT) { gui_mch_get_winpos(&x, &y); xPos -= x; if (xPos < 48) /*<VN> TODO should use system metric?*/ return HTBOTTOMLEFT; else return HTBOTTOMRIGHT; } else return result; } /* break; */ default: #ifdef MSWIN_FIND_REPLACE if (uMsg == s_findrep_msg && s_findrep_msg != 0) { _OnFindRepl(); } #endif return MyWindowProc(hwnd, uMsg, wParam, lParam); } return 1; } /* * End of call-back routines */ /* * Parse the GUI related command-line arguments. Any arguments used are * deleted from argv, and *argc is decremented accordingly. This is called * when vim is started, whether or not the GUI has been started. */ void gui_mch_prepare(int *argc, char **argv) { /* No special args for win16 GUI at the moment. */ } /* * Initialise the GUI. Create all the windows, set up all the call-backs * etc. */ int gui_mch_init(void) { const char szVimWndClass[] = VIM_CLASS; const char szTextAreaClass[] = "VimTextArea"; WNDCLASS wndclass; #ifdef WIN16_3DLOOK Ctl3dRegister(s_hinst); Ctl3dAutoSubclass(s_hinst); #endif /* Display any pending error messages */ display_errors(); gui.scrollbar_width = GetSystemMetrics(SM_CXVSCROLL); gui.scrollbar_height = GetSystemMetrics(SM_CYHSCROLL); #ifdef FEAT_MENU gui.menu_height = 0; /* Windows takes care of this */ #endif gui.border_width = 0; gui.currBgColor = INVALCOLOR; s_brush = CreateSolidBrush(GetSysColor(COLOR_BTNFACE)); if (GetClassInfo(s_hinst, szVimWndClass, &wndclass) == 0) { wndclass.style = 0; wndclass.lpfnWndProc = _WndProc; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = s_hinst; wndclass.hIcon = LoadIcon(wndclass.hInstance, MAKEINTRESOURCE(IDR_VIM)); wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hbrBackground = s_brush; wndclass.lpszMenuName = NULL; wndclass.lpszClassName = szVimWndClass; if (( #ifdef GLOBAL_IME atom = #endif RegisterClass(&wndclass)) == 0) return FAIL; } s_hwnd = CreateWindow( szVimWndClass, "Vim MSWindows GUI", WS_OVERLAPPEDWINDOW, gui_win_x == -1 ? CW_USEDEFAULT : gui_win_x, gui_win_y == -1 ? CW_USEDEFAULT : gui_win_y, 100, /* Any value will do */ 100, /* Any value will do */ NULL, NULL, s_hinst, NULL); if (s_hwnd == NULL) return FAIL; #ifdef GLOBAL_IME global_ime_init(atom, s_hwnd); #endif /* Create the text area window */ if (GetClassInfo(s_hinst, szTextAreaClass, &wndclass) == 0) { wndclass.style = CS_OWNDC; wndclass.lpfnWndProc = _TextAreaWndProc; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = s_hinst; wndclass.hIcon = NULL; wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hbrBackground = NULL; wndclass.lpszMenuName = NULL; wndclass.lpszClassName = szTextAreaClass; if (RegisterClass(&wndclass) == 0) return FAIL; } s_textArea = CreateWindow( szTextAreaClass, "Vim text area", WS_CHILD | WS_VISIBLE, 0, 0, 100, /* Any value will do for now */ 100, /* Any value will do for now */ s_hwnd, NULL, s_hinst, NULL); if (s_textArea == NULL) return FAIL; #ifdef FEAT_MENU s_menuBar = CreateMenu(); #endif s_hdc = GetDC(s_textArea); #ifdef MSWIN16_FASTTEXT SetBkMode(s_hdc, OPAQUE); #endif DragAcceptFiles(s_hwnd, TRUE); /* Do we need to bother with this? */ /* m_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT); */ /* Get background/foreground colors from the system */ gui_mch_def_colors(); /* Get the colors from the "Normal" group (set in syntax.c or in a vimrc * file) */ set_normal_colors(); /* * Check that none of the colors are the same as the background color. * Then store the current values as the defaults. */ gui_check_colors(); gui.def_norm_pixel = gui.norm_pixel; gui.def_back_pixel = gui.back_pixel; /* Get the colors for the highlight groups (gui_check_colors() might have * changed them) */ highlight_gui_started(); /* * Start out by adding the configured border width into the border offset */ gui.border_offset = gui.border_width; /* * compute a couple of metrics used for the dialogs */ get_dialog_font_metrics(); #ifdef FEAT_TOOLBAR /* * Create the toolbar */ initialise_toolbar(); #endif #ifdef MSWIN_FIND_REPLACE /* * Initialise the dialog box stuff */ s_findrep_msg = RegisterWindowMessage(FINDMSGSTRING); /* Initialise the struct */ s_findrep_struct.lStructSize = sizeof(s_findrep_struct); s_findrep_struct.lpstrFindWhat = alloc(MSWIN_FR_BUFSIZE); s_findrep_struct.lpstrFindWhat[0] = NUL; s_findrep_struct.lpstrReplaceWith = alloc(MSWIN_FR_BUFSIZE); s_findrep_struct.lpstrReplaceWith[0] = NUL; s_findrep_struct.wFindWhatLen = MSWIN_FR_BUFSIZE; s_findrep_struct.wReplaceWithLen = MSWIN_FR_BUFSIZE; #endif return OK; } /* * Set the size of the window to the given width and height in pixels. */ void gui_mch_set_shellsize(int width, int height, int min_width, int min_height, int base_width, int base_height, int direction) { RECT workarea_rect; int win_width, win_height; int win_xpos, win_ypos; WINDOWPLACEMENT wndpl; /* try to keep window completely on screen */ /* get size of the screen work area - use SM_CYFULLSCREEN * instead of SM_CYSCREEN so that we don't overlap the * taskbar if someone fires us up on Win95/NT */ workarea_rect.left = 0; workarea_rect.top = 0; workarea_rect.right = GetSystemMetrics(SM_CXSCREEN); workarea_rect.bottom = GetSystemMetrics(SM_CYFULLSCREEN); /* get current posision of our window */ wndpl.length = sizeof(WINDOWPLACEMENT); GetWindowPlacement(s_hwnd, &wndpl); if (wndpl.showCmd == SW_SHOWNORMAL) { win_xpos = wndpl.rcNormalPosition.left; win_ypos = wndpl.rcNormalPosition.top; } else { win_xpos = workarea_rect.left; win_ypos = workarea_rect.top; } /* compute the size of the outside of the window */ win_width = width + GetSystemMetrics(SM_CXFRAME) * 2; win_height = height + GetSystemMetrics(SM_CYFRAME) * 2 + GetSystemMetrics(SM_CYCAPTION) #ifdef FEAT_MENU + gui_mswin_get_menu_height(FALSE) #endif ; /* if the window is going off the screen, move it on to the screen */ if ((direction & RESIZE_HOR) && win_xpos + win_width > workarea_rect.right) win_xpos = workarea_rect.right - win_width; if ((direction & RESIZE_HOR) && win_xpos < workarea_rect.left) win_xpos = workarea_rect.left; if ((direction & RESIZE_VERT) && win_ypos + win_height > workarea_rect.bottom) win_ypos = workarea_rect.bottom - win_height; if ((direction & RESIZE_VERT) && win_ypos < workarea_rect.top) win_ypos = workarea_rect.top; /* set window position */ SetWindowPos(s_hwnd, NULL, win_xpos, win_ypos, win_width, win_height, SWP_NOZORDER | SWP_NOACTIVATE); #ifdef FEAT_MENU /* Menu may wrap differently now */ gui_mswin_get_menu_height(!gui.starting); #endif } void gui_mch_set_scrollbar_thumb( scrollbar_T *sb, long val, long size, long max) { sb->scroll_shift = 0; while (max > 32767) { max = (max + 1) >> 1; val >>= 1; size >>= 1; ++sb->scroll_shift; } if (sb->scroll_shift > 0) ++size; SetScrollRange(sb->id, SB_CTL, 0, (int) max, FALSE); SetScrollPos(sb->id, SB_CTL, (int) val, TRUE); } /* * Set the current text font. */ void gui_mch_set_font(GuiFont font) { gui.currFont = font; SelectFont(s_hdc, gui.currFont); } /* * Set the current text foreground color. */ void gui_mch_set_fg_color(guicolor_T color) { gui.currFgColor = color; SetTextColor(s_hdc, gui.currFgColor); } /* * Set the current text background color. */ void gui_mch_set_bg_color(guicolor_T color) { if (gui.currBgColor == color) return; gui.currBgColor = color; SetBkColor(s_hdc, gui.currBgColor); } /* * Set the current text special color. */ void gui_mch_set_sp_color(guicolor_T color) { /* TODO */ } void gui_mch_draw_string( int row, int col, char_u *text, int len, int flags) { #ifndef MSWIN16_FASTTEXT static int *padding = NULL; static int pad_size = 0; int i; #endif HPEN hpen, old_pen; int y; #ifndef MSWIN16_FASTTEXT /* * Italic and bold text seems to have an extra row of pixels at the bottom * (below where the bottom of the character should be). If we draw the * characters with a solid background, the top row of pixels in the * character below will be overwritten. We can fix this by filling in the * background ourselves, to the correct character proportions, and then * writing the character in transparent mode. Still have a problem when * the character is "_", which gets written on to the character below. * New fix: set gui.char_ascent to -1. This shifts all characters up one * pixel in their slots, which fixes the problem with the bottom row of * pixels. We still need this code because otherwise the top row of pixels * becomes a problem. - webb. */ HBRUSH hbr; RECT rc; if (!(flags & DRAW_TRANSP)) { /* * Clear background first. * Note: FillRect() excludes right and bottom of rectangle. */ rc.left = FILL_X(col); rc.top = FILL_Y(row); #ifdef FEAT_MBYTE if (has_mbyte) { /* Compute the length in display cells. */ rc.right = FILL_X(col + mb_string2cells(text, len)); } else #endif rc.right = FILL_X(col + len); rc.bottom = FILL_Y(row + 1); hbr = CreateSolidBrush(gui.currBgColor); FillRect(s_hdc, &rc, hbr); DeleteBrush(hbr); SetBkMode(s_hdc, TRANSPARENT); /* * When drawing block cursor, prevent inverted character spilling * over character cell (can happen with bold/italic) */ if (flags & DRAW_CURSOR) { pcliprect = &rc; foptions = ETO_CLIPPED; } } #else /* * Alternative: write the characters in opaque mode, since we have blocked * bold or italic fonts. */ /* The OPAQUE mode and backcolour have already been set */ #endif /* The forecolor and font have already been set */ #ifndef MSWIN16_FASTTEXT if (pad_size != Columns || padding == NULL || padding[0] != gui.char_width) { vim_free(padding); pad_size = Columns; padding = (int *)alloc(pad_size * sizeof(int)); if (padding != NULL) for (i = 0; i < pad_size; i++) padding[i] = gui.char_width; } #endif /* * We have to provide the padding argument because italic and bold versions * of fixed-width fonts are often one pixel or so wider than their normal * versions. * No check for DRAW_BOLD, Windows will have done it already. */ #ifndef MSWIN16_FASTTEXT ExtTextOut(s_hdc, TEXT_X(col), TEXT_Y(row), 0, NULL, (char *)text, len, padding); #else TextOut(s_hdc, TEXT_X(col), TEXT_Y(row), (char *)text, len); #endif if (flags & DRAW_UNDERL) { hpen = CreatePen(PS_SOLID, 1, gui.currFgColor); old_pen = SelectObject(s_hdc, hpen); /* When p_linespace is 0, overwrite the bottom row of pixels. * Otherwise put the line just below the character. */ y = FILL_Y(row + 1) - 1; #ifndef MSWIN16_FASTTEXT if (p_linespace > 1) y -= p_linespace - 1; #endif MoveToEx(s_hdc, FILL_X(col), y, NULL); /* Note: LineTo() excludes the last pixel in the line. */ LineTo(s_hdc, FILL_X(col + len), y); DeleteObject(SelectObject(s_hdc, old_pen)); } } /* * Output routines. */ /* Flush any output to the screen */ void gui_mch_flush(void) { /* Is anything needed here? */ } static void clear_rect(RECT *rcp) { /* Use trick for fast rect clear */ gui_mch_set_bg_color(gui.back_pixel); ExtTextOut(s_hdc, 0, 0, ETO_CLIPPED | ETO_OPAQUE, rcp, NULL, 0, NULL); } void gui_mch_get_screen_dimensions(int *screen_w, int *screen_h) { *screen_w = GetSystemMetrics(SM_CXFULLSCREEN) - GetSystemMetrics(SM_CXFRAME) * 2; /* FIXME: dirty trick: Because the gui_get_base_height() doesn't include * the menubar for MSwin, we subtract it from the screen height, so that * the window size can be made to fit on the screen. */ *screen_h = GetSystemMetrics(SM_CYFULLSCREEN) - GetSystemMetrics(SM_CYFRAME) * 2 #ifdef FEAT_MENU - gui_mswin_get_menu_height(FALSE) #endif ; } #if defined(FEAT_MENU) || defined(PROTO) /* * Add a sub menu to the menu bar. */ void gui_mch_add_menu( vimmenu_T *menu, int pos) { vimmenu_T *parent = menu->parent; menu->submenu_id = CreatePopupMenu(); menu->id = s_menu_id++; if (menu_is_menubar(menu->name)) { InsertMenu((parent == NULL) ? s_menuBar : parent->submenu_id, (UINT)pos, MF_POPUP | MF_STRING | MF_BYPOSITION, (UINT)menu->submenu_id, menu->name); } /* Fix window size if menu may have wrapped */ if (parent == NULL) gui_mswin_get_menu_height(!gui.starting); } void gui_mch_show_popupmenu(vimmenu_T *menu) { POINT mp; (void)GetCursorPos((LPPOINT)&mp); gui_mch_show_popupmenu_at(menu, (int)mp.x, (int)mp.y); } void gui_make_popup(char_u *path_name, int mouse_pos) { vimmenu_T *menu = gui_find_menu(path_name); if (menu != NULL) { /* Find the position of the current cursor */ DWORD temp_p; POINT p; temp_p = GetDCOrg(s_hdc); p.x = LOWORD(temp_p); p.y = HIWORD(temp_p); if (mouse_pos) { int mx, my; gui_mch_getmouse(&mx, &my); p.x += mx; p.y += my; } else if (curwin != NULL) { p.x += TEXT_X(W_WINCOL(curwin) + curwin->w_wcol + 1); p.y += TEXT_Y(W_WINROW(curwin) + curwin->w_wrow + 1); } msg_scroll = FALSE; gui_mch_show_popupmenu_at(menu, (int)p.x, (int)p.y); } } /* * Add a menu item to a menu */ void gui_mch_add_menu_item( vimmenu_T *menu, int idx) { vimmenu_T *parent = menu->parent; menu->id = s_menu_id++; menu->submenu_id = NULL; #ifdef FEAT_TOOLBAR if (menu_is_toolbar(parent->name)) { TBBUTTON newtb; vim_memset(&newtb, 0, sizeof(newtb)); if (menu_is_separator(menu->name)) { newtb.iBitmap = 0; newtb.fsStyle = TBSTYLE_SEP; } else { if (menu->iconidx >= TOOLBAR_BITMAP_COUNT) newtb.iBitmap = -1; else newtb.iBitmap = menu->iconidx; newtb.fsStyle = TBSTYLE_BUTTON; } newtb.idCommand = menu->id; newtb.fsState = TBSTATE_ENABLED; SendMessage(s_toolbarhwnd, TB_INSERTBUTTON, (WPARAM)idx, (LPARAM)&newtb); menu->submenu_id = (HMENU)-1; } else #endif { InsertMenu(parent->submenu_id, (UINT)idx, (menu_is_separator(menu->name) ? MF_SEPARATOR : MF_STRING) | MF_BYPOSITION, (UINT)menu->id, menu->name); } } /* * Destroy the machine specific menu widget. */ void gui_mch_destroy_menu(vimmenu_T *menu) { UINT i, j; char pants[80]; /*<VN> hack*/ #ifdef FEAT_TOOLBAR /* * is this a toolbar button? */ if (menu->submenu_id == (HMENU)-1) { int iButton; iButton = SendMessage(s_toolbarhwnd, TB_COMMANDTOINDEX, (WPARAM)menu->id, 0); SendMessage(s_toolbarhwnd, TB_DELETEBUTTON, (WPARAM)iButton, 0); } else #endif { /* * negri: horrible API bug when running 16-bit programs under Win9x or * NT means that we can't use MF_BYCOMMAND for menu items which have * submenus, including the top-level headings. We have to find the menu * item and use MF_BYPOSITION instead. :-p */ if (menu->parent != NULL && menu_is_popup(menu->parent->dname) && menu->parent->submenu_id != NULL) RemoveMenu(menu->parent->submenu_id, menu->id, MF_BYCOMMAND); else if (menu->submenu_id == NULL) RemoveMenu(s_menuBar, menu->id, MF_BYCOMMAND); else if (menu->parent != NULL) { i = GetMenuItemCount(menu->parent->submenu_id); for (j = 0; j < i; ++j) { GetMenuString(menu->parent->submenu_id, j, pants, 80, MF_BYPOSITION); if (strcmp(pants, menu->name) == 0) { RemoveMenu(menu->parent->submenu_id, j, MF_BYPOSITION); break; } } } else { i = GetMenuItemCount(s_menuBar); for (j = 0; j < i; ++j) { GetMenuString(s_menuBar, j, pants, 80, MF_BYPOSITION); if (strcmp(pants, menu->name) == 0) { RemoveMenu(s_menuBar, j, MF_BYPOSITION); break; } } } if (menu->submenu_id != NULL) DestroyMenu(menu->submenu_id); } DrawMenuBar(s_hwnd); } /* * Make a menu either grey or not grey. */ void gui_mch_menu_grey( vimmenu_T *menu, int grey) { #ifdef FEAT_TOOLBAR /* * is this a toolbar button? */ if (menu->submenu_id == (HMENU)-1) { SendMessage(s_toolbarhwnd, TB_ENABLEBUTTON, (WPARAM)menu->id, (LPARAM) MAKELONG((grey ? FALSE : TRUE), 0) ); } else #endif if (grey) EnableMenuItem(s_menuBar, menu->id, MF_BYCOMMAND | MF_GRAYED); else EnableMenuItem(s_menuBar, menu->id, MF_BYCOMMAND | MF_ENABLED); } #endif /*FEAT_MENU*/ /* define some macros used to make the dialogue creation more readable */ #define add_string(s) strcpy((LPSTR)p, s); (LPSTR)p += (strlen((LPSTR)p) + 1) #define add_word(x) *p++ = (x) #define add_byte(x) *((LPSTR)p)++ = (x) #define add_long(x) *((LPDWORD)p)++ = (x) #if defined(FEAT_GUI_DIALOG) || defined(PROTO) /* * stuff for dialogs */ /* * The callback routine used by all the dialogs. Very simple. First, * acknowledges the INITDIALOG message so that Windows knows to do standard * dialog stuff (Return = default, Esc = cancel....) Second, if a button is * pressed, return that button's ID - IDCANCEL (2), which is the button's * number. */ static BOOL CALLBACK dialog_callback( HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { if (message == WM_INITDIALOG) { CenterWindow(hwnd, GetWindow(hwnd, GW_OWNER)); /* Set focus to the dialog. Set the default button, if specified. */ (void)SetFocus(hwnd); if (dialog_default_button > IDCANCEL) (void)SetFocus(GetDlgItem(hwnd, dialog_default_button)); // if (dialog_default_button > 0) // (void)SetFocus(GetDlgItem(hwnd, dialog_default_button + IDCANCEL)); return FALSE; } if (message == WM_COMMAND) { int button = LOWORD(wParam); /* Don't end the dialog if something was selected that was * not a button. */ if (button >= DLG_NONBUTTON_CONTROL) return TRUE; /* If the edit box exists, copy the string. */ if (s_textfield != NULL) GetDlgItemText(hwnd, DLG_NONBUTTON_CONTROL + 2, s_textfield, IOSIZE); /* * Need to check for IDOK because if the user just hits Return to * accept the default value, some reason this is what we get. */ if (button == IDOK) EndDialog(hwnd, dialog_default_button); else EndDialog(hwnd, button - IDCANCEL); return TRUE; } if ((message == WM_SYSCOMMAND) && (wParam == SC_CLOSE)) { EndDialog(hwnd, 0); return TRUE; } return FALSE; } /* * Create a dialog dynamically from the parameter strings. * type = type of dialog (question, alert, etc.) * title = dialog title. may be NULL for default title. * message = text to display. Dialog sizes to accommodate it. * buttons = '\n' separated list of button captions, default first. * dfltbutton = number of default button. * * This routine returns 1 if the first button is pressed, * 2 for the second, etc. * * 0 indicates Esc was pressed. * -1 for unexpected error * * If stubbing out this fn, return 1. */ static const char_u dlg_icons[] = /* must match names in resource file */ { IDR_VIM, IDR_VIM_ERROR, IDR_VIM_ALERT, IDR_VIM_INFO, IDR_VIM_QUESTION }; int gui_mch_dialog( int type, char_u *title, char_u *message, char_u *buttons, int dfltbutton, char_u *textfield, int ex_cmd) { FARPROC dp; LPWORD p, pnumitems; int numButtons; int *buttonWidths, *buttonPositions; int buttonYpos; int nchar, i; DWORD lStyle; int dlgwidth = 0; int dlgheight; int editboxheight; int horizWidth; int msgheight; char_u *pstart; char_u *pend; char_u *tbuffer; RECT rect; HWND hwnd; HDC hdc; HFONT oldFont; TEXTMETRIC fontInfo; int fontHeight; int textWidth, minButtonWidth, messageWidth; int maxDialogWidth; int vertical; int dlgPaddingX; int dlgPaddingY; HGLOBAL hglbDlgTemp; #ifndef NO_CONSOLE /* Don't output anything in silent mode ("ex -s") */ if (silent_mode) return dfltbutton; /* return default option */ #endif /* If there is no window yet, open it. */ if (s_hwnd == NULL && gui_mch_init() == FAIL) return dfltbutton; if ((type < 0) || (type > VIM_LAST_TYPE)) type = 0; /* allocate some memory for dialog template */ /* TODO should compute this really*/ hglbDlgTemp = GlobalAlloc(GHND, DLG_ALLOC_SIZE); if (hglbDlgTemp == NULL) return -1; p = (LPWORD) GlobalLock(hglbDlgTemp); if (p == NULL) return -1; /* * make a copy of 'buttons' to fiddle with it. complier grizzles because * vim_strsave() doesn't take a const arg (why not?), so cast away the * const. */ tbuffer = vim_strsave(buttons); if (tbuffer == NULL) return -1; --dfltbutton; /* Change from one-based to zero-based */ /* Count buttons */ numButtons = 1; for (i = 0; tbuffer[i] != '\0'; i++) { if (tbuffer[i] == DLG_BUTTON_SEP) numButtons++; } if (dfltbutton >= numButtons) dfltbutton = 0; /* Allocate array to hold the width of each button */ buttonWidths = (int *) lalloc(numButtons * sizeof(int), TRUE); if (buttonWidths == NULL) return -1; /* Allocate array to hold the X position of each button */ buttonPositions = (int *) lalloc(numButtons * sizeof(int), TRUE); if (buttonPositions == NULL) return -1; /* * Calculate how big the dialog must be. */ hwnd = GetDesktopWindow(); hdc = GetWindowDC(hwnd); oldFont = SelectFont(hdc, GetStockObject(SYSTEM_FONT)); dlgPaddingX = DLG_OLD_STYLE_PADDING_X; dlgPaddingY = DLG_OLD_STYLE_PADDING_Y; GetTextMetrics(hdc, &fontInfo); fontHeight = fontInfo.tmHeight; /* Minimum width for horizontal button */ minButtonWidth = GetTextWidth(hdc, "Cancel", 6); /* Maximum width of a dialog, if possible */ GetWindowRect(s_hwnd, &rect); maxDialogWidth = rect.right - rect.left - GetSystemMetrics(SM_CXFRAME) * 2; if (maxDialogWidth < DLG_MIN_MAX_WIDTH) maxDialogWidth = DLG_MIN_MAX_WIDTH; /* Set dlgwidth to width of message */ pstart = message; messageWidth = 0; msgheight = 0; do { pend = vim_strchr(pstart, DLG_BUTTON_SEP); if (pend == NULL) pend = pstart + STRLEN(pstart); /* Last line of message. */ msgheight += fontHeight; textWidth = GetTextWidth(hdc, pstart, pend - pstart); if (textWidth > messageWidth) messageWidth = textWidth; pstart = pend + 1; } while (*pend != NUL); dlgwidth = messageWidth; /* Add width of icon to dlgwidth, and some space */ dlgwidth += DLG_ICON_WIDTH + 3 * dlgPaddingX; if (msgheight < DLG_ICON_HEIGHT) msgheight = DLG_ICON_HEIGHT; /* * Check button names. A long one will make the dialog wider. */ vertical = (vim_strchr(p_go, GO_VERTICAL) != NULL); if (!vertical) { // Place buttons horizontally if they fit. horizWidth = dlgPaddingX; pstart = tbuffer; i = 0; do { pend = vim_strchr(pstart, DLG_BUTTON_SEP); if (pend == NULL) pend = pstart + STRLEN(pstart); // Last button name. textWidth = GetTextWidth(hdc, pstart, pend - pstart); if (textWidth < minButtonWidth) textWidth = minButtonWidth; textWidth += dlgPaddingX; /* Padding within button */ buttonWidths[i] = textWidth; buttonPositions[i++] = horizWidth; horizWidth += textWidth + dlgPaddingX; /* Pad between buttons */ pstart = pend + 1; } while (*pend != NUL); if (horizWidth > maxDialogWidth) vertical = TRUE; // Too wide to fit on the screen. else if (horizWidth > dlgwidth) dlgwidth = horizWidth; } if (vertical) { // Stack buttons vertically. pstart = tbuffer; do { pend = vim_strchr(pstart, DLG_BUTTON_SEP); if (pend == NULL) pend = pstart + STRLEN(pstart); // Last button name. textWidth = GetTextWidth(hdc, pstart, pend - pstart); textWidth += dlgPaddingX; /* Padding within button */ textWidth += DLG_VERT_PADDING_X * 2; /* Padding around button */ if (textWidth > dlgwidth) dlgwidth = textWidth; pstart = pend + 1; } while (*pend != NUL); } if (dlgwidth < DLG_MIN_WIDTH) dlgwidth = DLG_MIN_WIDTH; /* Don't allow a really thin dialog!*/ /* start to fill in the dlgtemplate information. addressing by WORDs */ lStyle = DS_MODALFRAME | WS_CAPTION | WS_VISIBLE ; add_long(lStyle); pnumitems = p; /*save where the number of items must be stored*/ add_byte(0); // NumberOfItems(will change later) add_word(10); // x add_word(10); // y add_word(PixelToDialogX(dlgwidth)); // Dialog height. if (vertical) dlgheight = msgheight + 2 * dlgPaddingY + DLG_VERT_PADDING_Y + 2 * fontHeight * numButtons; else dlgheight = msgheight + 3 * dlgPaddingY + 2 * fontHeight; // Dialog needs to be taller if contains an edit box. editboxheight = fontHeight + dlgPaddingY + 4 * DLG_VERT_PADDING_Y; if (textfield != NULL) dlgheight += editboxheight; add_word(PixelToDialogY(dlgheight)); add_byte(0); //menu add_byte(0); //class /* copy the title of the dialog */ add_string(title ? title : ("Vim"VIM_VERSION_MEDIUM)); buttonYpos = msgheight + 2 * dlgPaddingY; if (textfield != NULL) buttonYpos += editboxheight; pstart = tbuffer; //dflt_text horizWidth = (dlgwidth - horizWidth) / 2; /* Now it's X offset */ for (i = 0; i < numButtons; i++) { /* get end of this button. */ for ( pend = pstart; *pend && (*pend != DLG_BUTTON_SEP); pend++) ; if (*pend) *pend = '\0'; /* * NOTE: * setting the BS_DEFPUSHBUTTON style doesn't work because Windows sets * the focus to the first tab-able button and in so doing makes that * the default!! Grrr. Workaround: Make the default button the only * one with WS_TABSTOP style. Means user can't tab between buttons, but * he/she can use arrow keys. * * NOTE (Thore): Setting BS_DEFPUSHBUTTON works fine when it's the * first one, so I changed the correct button to be this style. This * is necessary because when an edit box is added, we need a button to * be default. The edit box will be the default control, and when the * user presses enter from the edit box we want the default button to * be pressed. */ if (vertical) { p = add_dialog_element(p, ((i == dfltbutton || dfltbutton < 0) && textfield != NULL ? BS_DEFPUSHBUTTON : BS_PUSHBUTTON) | WS_TABSTOP, PixelToDialogX(DLG_VERT_PADDING_X), PixelToDialogY(buttonYpos /* TBK */ + 2 * fontHeight * i), PixelToDialogX(dlgwidth - 2 * DLG_VERT_PADDING_X), (WORD)(PixelToDialogY(2 * fontHeight) - 1), (WORD)(IDCANCEL + 1 + i), (BYTE)0x80, pstart); } else { p = add_dialog_element(p, ((i == dfltbutton || dfltbutton < 0) && textfield != NULL ? BS_DEFPUSHBUTTON : BS_PUSHBUTTON) | WS_TABSTOP, PixelToDialogX(horizWidth + buttonPositions[i]), PixelToDialogY(buttonYpos), /* TBK */ PixelToDialogX(buttonWidths[i]), (WORD)(PixelToDialogY(2 * fontHeight) - 1), (WORD)(IDCANCEL + 1 + i), (BYTE)0x80, pstart); } pstart = pend + 1; /*next button*/ } *pnumitems += numButtons; /* Vim icon */ p = add_dialog_element(p, SS_ICON, PixelToDialogX(dlgPaddingX), PixelToDialogY(dlgPaddingY), PixelToDialogX(DLG_ICON_WIDTH), PixelToDialogY(DLG_ICON_HEIGHT), DLG_NONBUTTON_CONTROL + 0, (BYTE)0x82, &dlg_icons[type]); /* Dialog message */ p = add_dialog_element(p, SS_LEFT, PixelToDialogX(2 * dlgPaddingX + DLG_ICON_WIDTH), PixelToDialogY(dlgPaddingY), (WORD)(PixelToDialogX(messageWidth) + 1), PixelToDialogY(msgheight), DLG_NONBUTTON_CONTROL + 1, (BYTE)0x82, message); /* Edit box */ if (textfield != NULL) { p = add_dialog_element(p, ES_LEFT | ES_AUTOHSCROLL | WS_TABSTOP | WS_BORDER, PixelToDialogX(2 * dlgPaddingX), PixelToDialogY(2 * dlgPaddingY + msgheight), PixelToDialogX(dlgwidth - 4 * dlgPaddingX), PixelToDialogY(fontHeight + dlgPaddingY), DLG_NONBUTTON_CONTROL + 2, (BYTE)0x81, textfield); *pnumitems += 1; } *pnumitems += 2; SelectFont(hdc, oldFont); ReleaseDC(hwnd, hdc); dp = MakeProcInstance((FARPROC)dialog_callback, s_hinst); /* Let the dialog_callback() function know which button to make default * If we have an edit box, make that the default. We also need to tell * dialog_callback() if this dialog contains an edit box or not. We do * this by setting s_textfield if it does. */ if (textfield != NULL) { dialog_default_button = DLG_NONBUTTON_CONTROL + 2; s_textfield = textfield; } else { dialog_default_button = IDCANCEL + 1 + dfltbutton; s_textfield = NULL; } /*show the dialog box modally and get a return value*/ nchar = DialogBoxIndirect( s_hinst, (HGLOBAL) hglbDlgTemp, s_hwnd, (DLGPROC)dp); FreeProcInstance( dp ); GlobalUnlock(hglbDlgTemp); GlobalFree(hglbDlgTemp); vim_free(tbuffer); vim_free(buttonWidths); vim_free(buttonPositions); return nchar; } /* * Put a simple element (basic class) onto a dialog template in memory. * return a pointer to where the next item should be added. * * parameters: * lStyle = additional style flags * x,y = x & y positions IN DIALOG UNITS * w,h = width and height IN DIALOG UNITS * Id = ID used in messages * clss = class ID, e.g 0x80 for a button, 0x82 for a static * caption = usually text or resource name * * TODO: use the length information noted here to enable the dialog creation * routines to work out more exactly how much memory they need to alloc. */ static LPWORD add_dialog_element( LPWORD p, DWORD lStyle, WORD x, WORD y, WORD w, WORD h, WORD Id, BYTE clss, const char *caption) { lStyle = lStyle | WS_VISIBLE | WS_CHILD; add_word(x); add_word(y); add_word(w); add_word(h); add_word(Id); add_long(lStyle); add_byte(clss); if (((lStyle & SS_ICON) != 0) && (clss == 0x82)) { /* Use resource ID */ add_byte(0xff); add_byte(*caption); } else add_string(caption); add_byte(0); //# of extra bytes following return p; } #undef add_byte #undef add_string #undef add_long #undef add_word #endif /* FEAT_GUI_DIALOG */ static void get_dialog_font_metrics(void) { DWORD dlgFontSize; dlgFontSize = GetDialogBaseUnits(); /* fall back to big old system*/ s_dlgfntwidth = LOWORD(dlgFontSize); s_dlgfntheight = HIWORD(dlgFontSize); } #if defined(FEAT_TOOLBAR) || defined(PROTO) #include "gui_w3~1.h" /* * Create the toolbar, initially unpopulated. * (just like the menu, there are no defaults, it's all * set up through menu.vim) */ static void initialise_toolbar(void) { s_toolbarhwnd = CreateToolbar( s_hwnd, WS_CHILD | WS_VISIBLE, CMD_TB_BASE, /*<vn>*/ 31, //number of images in initial bitmap s_hinst, IDR_TOOLBAR1, // id of initial bitmap NULL, 0 // initial number of buttons ); gui_mch_show_toolbar(vim_strchr(p_go, GO_TOOLBAR) != NULL); } #endif #if defined(FEAT_OLE) || defined(FEAT_EVAL) || defined(PROTO) /* * Make the GUI window come to the foreground. */ void gui_mch_set_foreground(void) { if (IsIconic(s_hwnd)) SendMessage(s_hwnd, WM_SYSCOMMAND, SC_RESTORE, 0); SetActiveWindow(s_hwnd); } #endif
zyz2011-vim
src/gui_w16.c
C
gpl2
38,587
/* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 3.01.75 */ /* at Wed Jun 06 18:20:37 2001 */ /* Compiler settings for .\if_ole.idl: Os (OptLev=s), W1, Zp8, env=Win32, ms_ext, c_ext error checks: none */ //@@MIDL_FILE_HEADING( ) #include "rpc.h" #include "rpcndr.h" #ifndef COM_NO_WINDOWS_H #include "windows.h" #include "ole2.h" #endif /*COM_NO_WINDOWS_H*/ #ifndef __if_ole_h__ #define __if_ole_h__ #ifdef __cplusplus extern "C"{ #endif /* Forward Declarations */ #ifndef __IVim_FWD_DEFINED__ #define __IVim_FWD_DEFINED__ typedef interface IVim IVim; #endif /* __IVim_FWD_DEFINED__ */ #ifndef __Vim_FWD_DEFINED__ #define __Vim_FWD_DEFINED__ #ifdef __cplusplus typedef class Vim Vim; #else typedef struct Vim Vim; #endif /* __cplusplus */ #endif /* __Vim_FWD_DEFINED__ */ /* header files for imported files */ #include "oaidl.h" #ifndef __MIDL_user_allocate_free_DEFINED__ #define __MIDL_user_allocate_free_DEFINED__ void __RPC_FAR * __RPC_USER MIDL_user_allocate(size_t); void __RPC_USER MIDL_user_free( void __RPC_FAR * ); #endif #ifndef __IVim_INTERFACE_DEFINED__ #define __IVim_INTERFACE_DEFINED__ /**************************************** * Generated header for interface: IVim * at Wed Jun 06 18:20:37 2001 * using MIDL 3.01.75 ****************************************/ /* [oleautomation][dual][unique][helpstring][uuid][object] */ EXTERN_C const IID IID_IVim; #if defined(__cplusplus) && !defined(CINTERFACE) interface DECLSPEC_UUID("0F0BFAE2-4C90-11d1-82D7-0004AC368519") IVim : public IDispatch { public: virtual HRESULT STDMETHODCALLTYPE SendKeys( /* [in] */ BSTR keys) = 0; virtual HRESULT STDMETHODCALLTYPE Eval( /* [in] */ BSTR expr, /* [retval][out] */ BSTR __RPC_FAR *result) = 0; virtual HRESULT STDMETHODCALLTYPE SetForeground( void) = 0; virtual HRESULT STDMETHODCALLTYPE GetHwnd( /* [retval][out] */ UINT_PTR __RPC_FAR *result) = 0; }; #else /* C style interface */ typedef struct IVimVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )( IVim __RPC_FAR * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject); ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )( IVim __RPC_FAR * This); ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )( IVim __RPC_FAR * This); HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetTypeInfoCount )( IVim __RPC_FAR * This, /* [out] */ UINT __RPC_FAR *pctinfo); HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetTypeInfo )( IVim __RPC_FAR * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo); HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetIDsOfNames )( IVim __RPC_FAR * This, /* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Invoke )( IVim __RPC_FAR * This, /* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr); HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SendKeys )( IVim __RPC_FAR * This, /* [in] */ BSTR keys); HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Eval )( IVim __RPC_FAR * This, /* [in] */ BSTR expr, /* [retval][out] */ BSTR __RPC_FAR *result); HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetForeground )( IVim __RPC_FAR * This); HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetHwnd )( IVim __RPC_FAR * This, /* [retval][out] */ UINT_PTR __RPC_FAR *result); END_INTERFACE } IVimVtbl; interface IVim { CONST_VTBL struct IVimVtbl __RPC_FAR *lpVtbl; }; #ifdef COBJMACROS #define IVim_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVim_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVim_Release(This) \ (This)->lpVtbl -> Release(This) #define IVim_GetTypeInfoCount(This,pctinfo) \ (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) #define IVim_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) #define IVim_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) #define IVim_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) #define IVim_SendKeys(This,keys) \ (This)->lpVtbl -> SendKeys(This,keys) #define IVim_Eval(This,expr,result) \ (This)->lpVtbl -> Eval(This,expr,result) #define IVim_SetForeground(This) \ (This)->lpVtbl -> SetForeground(This) #define IVim_GetHwnd(This,result) \ (This)->lpVtbl -> GetHwnd(This,result) #endif /* COBJMACROS */ #endif /* C style interface */ HRESULT STDMETHODCALLTYPE IVim_SendKeys_Proxy( IVim __RPC_FAR * This, /* [in] */ BSTR keys); void __RPC_STUB IVim_SendKeys_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVim_Eval_Proxy( IVim __RPC_FAR * This, /* [in] */ BSTR expr, /* [retval][out] */ BSTR __RPC_FAR *result); void __RPC_STUB IVim_Eval_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVim_SetForeground_Proxy( IVim __RPC_FAR * This); void __RPC_STUB IVim_SetForeground_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVim_GetHwnd_Proxy( IVim __RPC_FAR * This, /* [retval][out] */ UINT_PTR __RPC_FAR *result); void __RPC_STUB IVim_GetHwnd_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVim_INTERFACE_DEFINED__ */ #ifndef __Vim_LIBRARY_DEFINED__ #define __Vim_LIBRARY_DEFINED__ /**************************************** * Generated header for library: Vim * at Wed Jun 06 18:20:37 2001 * using MIDL 3.01.75 ****************************************/ /* [version][helpstring][uuid] */ EXTERN_C const IID LIBID_Vim; #ifdef __cplusplus EXTERN_C const CLSID CLSID_Vim; class DECLSPEC_UUID("0F0BFAE1-4C90-11d1-82D7-0004AC368519") Vim; #endif #endif /* __Vim_LIBRARY_DEFINED__ */ /* Additional Prototypes for ALL interfaces */ unsigned long __RPC_USER BSTR_UserSize( unsigned long __RPC_FAR *, unsigned long , BSTR __RPC_FAR * ); unsigned char __RPC_FAR * __RPC_USER BSTR_UserMarshal( unsigned long __RPC_FAR *, unsigned char __RPC_FAR *, BSTR __RPC_FAR * ); unsigned char __RPC_FAR * __RPC_USER BSTR_UserUnmarshal(unsigned long __RPC_FAR *, unsigned char __RPC_FAR *, BSTR __RPC_FAR * ); void __RPC_USER BSTR_UserFree( unsigned long __RPC_FAR *, BSTR __RPC_FAR * ); /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
zyz2011-vim
src/if_ole.h
C++
gpl2
7,487
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * os_win16.c * * Win16 (Windows 3.1x) system-dependent routines. * Carved brutally from os_win32.c by Vince Negri <vn@aslnet.co.uk> */ #ifdef __BORLANDC__ # pragma warn -par # pragma warn -ucp # pragma warn -use # pragma warn -aus # pragma warn -obs #endif #include "vim.h" #include <dos.h> #include <string.h> #include <sys/types.h> #include <signal.h> #include <limits.h> #include <process.h> #undef chdir #include <direct.h> #include <shellapi.h> /* required for FindExecutable() */ /* Record all output and all keyboard & mouse input */ /* #define MCH_WRITE_DUMP */ #ifdef MCH_WRITE_DUMP FILE* fdDump = NULL; #endif /* * When generating prototypes for Win32 on Unix, these lines make the syntax * errors disappear. They do not need to be correct. */ #ifdef PROTO typedef int HANDLE; typedef int SMALL_RECT; typedef int COORD; typedef int SHORT; typedef int WORD; typedef int DWORD; typedef int BOOL; typedef int LPSTR; typedef int LPTSTR; typedef int KEY_EVENT_RECORD; typedef int MOUSE_EVENT_RECORD; # define WINAPI typedef int CONSOLE_CURSOR_INFO; typedef char * LPCSTR; # define WINBASEAPI typedef int INPUT_RECORD; # define _cdecl #endif #ifdef __BORLANDC__ /* being a more ANSI compliant compiler, BorlandC doesn't define _stricoll: * but it does in BC 5.02! */ # if __BORLANDC__ < 0x502 int _stricoll(char *a, char *b); # endif #endif /* cproto doesn't create a prototype for main() */ int _cdecl VimMain __ARGS((int argc, char **argv)); static int (_cdecl *pmain)(int, char **); #ifndef PROTO void _cdecl SaveInst(HINSTANCE hInst); static void (_cdecl *pSaveInst)(HINSTANCE); int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInst, LPSTR lpszCmdLine, int nCmdShow) { int argc; char **argv; char *tofree; char prog[256]; /* * Ron: added full path name so that the $VIM variable will get set to our * startup path (so the .vimrc file can be found w/o a VIM env. var.) * Remove the ".exe" extension, and find the 1st non-space. */ GetModuleFileName(hInstance, prog, 255); if (*prog != NUL) exe_name = FullName_save((char_u *)prog, FALSE); /* Separate the command line into arguments. */ argc = get_cmd_args(prog, (char *)lpszCmdLine, &argv, &tofree); if (argc == 0) { /* Error message? */ return 0; } pSaveInst = SaveInst; pmain = VimMain; pSaveInst(hInstance); pmain(argc, argv); free(argv); if (tofree != NULL) free(tofree); return 0; } #endif #ifdef FEAT_MOUSE /* * For the GUI the mouse handling is in gui_w32.c. */ void mch_setmouse( int on) { } #endif /* FEAT_MOUSE */ /* * GUI version of mch_init(). */ void mch_init() { extern int _fmode; /* Let critical errors result in a failure, not in a dialog box. Required * for the timestamp test to work on removed floppies. */ SetErrorMode(SEM_FAILCRITICALERRORS); _fmode = O_BINARY; /* we do our own CR-LF translation */ /* Specify window size. Is there a place to get the default from? */ Rows = 25; Columns = 80; set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0); #ifdef FEAT_CLIPBOARD clip_init(TRUE); /* * Vim's own clipboard format recognises whether the text is char, line, * or rectangular block. Only useful for copying between two Vims. * "VimClipboard" was used for previous versions, using the first * character to specify MCHAR, MLINE or MBLOCK. */ clip_star.format = RegisterClipboardFormat("VimClipboard2"); clip_star.format_raw = RegisterClipboardFormat("VimRawBytes"); #endif } /* * Do we have an interactive window? */ int mch_check_win( int argc, char **argv) { return OK; /* GUI always has a tty */ } /* * return process ID */ long mch_get_pid() { return (long)GetCurrentTask(); } /* * Specialised version of system(). * This version proceeds as follows: * 1. Start the program with WinExec * 2. Wait for the module use count of the program to go to 0 * (This is the best way of detecting the program has finished) */ static int mch_system(char *cmd, int options) { DWORD ret = 0; UINT wShowWindow; UINT h_module; MSG msg; BOOL again = TRUE; /* * It's nicer to run a filter command in a minimized window, but in */ if (options & SHELL_DOOUT) wShowWindow = SW_SHOWMINIMIZED; else wShowWindow = SW_SHOWNORMAL; /* Now, run the command */ h_module = WinExec((LPCSTR)cmd, wShowWindow); if (h_module < 32) { /*error*/ ret = -h_module; } else { /* Wait for the command to terminate before continuing */ while (GetModuleUsage((HINSTANCE)h_module) > 0 && again ) { while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) && again) { if (msg.message == WM_QUIT) { PostQuitMessage(msg.wParam); again = FALSE; } TranslateMessage(&msg); DispatchMessage(&msg); } } } return ret; } /* * Either execute a command by calling the shell or start a new shell */ int mch_call_shell( char_u *cmd, int options) /* SHELL_, see vim.h */ { int x; int tmode = cur_tmode; out_flush(); #ifdef MCH_WRITE_DUMP if (fdDump) { fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options); fflush(fdDump); } #endif /* * Catch all deadly signals while running the external command, because a * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us. */ signal(SIGINT, SIG_IGN); signal(SIGILL, SIG_IGN); signal(SIGFPE, SIG_IGN); signal(SIGSEGV, SIG_IGN); signal(SIGTERM, SIG_IGN); signal(SIGABRT, SIG_IGN); if (options & SHELL_COOKED) settmode(TMODE_COOK); /* set to normal mode */ if (cmd == NULL) { x = mch_system(p_sh, options); } else { /* we use "command" or "cmd" to start the shell; slow but easy */ char_u *newcmd; newcmd = lalloc( STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10, TRUE); if (newcmd != NULL) { if (STRNICMP(cmd, "start ", 6) == 0) { sprintf((char *)newcmd, "%s\0", cmd+6); if (WinExec((LPCSTR)newcmd, SW_SHOWNORMAL) > 31) x = 0; else x = -1; } else { sprintf((char *)newcmd, "%s%s %s %s", "", p_sh, p_shcf, cmd); x = mch_system((char *)newcmd, options); } vim_free(newcmd); } } if (tmode == TMODE_RAW) settmode(TMODE_RAW); /* set to raw mode */ if (x && !(options & SHELL_SILENT) && !emsg_silent) { smsg(_("shell returned %d"), x); msg_putchar('\n'); } #ifdef FEAT_TITLE resettitle(); #endif signal(SIGINT, SIG_DFL); signal(SIGILL, SIG_DFL); signal(SIGFPE, SIG_DFL); signal(SIGSEGV, SIG_DFL); signal(SIGTERM, SIG_DFL); signal(SIGABRT, SIG_DFL); return x; } /* * Delay for half a second. */ void mch_delay( long msec, int ignoreinput) { #ifdef MUST_FIX Sleep((int)msec); /* never wait for input */ #endif } /* * check for an "interrupt signal": CTRL-break or CTRL-C */ void mch_breakcheck() { /* never used */ } /* * How much memory is available? */ long_u mch_avail_mem( int special) { return GetFreeSpace(0); } /* * Like rename(), returns 0 upon success, non-zero upon failure. * Should probably set errno appropriately when errors occur. */ int mch_rename( const char *pszOldFile, const char *pszNewFile) { /* * No need to play tricks, this isn't rubbish like Windows 95 <g> */ return rename(pszOldFile, pszNewFile); } /* * Get the default shell for the current hardware platform */ char* default_shell() { char* psz = NULL; psz = "command.com"; return psz; }
zyz2011-vim
src/os_win16.c
C
gpl2
8,058
# # Makefile for VIM on MSDOS, using DJGPP 2.0 # #>>>>> choose options: ### See feature.h for a list of optionals. ### Any other defines can be included here. DEFINES = #>>>>> name of the compiler and linker, name of lib directory CC = gcc #>>>>> end of choices ########################################################################### INCL = vim.h globals.h option.h keymap.h macros.h ascii.h term.h os_msdos.h structs.h CFLAGS = -O2 -DMSDOS -Iproto $(DEFINES) -Wall -Dinterrupt= -Dfar= -DMAXMEM=512 -D_NAIVE_DOS_REGS OBJ = \ obj/blowfish.o \ obj/buffer.o \ obj/charset.o \ obj/diff.o \ obj/digraph.o \ obj/edit.o \ obj/eval.o \ obj/ex_cmds.o \ obj/ex_cmds2.o \ obj/ex_docmd.o \ obj/ex_eval.o \ obj/ex_getln.o \ obj/fileio.o \ obj/fold.o \ obj/getchar.o \ obj/hardcopy.o \ obj/hashtab.o \ obj/main.o \ obj/mark.o \ obj/memfile.o \ obj/memline.o \ obj/menu.o \ obj/message.o \ obj/misc1.o \ obj/misc2.o \ obj/move.o \ obj/mbyte.o \ obj/normal.o \ obj/ops.o \ obj/option.o \ obj/os_msdos.o \ obj/popupmnu.o \ obj/quickfix.o \ obj/regexp.o \ obj/screen.o \ obj/search.o \ obj/sha256.o \ obj/spell.o \ obj/syntax.o \ obj/tag.o \ obj/term.o \ obj/ui.o \ obj/undo.o \ obj/window.o \ $(TERMLIB) all: vim.exe install.exe uninstal.exe xxd/xxd.exe # version.c is compiled each time, so that it sets the build time. vim.exe: obj $(OBJ) version.c version.h $(CC) $(CFLAGS) -s -o vim.exe version.c $(OBJ) -lpc install.exe: dosinst.c $(CC) $(CFLAGS) -s -o install.exe dosinst.c -lpc uninstal.exe: uninstal.c $(CC) $(CFLAGS) -s -o uninstal.exe uninstal.c -lpc # This requires GNU make. xxd/xxd.exe: xxd/xxd.c $(MAKE) --directory=xxd -f Make_djg.mak obj: mkdir obj tags: command /c ctags *.c $(INCL) ex_cmds.h clean: -del obj\*.o -rmdir obj -del vim.exe -del install.exe -del xxd\xxd.exe -del testdir\*.out # This requires GNU make. test: $(MAKE) --directory=testdir -f Make_dos.mak ########################################################################### obj/%.o: %.c obj $(INCL) $(CC) -c $(CFLAGS) -o $@ $< # Extra dependency (there are actually many more...) obj/ex_docmd.o: ex_cmds.h
zyz2011-vim
src/Make_djg.mak
Makefile
gpl2
2,156
/* vi:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * Win16 Toolbar by Vince Negri - External Header * (Based on MS Sample Code) * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. */ // // Button Structure // typedef struct tagTBBUTTON { int iBitmap; // index into bitmap of this button's picture int idCommand; // WM_COMMAND menu ID that this button sends BYTE fsState; // button's state BYTE fsStyle; // button's style } TBBUTTON; typedef TBBUTTON NEAR* PTBBUTTON; typedef TBBUTTON FAR* LPTBBUTTON; typedef const TBBUTTON FAR* LPCTBBUTTON; // // Styles // #define TBSTYLE_BUTTON 0x00 // this entry is button #define TBSTYLE_SEP 0x01 // this entry is a separator #define TBSTYLE_CHECK 0x02 // this is a check button (it stays down) #define TBSTYLE_GROUP 0x04 // this is a check button (it stays down) #define TBSTYLE_CHECKGROUP (TBSTYLE_GROUP | TBSTYLE_CHECK) // this group is a member of a group radio group // // States // #define TBSTATE_CHECKED 0x01 // radio button is checked #define TBSTATE_PRESSED 0x02 // button is being depressed (any style) #define TBSTATE_ENABLED 0x04 // button is enabled #define TBSTATE_HIDDEN 0x08 // button is hidden #define TBSTATE_INDETERMINATE 0x10 // button is indeterminate #define TBSTATE_SELECTED 0x20 // mouse hovering over button (for coolbar look) typedef struct tagADJUSTINFO { TBBUTTON tbButton; char szDescription[1]; } ADJUSTINFO; typedef ADJUSTINFO NEAR* PADJUSTINFO; typedef ADJUSTINFO FAR* LPADJUSTINFO; HWND WINAPI CreateToolbar(HWND hwnd, DWORD ws, WORD wID, int nBitmaps, HINSTANCE hBMInst, WORD wBMID, LPCTBBUTTON lpButtons, int iNumButtons); #define CMB_DISCARDABLE 0x01 // create bitmap as discardable #define CMB_MASKED 0x02 // create image/mask pair in bitmap #define TB_ENABLEBUTTON (WM_USER + 1) // wParam: UINT, button ID // lParam: BOOL LOWORD, enable if nonzero; HIWORD not used, 0 // return: not used // #define TB_CHECKBUTTON (WM_USER + 2) // wParam: UINT, button ID // lParam: BOOL LOWORD, check if nonzero; HIWORD not used, 0 // return: not used // #define TB_PRESSBUTTON (WM_USER + 3) // wParam: UINT, button ID // lParam: BOOL LOWORD, press if nonzero; HIWORD not used, 0 // return: not used // #define TB_HIDEBUTTON (WM_USER + 4) // wParam: UINT, button ID // lParam: BOOL LOWORD, hide if nonzero; HIWORD not used, 0 // return: not used // #define TB_INDETERMINATE (WM_USER + 5) // wParam: UINT, button ID // lParam: BOOL LOWORD, make indeterminate if nonzero; HIWORD not used, 0 // return: not used // #define TB_ISBUTTONENABLED (WM_USER + 9) // wParam: UINT, button ID // lParam: not used, 0 // return: BOOL LOWORD, enabled if nonzero; HIWORD not used // #define TB_ISBUTTONCHECKED (WM_USER + 10) // wParam: UINT, button ID // lParam: not used, 0 // return: BOOL LOWORD, checked if nonzero; HIWORD not used // #define TB_ISBUTTONPRESSED (WM_USER + 11) // wParam: UINT, button ID // lParam: not used, 0 // return: BOOL LOWORD, pressed if nonzero; HIWORD not used // #define TB_ISBUTTONHIDDEN (WM_USER + 12) // wParam: UINT, button ID // lParam: not used, 0 // return: BOOL LOWORD, hidden if nonzero; HIWORD not used // #define TB_ISBUTTONINDETERMINATE (WM_USER + 13) // wParam: UINT, button ID // lParam: not used, 0 // return: BOOL LOWORD, indeterminate if nonzero; HIWORD not used // #define TB_SETSTATE (WM_USER + 17) // wParam: UINT, button ID // lParam: UINT LOWORD, state bits; HIWORD not used, 0 // return: not used // #define TB_GETSTATE (WM_USER + 18) // wParam: UINT, button ID // lParam: not used, 0 // return: UINT LOWORD, state bits; HIWORD not used // #define TB_ADDBITMAP (WM_USER + 19) // wParam: UINT, number of button graphics in bitmap // lParam: one of: // HINSTANCE LOWORD, module handle; UINT HIWORD, resource id // HINSTANCE LOWORD, NULL; HBITMAP HIWORD, bitmap handle // return: one of: // int LOWORD, index for first new button; HIWORD not used // int LOWORD, -1 indicating error; HIWORD not used // #define TB_ADDBUTTONS (WM_USER + 20) // wParam: UINT, number of buttons to add // lParam: LPTBBUTTON, pointer to array of TBBUTTON structures // return: not used // #define TB_INSERTBUTTON (WM_USER + 21) // wParam: UINT, index for insertion (appended if index doesn't exist) // lParam: LPTBBUTTON, pointer to one TBBUTTON structure // return: not used // #define TB_DELETEBUTTON (WM_USER + 22) // wParam: UINT, index of button to delete // lParam: not used, 0 // return: not used // #define TB_GETBUTTON (WM_USER + 23) // wParam: UINT, index of button to get // lParam: LPTBBUTTON, pointer to TBBUTTON buffer to receive button // return: not used // #define TB_BUTTONCOUNT (WM_USER + 24) // wParam: not used, 0 // lParam: not used, 0 // return: UINT LOWORD, number of buttons; HIWORD not used // #define TB_COMMANDTOINDEX (WM_USER + 25) // wParam: UINT, command id // lParam: not used, 0 // return: UINT LOWORD, index of button (-1 if command not found); // HIWORD not used // #define TBN_BEGINDRAG 0x0201 #define TBN_ENDDRAG 0x0203
zyz2011-vim
src/vimtbar.h
C
gpl2
5,153
#! /bin/sh # # which.sh -- find where an executable is located. It's here because the # "which" command is not supported everywhere. Used by Makefile. IFS=":" for ac_dir in $PATH; do if test -f "$ac_dir/$1"; then echo "$ac_dir/$1" break fi done
zyz2011-vim
src/which.sh
Shell
gpl2
254
/* vi:set ts=8 sts=8 sw=8: * * VIM - Vi IMproved by Bram Moolenaar * Visual Workshop integration by Gordon Prieur * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * WorkShop Debugging Tools. What are these tools and why are they important? * There are two main tools here. The first tool is a tool for delaying or * stopping gvim during startup. The second tool is a protocol log tool. * * The startup delay tool is called wsdebug_wait(). This is very important for * debugging startup problems because gvim will be started automatically from * workshop and cannot be run directly from a debugger. The only way to debug * a gvim started by workshop is by attaching a debugger to it. Without this * tool all starup code will have completed before you can get the pid and * attach. * * The second tool is a protocol log tool. The workshop editor server and gvim * pass information back and forth during a workshop session. Sometimes it is * very important to peruse this conversation in order to understand what is * happening. The wsdebug_log_init() call sets up this protocol log tool and * wsdebug() and wstrace() calls output the information to the log. * * This code must have WSDEBUG defined for it to be compiled into vim/gvim. */ #ifdef WSDEBUG #include "vim.h" FILE *ws_debug = NULL; u_int ws_dlevel = 0; /* ws_debug verbosity level */ void wsdebug(char *, ...); void wstrace(char *, ...); static int lookup(char *); #ifdef USE_WS_ERRORHANDLER static int errorHandler(Display *, XErrorEvent *); #endif /* * wsdebug_wait - This function can be used to delay or stop execution of vim. * Its normally used to delay startup while attaching a * debugger to a running process. Since workshop starts gvim * from a background process this is the only way to debug * startup problems. */ void wsdebug_wait( u_int wait_flags, /* tells what to do */ char *wait_var, /* wait environment variable */ u_int wait_secs) /* how many seconds to wait */ { init_homedir(); /* not inited yet */ #ifdef USE_WDDUMP WDDump(0, 0, 0); #endif /* for debugging purposes only */ if (wait_flags & WT_ENV && wait_var && getenv(wait_var) != NULL) { sleep(atoi(getenv(wait_var))); } else if (wait_flags & WT_WAIT && lookup("~/.gvimwait")) { sleep(wait_secs > 0 && wait_secs < 120 ? wait_secs : 20); } else if (wait_flags & WT_STOP && lookup("~/.gvimstop")) { int w = 1; while (w) { ; } } } /* end wsdebug_wait */ void wsdebug_log_init( char *log_var, /* env var with log file */ char *level_var) /* env var with ws_debug level */ { char *file; /* possible ws_debug output file */ char *cp; /* ws_dlevel pointer */ if (log_var && (file = getenv(log_var)) != NULL) { char buf[BUFSIZ]; vim_snprintf(buf, sizeof(buf), "date > %s", file); system(buf); ws_debug = fopen(file, "a"); if (level_var && (cp = getenv(level_var)) != NULL) { ws_dlevel = strtoul(cp, NULL, 0); } else { ws_dlevel = WS_TRACE; /* default level */ } #ifdef USE_WS_ERRORHANDLER XSetErrorHandler(errorHandler); #endif } } /* end wsdebug_log_init */ void wstrace( char *fmt, ...) { va_list ap; if (ws_debug!= NULL && (ws_dlevel & (WS_TRACE | WS_TRACE_VERBOSE))) { va_start(ap, fmt); vfprintf(ws_debug, fmt, ap); va_end(ap); fflush(ws_debug); } } /* end wstrace */ void wsdebug( char *fmt, ...) { va_list ap; if (ws_debug != NULL) { va_start(ap, fmt); vfprintf(ws_debug, fmt, ap); va_end(ap); fflush(ws_debug); } } /* end wsdebug */ static int lookup( char *file) { char buf[BUFSIZ]; expand_env((char_u *) file, (char_u *) buf, BUFSIZ); return (access(buf, F_OK) == 0); } /* end lookup */ #ifdef USE_WS_ERRORHANDLER static int errorHandler( Display *dpy, XErrorEvent *err) { char msg[256]; char buf[256]; XGetErrorText(dpy, err->error_code, msg, sizeof(msg)); wsdebug("\n\nWSDEBUG Vim: X Error of failed request: %s\n", msg); sprintf(buf, "%d", err->request_code); XGetErrorDatabaseText(dpy, "XRequest", buf, "Unknown", msg, sizeof(msg)); wsdebug("\tMajor opcode of failed request: %d (%s)\n", err->request_code, msg); if (err->request_code > 128) { wsdebug("\tMinor opcode of failed request: %d\n", err->minor_code); } return 0; } #endif #endif /* WSDEBUG */
zyz2011-vim
src/wsdebug.c
C
gpl2
4,506
/* vim:set ts=8 sts=4 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * diff.c: code for diff'ing two, three or four buffers. */ #include "vim.h" #if defined(FEAT_DIFF) || defined(PROTO) static int diff_busy = FALSE; /* ex_diffgetput() is busy */ /* flags obtained from the 'diffopt' option */ #define DIFF_FILLER 1 /* display filler lines */ #define DIFF_ICASE 2 /* ignore case */ #define DIFF_IWHITE 4 /* ignore change in white space */ #define DIFF_HORIZONTAL 8 /* horizontal splits */ #define DIFF_VERTICAL 16 /* vertical splits */ static int diff_flags = DIFF_FILLER; #define LBUFLEN 50 /* length of line in diff file */ static int diff_a_works = MAYBE; /* TRUE when "diff -a" works, FALSE when it doesn't work, MAYBE when not checked yet */ #if defined(MSWIN) || defined(MSDOS) static int diff_bin_works = MAYBE; /* TRUE when "diff --binary" works, FALSE when it doesn't work, MAYBE when not checked yet */ #endif static int diff_buf_idx __ARGS((buf_T *buf)); static int diff_buf_idx_tp __ARGS((buf_T *buf, tabpage_T *tp)); static void diff_mark_adjust_tp __ARGS((tabpage_T *tp, int idx, linenr_T line1, linenr_T line2, long amount, long amount_after)); static void diff_check_unchanged __ARGS((tabpage_T *tp, diff_T *dp)); static int diff_check_sanity __ARGS((tabpage_T *tp, diff_T *dp)); static void diff_redraw __ARGS((int dofold)); static int diff_write __ARGS((buf_T *buf, char_u *fname)); static void diff_file __ARGS((char_u *tmp_orig, char_u *tmp_new, char_u *tmp_diff)); static int diff_equal_entry __ARGS((diff_T *dp, int idx1, int idx2)); static int diff_cmp __ARGS((char_u *s1, char_u *s2)); #ifdef FEAT_FOLDING static void diff_fold_update __ARGS((diff_T *dp, int skip_idx)); #endif static void diff_read __ARGS((int idx_orig, int idx_new, char_u *fname)); static void diff_copy_entry __ARGS((diff_T *dprev, diff_T *dp, int idx_orig, int idx_new)); static diff_T *diff_alloc_new __ARGS((tabpage_T *tp, diff_T *dprev, diff_T *dp)); #ifndef USE_CR # define tag_fgets vim_fgets #endif /* * Called when deleting or unloading a buffer: No longer make a diff with it. */ void diff_buf_delete(buf) buf_T *buf; { int i; tabpage_T *tp; for (tp = first_tabpage; tp != NULL; tp = tp->tp_next) { i = diff_buf_idx_tp(buf, tp); if (i != DB_COUNT) { tp->tp_diffbuf[i] = NULL; tp->tp_diff_invalid = TRUE; if (tp == curtab) diff_redraw(TRUE); } } } /* * Check if the current buffer should be added to or removed from the list of * diff buffers. */ void diff_buf_adjust(win) win_T *win; { win_T *wp; int i; if (!win->w_p_diff) { /* When there is no window showing a diff for this buffer, remove * it from the diffs. */ for (wp = firstwin; wp != NULL; wp = wp->w_next) if (wp->w_buffer == win->w_buffer && wp->w_p_diff) break; if (wp == NULL) { i = diff_buf_idx(win->w_buffer); if (i != DB_COUNT) { curtab->tp_diffbuf[i] = NULL; curtab->tp_diff_invalid = TRUE; diff_redraw(TRUE); } } } else diff_buf_add(win->w_buffer); } /* * Add a buffer to make diffs for. * Call this when a new buffer is being edited in the current window where * 'diff' is set. * Marks the current buffer as being part of the diff and requiring updating. * This must be done before any autocmd, because a command may use info * about the screen contents. */ void diff_buf_add(buf) buf_T *buf; { int i; if (diff_buf_idx(buf) != DB_COUNT) return; /* It's already there. */ for (i = 0; i < DB_COUNT; ++i) if (curtab->tp_diffbuf[i] == NULL) { curtab->tp_diffbuf[i] = buf; curtab->tp_diff_invalid = TRUE; diff_redraw(TRUE); return; } EMSGN(_("E96: Can not diff more than %ld buffers"), DB_COUNT); } /* * Find buffer "buf" in the list of diff buffers for the current tab page. * Return its index or DB_COUNT if not found. */ static int diff_buf_idx(buf) buf_T *buf; { int idx; for (idx = 0; idx < DB_COUNT; ++idx) if (curtab->tp_diffbuf[idx] == buf) break; return idx; } /* * Find buffer "buf" in the list of diff buffers for tab page "tp". * Return its index or DB_COUNT if not found. */ static int diff_buf_idx_tp(buf, tp) buf_T *buf; tabpage_T *tp; { int idx; for (idx = 0; idx < DB_COUNT; ++idx) if (tp->tp_diffbuf[idx] == buf) break; return idx; } /* * Mark the diff info involving buffer "buf" as invalid, it will be updated * when info is requested. */ void diff_invalidate(buf) buf_T *buf; { tabpage_T *tp; int i; for (tp = first_tabpage; tp != NULL; tp = tp->tp_next) { i = diff_buf_idx_tp(buf, tp); if (i != DB_COUNT) { tp->tp_diff_invalid = TRUE; if (tp == curtab) diff_redraw(TRUE); } } } /* * Called by mark_adjust(): update line numbers in "curbuf". */ void diff_mark_adjust(line1, line2, amount, amount_after) linenr_T line1; linenr_T line2; long amount; long amount_after; { int idx; tabpage_T *tp; /* Handle all tab pages that use the current buffer in a diff. */ for (tp = first_tabpage; tp != NULL; tp = tp->tp_next) { idx = diff_buf_idx_tp(curbuf, tp); if (idx != DB_COUNT) diff_mark_adjust_tp(tp, idx, line1, line2, amount, amount_after); } } /* * Update line numbers in tab page "tp" for "curbuf" with index "idx". * This attempts to update the changes as much as possible: * When inserting/deleting lines outside of existing change blocks, create a * new change block and update the line numbers in following blocks. * When inserting/deleting lines in existing change blocks, update them. */ static void diff_mark_adjust_tp(tp, idx, line1, line2, amount, amount_after) tabpage_T *tp; int idx; linenr_T line1; linenr_T line2; long amount; long amount_after; { diff_T *dp; diff_T *dprev; diff_T *dnext; int i; int inserted, deleted; int n, off; linenr_T last; linenr_T lnum_deleted = line1; /* lnum of remaining deletion */ int check_unchanged; if (line2 == MAXLNUM) { /* mark_adjust(99, MAXLNUM, 9, 0): insert lines */ inserted = amount; deleted = 0; } else if (amount_after > 0) { /* mark_adjust(99, 98, MAXLNUM, 9): a change that inserts lines*/ inserted = amount_after; deleted = 0; } else { /* mark_adjust(98, 99, MAXLNUM, -2): delete lines */ inserted = 0; deleted = -amount_after; } dprev = NULL; dp = tp->tp_first_diff; for (;;) { /* If the change is after the previous diff block and before the next * diff block, thus not touching an existing change, create a new diff * block. Don't do this when ex_diffgetput() is busy. */ if ((dp == NULL || dp->df_lnum[idx] - 1 > line2 || (line2 == MAXLNUM && dp->df_lnum[idx] > line1)) && (dprev == NULL || dprev->df_lnum[idx] + dprev->df_count[idx] < line1) && !diff_busy) { dnext = diff_alloc_new(tp, dprev, dp); if (dnext == NULL) return; dnext->df_lnum[idx] = line1; dnext->df_count[idx] = inserted; for (i = 0; i < DB_COUNT; ++i) if (tp->tp_diffbuf[i] != NULL && i != idx) { if (dprev == NULL) dnext->df_lnum[i] = line1; else dnext->df_lnum[i] = line1 + (dprev->df_lnum[i] + dprev->df_count[i]) - (dprev->df_lnum[idx] + dprev->df_count[idx]); dnext->df_count[i] = deleted; } } /* if at end of the list, quit */ if (dp == NULL) break; /* * Check for these situations: * 1 2 3 * 1 2 3 * line1 2 3 4 5 * 2 3 4 5 * 2 3 4 5 * line2 2 3 4 5 * 3 5 6 * 3 5 6 */ /* compute last line of this change */ last = dp->df_lnum[idx] + dp->df_count[idx] - 1; /* 1. change completely above line1: nothing to do */ if (last >= line1 - 1) { /* 6. change below line2: only adjust for amount_after; also when * "deleted" became zero when deleted all lines between two diffs */ if (dp->df_lnum[idx] - (deleted + inserted != 0) > line2) { if (amount_after == 0) break; /* nothing left to change */ dp->df_lnum[idx] += amount_after; } else { check_unchanged = FALSE; /* 2. 3. 4. 5.: inserted/deleted lines touching this diff. */ if (deleted > 0) { if (dp->df_lnum[idx] >= line1) { off = dp->df_lnum[idx] - lnum_deleted; if (last <= line2) { /* 4. delete all lines of diff */ if (dp->df_next != NULL && dp->df_next->df_lnum[idx] - 1 <= line2) { /* delete continues in next diff, only do * lines until that one */ n = dp->df_next->df_lnum[idx] - lnum_deleted; deleted -= n; n -= dp->df_count[idx]; lnum_deleted = dp->df_next->df_lnum[idx]; } else n = deleted - dp->df_count[idx]; dp->df_count[idx] = 0; } else { /* 5. delete lines at or just before top of diff */ n = off; dp->df_count[idx] -= line2 - dp->df_lnum[idx] + 1; check_unchanged = TRUE; } dp->df_lnum[idx] = line1; } else { off = 0; if (last < line2) { /* 2. delete at end of of diff */ dp->df_count[idx] -= last - lnum_deleted + 1; if (dp->df_next != NULL && dp->df_next->df_lnum[idx] - 1 <= line2) { /* delete continues in next diff, only do * lines until that one */ n = dp->df_next->df_lnum[idx] - 1 - last; deleted -= dp->df_next->df_lnum[idx] - lnum_deleted; lnum_deleted = dp->df_next->df_lnum[idx]; } else n = line2 - last; check_unchanged = TRUE; } else { /* 3. delete lines inside the diff */ n = 0; dp->df_count[idx] -= deleted; } } for (i = 0; i < DB_COUNT; ++i) if (tp->tp_diffbuf[i] != NULL && i != idx) { dp->df_lnum[i] -= off; dp->df_count[i] += n; } } else { if (dp->df_lnum[idx] <= line1) { /* inserted lines somewhere in this diff */ dp->df_count[idx] += inserted; check_unchanged = TRUE; } else /* inserted lines somewhere above this diff */ dp->df_lnum[idx] += inserted; } if (check_unchanged) /* Check if inserted lines are equal, may reduce the * size of the diff. TODO: also check for equal lines * in the middle and perhaps split the block. */ diff_check_unchanged(tp, dp); } } /* check if this block touches the previous one, may merge them. */ if (dprev != NULL && dprev->df_lnum[idx] + dprev->df_count[idx] == dp->df_lnum[idx]) { for (i = 0; i < DB_COUNT; ++i) if (tp->tp_diffbuf[i] != NULL) dprev->df_count[i] += dp->df_count[i]; dprev->df_next = dp->df_next; vim_free(dp); dp = dprev->df_next; } else { /* Advance to next entry. */ dprev = dp; dp = dp->df_next; } } dprev = NULL; dp = tp->tp_first_diff; while (dp != NULL) { /* All counts are zero, remove this entry. */ for (i = 0; i < DB_COUNT; ++i) if (tp->tp_diffbuf[i] != NULL && dp->df_count[i] != 0) break; if (i == DB_COUNT) { dnext = dp->df_next; vim_free(dp); dp = dnext; if (dprev == NULL) tp->tp_first_diff = dnext; else dprev->df_next = dnext; } else { /* Advance to next entry. */ dprev = dp; dp = dp->df_next; } } if (tp == curtab) { diff_redraw(TRUE); /* Need to recompute the scroll binding, may remove or add filler * lines (e.g., when adding lines above w_topline). But it's slow when * making many changes, postpone until redrawing. */ diff_need_scrollbind = TRUE; } } /* * Allocate a new diff block and link it between "dprev" and "dp". */ static diff_T * diff_alloc_new(tp, dprev, dp) tabpage_T *tp; diff_T *dprev; diff_T *dp; { diff_T *dnew; dnew = (diff_T *)alloc((unsigned)sizeof(diff_T)); if (dnew != NULL) { dnew->df_next = dp; if (dprev == NULL) tp->tp_first_diff = dnew; else dprev->df_next = dnew; } return dnew; } /* * Check if the diff block "dp" can be made smaller for lines at the start and * end that are equal. Called after inserting lines. * This may result in a change where all buffers have zero lines, the caller * must take care of removing it. */ static void diff_check_unchanged(tp, dp) tabpage_T *tp; diff_T *dp; { int i_org; int i_new; int off_org, off_new; char_u *line_org; int dir = FORWARD; /* Find the first buffers, use it as the original, compare the other * buffer lines against this one. */ for (i_org = 0; i_org < DB_COUNT; ++i_org) if (tp->tp_diffbuf[i_org] != NULL) break; if (i_org == DB_COUNT) /* safety check */ return; if (diff_check_sanity(tp, dp) == FAIL) return; /* First check lines at the top, then at the bottom. */ off_org = 0; off_new = 0; for (;;) { /* Repeat until a line is found which is different or the number of * lines has become zero. */ while (dp->df_count[i_org] > 0) { /* Copy the line, the next ml_get() will invalidate it. */ if (dir == BACKWARD) off_org = dp->df_count[i_org] - 1; line_org = vim_strsave(ml_get_buf(tp->tp_diffbuf[i_org], dp->df_lnum[i_org] + off_org, FALSE)); if (line_org == NULL) return; for (i_new = i_org + 1; i_new < DB_COUNT; ++i_new) { if (tp->tp_diffbuf[i_new] == NULL) continue; if (dir == BACKWARD) off_new = dp->df_count[i_new] - 1; /* if other buffer doesn't have this line, it was inserted */ if (off_new < 0 || off_new >= dp->df_count[i_new]) break; if (diff_cmp(line_org, ml_get_buf(tp->tp_diffbuf[i_new], dp->df_lnum[i_new] + off_new, FALSE)) != 0) break; } vim_free(line_org); /* Stop when a line isn't equal in all diff buffers. */ if (i_new != DB_COUNT) break; /* Line matched in all buffers, remove it from the diff. */ for (i_new = i_org; i_new < DB_COUNT; ++i_new) if (tp->tp_diffbuf[i_new] != NULL) { if (dir == FORWARD) ++dp->df_lnum[i_new]; --dp->df_count[i_new]; } } if (dir == BACKWARD) break; dir = BACKWARD; } } /* * Check if a diff block doesn't contain invalid line numbers. * This can happen when the diff program returns invalid results. */ static int diff_check_sanity(tp, dp) tabpage_T *tp; diff_T *dp; { int i; for (i = 0; i < DB_COUNT; ++i) if (tp->tp_diffbuf[i] != NULL) if (dp->df_lnum[i] + dp->df_count[i] - 1 > tp->tp_diffbuf[i]->b_ml.ml_line_count) return FAIL; return OK; } /* * Mark all diff buffers in the current tab page for redraw. */ static void diff_redraw(dofold) int dofold; /* also recompute the folds */ { win_T *wp; int n; for (wp = firstwin; wp != NULL; wp = wp->w_next) if (wp->w_p_diff) { redraw_win_later(wp, SOME_VALID); #ifdef FEAT_FOLDING if (dofold && foldmethodIsDiff(wp)) foldUpdateAll(wp); #endif /* A change may have made filler lines invalid, need to take care * of that for other windows. */ if (wp != curwin && wp->w_topfill > 0) { n = diff_check(wp, wp->w_topline); if (wp->w_topfill > n) wp->w_topfill = (n < 0 ? 0 : n); } } } /* * Write buffer "buf" to file "name". * Always use 'fileformat' set to "unix". * Return FAIL for failure */ static int diff_write(buf, fname) buf_T *buf; char_u *fname; { int r; char_u *save_ff; save_ff = buf->b_p_ff; buf->b_p_ff = vim_strsave((char_u *)FF_UNIX); r = buf_write(buf, fname, NULL, (linenr_T)1, buf->b_ml.ml_line_count, NULL, FALSE, FALSE, FALSE, TRUE); free_string_option(buf->b_p_ff); buf->b_p_ff = save_ff; return r; } /* * Completely update the diffs for the buffers involved. * This uses the ordinary "diff" command. * The buffers are written to a file, also for unmodified buffers (the file * could have been produced by autocommands, e.g. the netrw plugin). */ void ex_diffupdate(eap) exarg_T *eap UNUSED; /* can be NULL */ { buf_T *buf; int idx_orig; int idx_new; char_u *tmp_orig; char_u *tmp_new; char_u *tmp_diff; FILE *fd; int ok; int io_error = FALSE; /* Delete all diffblocks. */ diff_clear(curtab); curtab->tp_diff_invalid = FALSE; /* Use the first buffer as the original text. */ for (idx_orig = 0; idx_orig < DB_COUNT; ++idx_orig) if (curtab->tp_diffbuf[idx_orig] != NULL) break; if (idx_orig == DB_COUNT) return; /* Only need to do something when there is another buffer. */ for (idx_new = idx_orig + 1; idx_new < DB_COUNT; ++idx_new) if (curtab->tp_diffbuf[idx_new] != NULL) break; if (idx_new == DB_COUNT) return; /* We need three temp file names. */ tmp_orig = vim_tempname('o'); tmp_new = vim_tempname('n'); tmp_diff = vim_tempname('d'); if (tmp_orig == NULL || tmp_new == NULL || tmp_diff == NULL) goto theend; /* * Do a quick test if "diff" really works. Otherwise it looks like there * are no differences. Can't use the return value, it's non-zero when * there are differences. * May try twice, first with "-a" and then without. */ for (;;) { ok = FALSE; fd = mch_fopen((char *)tmp_orig, "w"); if (fd == NULL) io_error = TRUE; else { if (fwrite("line1\n", (size_t)6, (size_t)1, fd) != 1) io_error = TRUE; fclose(fd); fd = mch_fopen((char *)tmp_new, "w"); if (fd == NULL) io_error = TRUE; else { if (fwrite("line2\n", (size_t)6, (size_t)1, fd) != 1) io_error = TRUE; fclose(fd); diff_file(tmp_orig, tmp_new, tmp_diff); fd = mch_fopen((char *)tmp_diff, "r"); if (fd == NULL) io_error = TRUE; else { char_u linebuf[LBUFLEN]; for (;;) { /* There must be a line that contains "1c1". */ if (tag_fgets(linebuf, LBUFLEN, fd)) break; if (STRNCMP(linebuf, "1c1", 3) == 0) ok = TRUE; } fclose(fd); } mch_remove(tmp_diff); mch_remove(tmp_new); } mch_remove(tmp_orig); } #ifdef FEAT_EVAL /* When using 'diffexpr' break here. */ if (*p_dex != NUL) break; #endif #if defined(MSWIN) || defined(MSDOS) /* If the "-a" argument works, also check if "--binary" works. */ if (ok && diff_a_works == MAYBE && diff_bin_works == MAYBE) { diff_a_works = TRUE; diff_bin_works = TRUE; continue; } if (!ok && diff_a_works == TRUE && diff_bin_works == TRUE) { /* Tried --binary, but it failed. "-a" works though. */ diff_bin_works = FALSE; ok = TRUE; } #endif /* If we checked if "-a" works already, break here. */ if (diff_a_works != MAYBE) break; diff_a_works = ok; /* If "-a" works break here, otherwise retry without "-a". */ if (ok) break; } if (!ok) { if (io_error) EMSG(_("E810: Cannot read or write temp files")); EMSG(_("E97: Cannot create diffs")); diff_a_works = MAYBE; #if defined(MSWIN) || defined(MSDOS) diff_bin_works = MAYBE; #endif goto theend; } /* :diffupdate! */ if (eap != NULL && eap->forceit) for (idx_new = idx_orig; idx_new < DB_COUNT; ++idx_new) { buf = curtab->tp_diffbuf[idx_new]; if (buf_valid(buf)) buf_check_timestamp(buf, FALSE); } /* Write the first buffer to a tempfile. */ buf = curtab->tp_diffbuf[idx_orig]; if (diff_write(buf, tmp_orig) == FAIL) goto theend; /* Make a difference between the first buffer and every other. */ for (idx_new = idx_orig + 1; idx_new < DB_COUNT; ++idx_new) { buf = curtab->tp_diffbuf[idx_new]; if (buf == NULL) continue; if (diff_write(buf, tmp_new) == FAIL) continue; diff_file(tmp_orig, tmp_new, tmp_diff); /* Read the diff output and add each entry to the diff list. */ diff_read(idx_orig, idx_new, tmp_diff); mch_remove(tmp_diff); mch_remove(tmp_new); } mch_remove(tmp_orig); /* force updating cursor position on screen */ curwin->w_valid_cursor.lnum = 0; diff_redraw(TRUE); theend: vim_free(tmp_orig); vim_free(tmp_new); vim_free(tmp_diff); } /* * Make a diff between files "tmp_orig" and "tmp_new", results in "tmp_diff". */ static void diff_file(tmp_orig, tmp_new, tmp_diff) char_u *tmp_orig; char_u *tmp_new; char_u *tmp_diff; { char_u *cmd; size_t len; #ifdef FEAT_EVAL if (*p_dex != NUL) /* Use 'diffexpr' to generate the diff file. */ eval_diff(tmp_orig, tmp_new, tmp_diff); else #endif { len = STRLEN(tmp_orig) + STRLEN(tmp_new) + STRLEN(tmp_diff) + STRLEN(p_srr) + 27; cmd = alloc((unsigned)len); if (cmd != NULL) { /* We don't want $DIFF_OPTIONS to get in the way. */ if (getenv("DIFF_OPTIONS")) vim_setenv((char_u *)"DIFF_OPTIONS", (char_u *)""); /* Build the diff command and execute it. Always use -a, binary * differences are of no use. Ignore errors, diff returns * non-zero when differences have been found. */ vim_snprintf((char *)cmd, len, "diff %s%s%s%s%s %s", diff_a_works == FALSE ? "" : "-a ", #if defined(MSWIN) || defined(MSDOS) diff_bin_works == TRUE ? "--binary " : "", #else "", #endif (diff_flags & DIFF_IWHITE) ? "-b " : "", (diff_flags & DIFF_ICASE) ? "-i " : "", tmp_orig, tmp_new); append_redir(cmd, (int)len, p_srr, tmp_diff); #ifdef FEAT_AUTOCMD block_autocmds(); /* Avoid ShellCmdPost stuff */ #endif (void)call_shell(cmd, SHELL_FILTER|SHELL_SILENT|SHELL_DOOUT); #ifdef FEAT_AUTOCMD unblock_autocmds(); #endif vim_free(cmd); } } } /* * Create a new version of a file from the current buffer and a diff file. * The buffer is written to a file, also for unmodified buffers (the file * could have been produced by autocommands, e.g. the netrw plugin). */ void ex_diffpatch(eap) exarg_T *eap; { char_u *tmp_orig; /* name of original temp file */ char_u *tmp_new; /* name of patched temp file */ char_u *buf = NULL; size_t buflen; win_T *old_curwin = curwin; char_u *newname = NULL; /* name of patched file buffer */ #ifdef UNIX char_u dirbuf[MAXPATHL]; char_u *fullname = NULL; #endif #ifdef FEAT_BROWSE char_u *browseFile = NULL; int browse_flag = cmdmod.browse; #endif struct stat st; #ifdef FEAT_BROWSE if (cmdmod.browse) { browseFile = do_browse(0, (char_u *)_("Patch file"), eap->arg, NULL, NULL, BROWSE_FILTER_ALL_FILES, NULL); if (browseFile == NULL) return; /* operation cancelled */ eap->arg = browseFile; cmdmod.browse = FALSE; /* don't let do_ecmd() browse again */ } #endif /* We need two temp file names. */ tmp_orig = vim_tempname('o'); tmp_new = vim_tempname('n'); if (tmp_orig == NULL || tmp_new == NULL) goto theend; /* Write the current buffer to "tmp_orig". */ if (buf_write(curbuf, tmp_orig, NULL, (linenr_T)1, curbuf->b_ml.ml_line_count, NULL, FALSE, FALSE, FALSE, TRUE) == FAIL) goto theend; #ifdef UNIX /* Get the absolute path of the patchfile, changing directory below. */ fullname = FullName_save(eap->arg, FALSE); #endif buflen = STRLEN(tmp_orig) + ( # ifdef UNIX fullname != NULL ? STRLEN(fullname) : # endif STRLEN(eap->arg)) + STRLEN(tmp_new) + 16; buf = alloc((unsigned)buflen); if (buf == NULL) goto theend; #ifdef UNIX /* Temporarily chdir to /tmp, to avoid patching files in the current * directory when the patch file contains more than one patch. When we * have our own temp dir use that instead, it will be cleaned up when we * exit (any .rej files created). Don't change directory if we can't * return to the current. */ if (mch_dirname(dirbuf, MAXPATHL) != OK || mch_chdir((char *)dirbuf) != 0) dirbuf[0] = NUL; else { # ifdef TEMPDIRNAMES if (vim_tempdir != NULL) ignored = mch_chdir((char *)vim_tempdir); else # endif ignored = mch_chdir("/tmp"); shorten_fnames(TRUE); } #endif #ifdef FEAT_EVAL if (*p_pex != NUL) /* Use 'patchexpr' to generate the new file. */ eval_patch(tmp_orig, # ifdef UNIX fullname != NULL ? fullname : # endif eap->arg, tmp_new); else #endif { /* Build the patch command and execute it. Ignore errors. Switch to * cooked mode to allow the user to respond to prompts. */ vim_snprintf((char *)buf, buflen, "patch -o %s %s < \"%s\"", tmp_new, tmp_orig, # ifdef UNIX fullname != NULL ? fullname : # endif eap->arg); #ifdef FEAT_AUTOCMD block_autocmds(); /* Avoid ShellCmdPost stuff */ #endif (void)call_shell(buf, SHELL_FILTER | SHELL_COOKED); #ifdef FEAT_AUTOCMD unblock_autocmds(); #endif } #ifdef UNIX if (dirbuf[0] != NUL) { if (mch_chdir((char *)dirbuf) != 0) EMSG(_(e_prev_dir)); shorten_fnames(TRUE); } #endif /* patch probably has written over the screen */ redraw_later(CLEAR); /* Delete any .orig or .rej file created. */ STRCPY(buf, tmp_new); STRCAT(buf, ".orig"); mch_remove(buf); STRCPY(buf, tmp_new); STRCAT(buf, ".rej"); mch_remove(buf); /* Only continue if the output file was created. */ if (mch_stat((char *)tmp_new, &st) < 0 || st.st_size == 0) EMSG(_("E816: Cannot read patch output")); else { if (curbuf->b_fname != NULL) { newname = vim_strnsave(curbuf->b_fname, (int)(STRLEN(curbuf->b_fname) + 4)); if (newname != NULL) STRCAT(newname, ".new"); } #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif /* don't use a new tab page, each tab page has its own diffs */ cmdmod.tab = 0; if (win_split(0, (diff_flags & DIFF_VERTICAL) ? WSP_VERT : 0) != FAIL) { /* Pretend it was a ":split fname" command */ eap->cmdidx = CMD_split; eap->arg = tmp_new; do_exedit(eap, old_curwin); /* check that split worked and editing tmp_new */ if (curwin != old_curwin && win_valid(old_curwin)) { /* Set 'diff', 'scrollbind' on and 'wrap' off. */ diff_win_options(curwin, TRUE); diff_win_options(old_curwin, TRUE); if (newname != NULL) { /* do a ":file filename.new" on the patched buffer */ eap->arg = newname; ex_file(eap); #ifdef FEAT_AUTOCMD /* Do filetype detection with the new name. */ if (au_has_group((char_u *)"filetypedetect")) do_cmdline_cmd((char_u *)":doau filetypedetect BufRead"); #endif } } } } theend: if (tmp_orig != NULL) mch_remove(tmp_orig); vim_free(tmp_orig); if (tmp_new != NULL) mch_remove(tmp_new); vim_free(tmp_new); vim_free(newname); vim_free(buf); #ifdef UNIX vim_free(fullname); #endif #ifdef FEAT_BROWSE vim_free(browseFile); cmdmod.browse = browse_flag; #endif } /* * Split the window and edit another file, setting options to show the diffs. */ void ex_diffsplit(eap) exarg_T *eap; { win_T *old_curwin = curwin; #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif /* don't use a new tab page, each tab page has its own diffs */ cmdmod.tab = 0; if (win_split(0, (diff_flags & DIFF_VERTICAL) ? WSP_VERT : 0) != FAIL) { /* Pretend it was a ":split fname" command */ eap->cmdidx = CMD_split; curwin->w_p_diff = TRUE; do_exedit(eap, old_curwin); if (curwin != old_curwin) /* split must have worked */ { /* Set 'diff', 'scrollbind' on and 'wrap' off. */ diff_win_options(curwin, TRUE); diff_win_options(old_curwin, TRUE); } } } /* * Set options to show difs for the current window. */ void ex_diffthis(eap) exarg_T *eap UNUSED; { /* Set 'diff', 'scrollbind' on and 'wrap' off. */ diff_win_options(curwin, TRUE); } /* * Set options in window "wp" for diff mode. */ void diff_win_options(wp, addbuf) win_T *wp; int addbuf; /* Add buffer to diff. */ { # ifdef FEAT_FOLDING win_T *old_curwin = curwin; /* close the manually opened folds */ curwin = wp; newFoldLevel(); curwin = old_curwin; # endif wp->w_p_diff = TRUE; /* Use 'scrollbind' and 'cursorbind' when available */ #ifdef FEAT_SCROLLBIND wp->w_p_scb = TRUE; #endif #ifdef FEAT_CURSORBIND wp->w_p_crb = TRUE; #endif wp->w_p_wrap = FALSE; # ifdef FEAT_FOLDING curwin = wp; curbuf = curwin->w_buffer; set_string_option_direct((char_u *)"fdm", -1, (char_u *)"diff", OPT_LOCAL|OPT_FREE, 0); curwin = old_curwin; curbuf = curwin->w_buffer; wp->w_p_fdc = diff_foldcolumn; wp->w_p_fen = TRUE; wp->w_p_fdl = 0; foldUpdateAll(wp); /* make sure topline is not halfway a fold */ changed_window_setting_win(wp); # endif #ifdef FEAT_SCROLLBIND if (vim_strchr(p_sbo, 'h') == NULL) do_cmdline_cmd((char_u *)"set sbo+=hor"); #endif if (addbuf) diff_buf_add(wp->w_buffer); redraw_win_later(wp, NOT_VALID); } /* * Set options not to show diffs. For the current window or all windows. * Only in the current tab page. */ void ex_diffoff(eap) exarg_T *eap; { win_T *wp; win_T *old_curwin = curwin; #ifdef FEAT_SCROLLBIND int diffwin = FALSE; #endif for (wp = firstwin; wp != NULL; wp = wp->w_next) { if (wp == curwin || (eap->forceit && wp->w_p_diff)) { /* Set 'diff', 'scrollbind' off and 'wrap' on. */ wp->w_p_diff = FALSE; RESET_BINDING(wp); wp->w_p_wrap = TRUE; #ifdef FEAT_FOLDING curwin = wp; curbuf = curwin->w_buffer; set_string_option_direct((char_u *)"fdm", -1, (char_u *)"manual", OPT_LOCAL|OPT_FREE, 0); curwin = old_curwin; curbuf = curwin->w_buffer; wp->w_p_fdc = 0; wp->w_p_fen = FALSE; wp->w_p_fdl = 0; foldUpdateAll(wp); /* make sure topline is not halfway a fold */ changed_window_setting_win(wp); #endif diff_buf_adjust(wp); } #ifdef FEAT_SCROLLBIND diffwin |= wp->w_p_diff; #endif } #ifdef FEAT_SCROLLBIND /* Remove "hor" from from 'scrollopt' if there are no diff windows left. */ if (!diffwin && vim_strchr(p_sbo, 'h') != NULL) do_cmdline_cmd((char_u *)"set sbo-=hor"); #endif } /* * Read the diff output and add each entry to the diff list. */ static void diff_read(idx_orig, idx_new, fname) int idx_orig; /* idx of original file */ int idx_new; /* idx of new file */ char_u *fname; /* name of diff output file */ { FILE *fd; diff_T *dprev = NULL; diff_T *dp = curtab->tp_first_diff; diff_T *dn, *dpl; long f1, l1, f2, l2; char_u linebuf[LBUFLEN]; /* only need to hold the diff line */ int difftype; char_u *p; long off; int i; linenr_T lnum_orig, lnum_new; long count_orig, count_new; int notset = TRUE; /* block "*dp" not set yet */ fd = mch_fopen((char *)fname, "r"); if (fd == NULL) { EMSG(_("E98: Cannot read diff output")); return; } for (;;) { if (tag_fgets(linebuf, LBUFLEN, fd)) break; /* end of file */ if (!isdigit(*linebuf)) continue; /* not the start of a diff block */ /* This line must be one of three formats: * {first}[,{last}]c{first}[,{last}] * {first}a{first}[,{last}] * {first}[,{last}]d{first} */ p = linebuf; f1 = getdigits(&p); if (*p == ',') { ++p; l1 = getdigits(&p); } else l1 = f1; if (*p != 'a' && *p != 'c' && *p != 'd') continue; /* invalid diff format */ difftype = *p++; f2 = getdigits(&p); if (*p == ',') { ++p; l2 = getdigits(&p); } else l2 = f2; if (l1 < f1 || l2 < f2) continue; /* invalid line range */ if (difftype == 'a') { lnum_orig = f1 + 1; count_orig = 0; } else { lnum_orig = f1; count_orig = l1 - f1 + 1; } if (difftype == 'd') { lnum_new = f2 + 1; count_new = 0; } else { lnum_new = f2; count_new = l2 - f2 + 1; } /* Go over blocks before the change, for which orig and new are equal. * Copy blocks from orig to new. */ while (dp != NULL && lnum_orig > dp->df_lnum[idx_orig] + dp->df_count[idx_orig]) { if (notset) diff_copy_entry(dprev, dp, idx_orig, idx_new); dprev = dp; dp = dp->df_next; notset = TRUE; } if (dp != NULL && lnum_orig <= dp->df_lnum[idx_orig] + dp->df_count[idx_orig] && lnum_orig + count_orig >= dp->df_lnum[idx_orig]) { /* New block overlaps with existing block(s). * First find last block that overlaps. */ for (dpl = dp; dpl->df_next != NULL; dpl = dpl->df_next) if (lnum_orig + count_orig < dpl->df_next->df_lnum[idx_orig]) break; /* If the newly found block starts before the old one, set the * start back a number of lines. */ off = dp->df_lnum[idx_orig] - lnum_orig; if (off > 0) { for (i = idx_orig; i < idx_new; ++i) if (curtab->tp_diffbuf[i] != NULL) dp->df_lnum[i] -= off; dp->df_lnum[idx_new] = lnum_new; dp->df_count[idx_new] = count_new; } else if (notset) { /* new block inside existing one, adjust new block */ dp->df_lnum[idx_new] = lnum_new + off; dp->df_count[idx_new] = count_new - off; } else /* second overlap of new block with existing block */ dp->df_count[idx_new] += count_new - count_orig + dpl->df_lnum[idx_orig] + dpl->df_count[idx_orig] - (dp->df_lnum[idx_orig] + dp->df_count[idx_orig]); /* Adjust the size of the block to include all the lines to the * end of the existing block or the new diff, whatever ends last. */ off = (lnum_orig + count_orig) - (dpl->df_lnum[idx_orig] + dpl->df_count[idx_orig]); if (off < 0) { /* new change ends in existing block, adjust the end if not * done already */ if (notset) dp->df_count[idx_new] += -off; off = 0; } for (i = idx_orig; i < idx_new; ++i) if (curtab->tp_diffbuf[i] != NULL) dp->df_count[i] = dpl->df_lnum[i] + dpl->df_count[i] - dp->df_lnum[i] + off; /* Delete the diff blocks that have been merged into one. */ dn = dp->df_next; dp->df_next = dpl->df_next; while (dn != dp->df_next) { dpl = dn->df_next; vim_free(dn); dn = dpl; } } else { /* Allocate a new diffblock. */ dp = diff_alloc_new(curtab, dprev, dp); if (dp == NULL) goto done; dp->df_lnum[idx_orig] = lnum_orig; dp->df_count[idx_orig] = count_orig; dp->df_lnum[idx_new] = lnum_new; dp->df_count[idx_new] = count_new; /* Set values for other buffers, these must be equal to the * original buffer, otherwise there would have been a change * already. */ for (i = idx_orig + 1; i < idx_new; ++i) if (curtab->tp_diffbuf[i] != NULL) diff_copy_entry(dprev, dp, idx_orig, i); } notset = FALSE; /* "*dp" has been set */ } /* for remaining diff blocks orig and new are equal */ while (dp != NULL) { if (notset) diff_copy_entry(dprev, dp, idx_orig, idx_new); dprev = dp; dp = dp->df_next; notset = TRUE; } done: fclose(fd); } /* * Copy an entry at "dp" from "idx_orig" to "idx_new". */ static void diff_copy_entry(dprev, dp, idx_orig, idx_new) diff_T *dprev; diff_T *dp; int idx_orig; int idx_new; { long off; if (dprev == NULL) off = 0; else off = (dprev->df_lnum[idx_orig] + dprev->df_count[idx_orig]) - (dprev->df_lnum[idx_new] + dprev->df_count[idx_new]); dp->df_lnum[idx_new] = dp->df_lnum[idx_orig] - off; dp->df_count[idx_new] = dp->df_count[idx_orig]; } /* * Clear the list of diffblocks for tab page "tp". */ void diff_clear(tp) tabpage_T *tp; { diff_T *p, *next_p; for (p = tp->tp_first_diff; p != NULL; p = next_p) { next_p = p->df_next; vim_free(p); } tp->tp_first_diff = NULL; } /* * Check diff status for line "lnum" in buffer "buf": * Returns 0 for nothing special * Returns -1 for a line that should be highlighted as changed. * Returns -2 for a line that should be highlighted as added/deleted. * Returns > 0 for inserting that many filler lines above it (never happens * when 'diffopt' doesn't contain "filler"). * This should only be used for windows where 'diff' is set. */ int diff_check(wp, lnum) win_T *wp; linenr_T lnum; { int idx; /* index in tp_diffbuf[] for this buffer */ diff_T *dp; int maxcount; int i; buf_T *buf = wp->w_buffer; int cmp; if (curtab->tp_diff_invalid) ex_diffupdate(NULL); /* update after a big change */ if (curtab->tp_first_diff == NULL || !wp->w_p_diff) /* no diffs at all */ return 0; /* safety check: "lnum" must be a buffer line */ if (lnum < 1 || lnum > buf->b_ml.ml_line_count + 1) return 0; idx = diff_buf_idx(buf); if (idx == DB_COUNT) return 0; /* no diffs for buffer "buf" */ #ifdef FEAT_FOLDING /* A closed fold never has filler lines. */ if (hasFoldingWin(wp, lnum, NULL, NULL, TRUE, NULL)) return 0; #endif /* search for a change that includes "lnum" in the list of diffblocks. */ for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next) if (lnum <= dp->df_lnum[idx] + dp->df_count[idx]) break; if (dp == NULL || lnum < dp->df_lnum[idx]) return 0; if (lnum < dp->df_lnum[idx] + dp->df_count[idx]) { int zero = FALSE; /* Changed or inserted line. If the other buffers have a count of * zero, the lines were inserted. If the other buffers have the same * count, check if the lines are identical. */ cmp = FALSE; for (i = 0; i < DB_COUNT; ++i) if (i != idx && curtab->tp_diffbuf[i] != NULL) { if (dp->df_count[i] == 0) zero = TRUE; else { if (dp->df_count[i] != dp->df_count[idx]) return -1; /* nr of lines changed. */ cmp = TRUE; } } if (cmp) { /* Compare all lines. If they are equal the lines were inserted * in some buffers, deleted in others, but not changed. */ for (i = 0; i < DB_COUNT; ++i) if (i != idx && curtab->tp_diffbuf[i] != NULL && dp->df_count[i] != 0) if (!diff_equal_entry(dp, idx, i)) return -1; } /* If there is no buffer with zero lines then there is no difference * any longer. Happens when making a change (or undo) that removes * the difference. Can't remove the entry here, we might be halfway * updating the window. Just report the text as unchanged. Other * windows might still show the change though. */ if (zero == FALSE) return 0; return -2; } /* If 'diffopt' doesn't contain "filler", return 0. */ if (!(diff_flags & DIFF_FILLER)) return 0; /* Insert filler lines above the line just below the change. Will return * 0 when this buf had the max count. */ maxcount = 0; for (i = 0; i < DB_COUNT; ++i) if (curtab->tp_diffbuf[i] != NULL && dp->df_count[i] > maxcount) maxcount = dp->df_count[i]; return maxcount - dp->df_count[idx]; } /* * Compare two entries in diff "*dp" and return TRUE if they are equal. */ static int diff_equal_entry(dp, idx1, idx2) diff_T *dp; int idx1; int idx2; { int i; char_u *line; int cmp; if (dp->df_count[idx1] != dp->df_count[idx2]) return FALSE; if (diff_check_sanity(curtab, dp) == FAIL) return FALSE; for (i = 0; i < dp->df_count[idx1]; ++i) { line = vim_strsave(ml_get_buf(curtab->tp_diffbuf[idx1], dp->df_lnum[idx1] + i, FALSE)); if (line == NULL) return FALSE; cmp = diff_cmp(line, ml_get_buf(curtab->tp_diffbuf[idx2], dp->df_lnum[idx2] + i, FALSE)); vim_free(line); if (cmp != 0) return FALSE; } return TRUE; } /* * Compare strings "s1" and "s2" according to 'diffopt'. * Return non-zero when they are different. */ static int diff_cmp(s1, s2) char_u *s1; char_u *s2; { char_u *p1, *p2; #ifdef FEAT_MBYTE int l; #endif if ((diff_flags & (DIFF_ICASE | DIFF_IWHITE)) == 0) return STRCMP(s1, s2); if ((diff_flags & DIFF_ICASE) && !(diff_flags & DIFF_IWHITE)) return MB_STRICMP(s1, s2); /* Ignore white space changes and possibly ignore case. */ p1 = s1; p2 = s2; while (*p1 != NUL && *p2 != NUL) { if (vim_iswhite(*p1) && vim_iswhite(*p2)) { p1 = skipwhite(p1); p2 = skipwhite(p2); } else { #ifdef FEAT_MBYTE l = (*mb_ptr2len)(p1); if (l != (*mb_ptr2len)(p2)) break; if (l > 1) { if (STRNCMP(p1, p2, l) != 0 && (!enc_utf8 || !(diff_flags & DIFF_ICASE) || utf_fold(utf_ptr2char(p1)) != utf_fold(utf_ptr2char(p2)))) break; p1 += l; p2 += l; } else #endif { if (*p1 != *p2 && (!(diff_flags & DIFF_ICASE) || TOLOWER_LOC(*p1) != TOLOWER_LOC(*p2))) break; ++p1; ++p2; } } } /* Ignore trailing white space. */ p1 = skipwhite(p1); p2 = skipwhite(p2); if (*p1 != NUL || *p2 != NUL) return 1; return 0; } /* * Return the number of filler lines above "lnum". */ int diff_check_fill(wp, lnum) win_T *wp; linenr_T lnum; { int n; /* be quick when there are no filler lines */ if (!(diff_flags & DIFF_FILLER)) return 0; n = diff_check(wp, lnum); if (n <= 0) return 0; return n; } /* * Set the topline of "towin" to match the position in "fromwin", so that they * show the same diff'ed lines. */ void diff_set_topline(fromwin, towin) win_T *fromwin; win_T *towin; { buf_T *frombuf = fromwin->w_buffer; linenr_T lnum = fromwin->w_topline; int fromidx; int toidx; diff_T *dp; int max_count; int i; fromidx = diff_buf_idx(frombuf); if (fromidx == DB_COUNT) return; /* safety check */ if (curtab->tp_diff_invalid) ex_diffupdate(NULL); /* update after a big change */ towin->w_topfill = 0; /* search for a change that includes "lnum" in the list of diffblocks. */ for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next) if (lnum <= dp->df_lnum[fromidx] + dp->df_count[fromidx]) break; if (dp == NULL) { /* After last change, compute topline relative to end of file; no * filler lines. */ towin->w_topline = towin->w_buffer->b_ml.ml_line_count - (frombuf->b_ml.ml_line_count - lnum); } else { /* Find index for "towin". */ toidx = diff_buf_idx(towin->w_buffer); if (toidx == DB_COUNT) return; /* safety check */ towin->w_topline = lnum + (dp->df_lnum[toidx] - dp->df_lnum[fromidx]); if (lnum >= dp->df_lnum[fromidx]) { /* Inside a change: compute filler lines. With three or more * buffers we need to know the largest count. */ max_count = 0; for (i = 0; i < DB_COUNT; ++i) if (curtab->tp_diffbuf[i] != NULL && max_count < dp->df_count[i]) max_count = dp->df_count[i]; if (dp->df_count[toidx] == dp->df_count[fromidx]) { /* same number of lines: use same filler count */ towin->w_topfill = fromwin->w_topfill; } else if (dp->df_count[toidx] > dp->df_count[fromidx]) { if (lnum == dp->df_lnum[fromidx] + dp->df_count[fromidx]) { /* more lines in towin and fromwin doesn't show diff * lines, only filler lines */ if (max_count - fromwin->w_topfill >= dp->df_count[toidx]) { /* towin also only shows filler lines */ towin->w_topline = dp->df_lnum[toidx] + dp->df_count[toidx]; towin->w_topfill = fromwin->w_topfill; } else /* towin still has some diff lines to show */ towin->w_topline = dp->df_lnum[toidx] + max_count - fromwin->w_topfill; } } else if (towin->w_topline >= dp->df_lnum[toidx] + dp->df_count[toidx]) { /* less lines in towin and no diff lines to show: compute * filler lines */ towin->w_topline = dp->df_lnum[toidx] + dp->df_count[toidx]; if (diff_flags & DIFF_FILLER) { if (lnum == dp->df_lnum[fromidx] + dp->df_count[fromidx]) /* fromwin is also out of diff lines */ towin->w_topfill = fromwin->w_topfill; else /* fromwin has some diff lines */ towin->w_topfill = dp->df_lnum[fromidx] + max_count - lnum; } } } } /* safety check (if diff info gets outdated strange things may happen) */ towin->w_botfill = FALSE; if (towin->w_topline > towin->w_buffer->b_ml.ml_line_count) { towin->w_topline = towin->w_buffer->b_ml.ml_line_count; towin->w_botfill = TRUE; } if (towin->w_topline < 1) { towin->w_topline = 1; towin->w_topfill = 0; } /* When w_topline changes need to recompute w_botline and cursor position */ invalidate_botline_win(towin); changed_line_abv_curs_win(towin); check_topfill(towin, FALSE); #ifdef FEAT_FOLDING (void)hasFoldingWin(towin, towin->w_topline, &towin->w_topline, NULL, TRUE, NULL); #endif } /* * This is called when 'diffopt' is changed. */ int diffopt_changed() { char_u *p; int diff_context_new = 6; int diff_flags_new = 0; int diff_foldcolumn_new = 2; tabpage_T *tp; p = p_dip; while (*p != NUL) { if (STRNCMP(p, "filler", 6) == 0) { p += 6; diff_flags_new |= DIFF_FILLER; } else if (STRNCMP(p, "context:", 8) == 0 && VIM_ISDIGIT(p[8])) { p += 8; diff_context_new = getdigits(&p); } else if (STRNCMP(p, "icase", 5) == 0) { p += 5; diff_flags_new |= DIFF_ICASE; } else if (STRNCMP(p, "iwhite", 6) == 0) { p += 6; diff_flags_new |= DIFF_IWHITE; } else if (STRNCMP(p, "horizontal", 10) == 0) { p += 10; diff_flags_new |= DIFF_HORIZONTAL; } else if (STRNCMP(p, "vertical", 8) == 0) { p += 8; diff_flags_new |= DIFF_VERTICAL; } else if (STRNCMP(p, "foldcolumn:", 11) == 0 && VIM_ISDIGIT(p[11])) { p += 11; diff_foldcolumn_new = getdigits(&p); } if (*p != ',' && *p != NUL) return FAIL; if (*p == ',') ++p; } /* Can't have both "horizontal" and "vertical". */ if ((diff_flags_new & DIFF_HORIZONTAL) && (diff_flags_new & DIFF_VERTICAL)) return FAIL; /* If "icase" or "iwhite" was added or removed, need to update the diff. */ if (diff_flags != diff_flags_new) for (tp = first_tabpage; tp != NULL; tp = tp->tp_next) tp->tp_diff_invalid = TRUE; diff_flags = diff_flags_new; diff_context = diff_context_new; diff_foldcolumn = diff_foldcolumn_new; diff_redraw(TRUE); /* recompute the scroll binding with the new option value, may * remove or add filler lines */ check_scrollbind((linenr_T)0, 0L); return OK; } /* * Return TRUE if 'diffopt' contains "horizontal". */ int diffopt_horizontal() { return (diff_flags & DIFF_HORIZONTAL) != 0; } /* * Find the difference within a changed line. * Returns TRUE if the line was added, no other buffer has it. */ int diff_find_change(wp, lnum, startp, endp) win_T *wp; linenr_T lnum; int *startp; /* first char of the change */ int *endp; /* last char of the change */ { char_u *line_org; char_u *line_new; int i; int si_org, si_new; int ei_org, ei_new; diff_T *dp; int idx; int off; int added = TRUE; /* Make a copy of the line, the next ml_get() will invalidate it. */ line_org = vim_strsave(ml_get_buf(wp->w_buffer, lnum, FALSE)); if (line_org == NULL) return FALSE; idx = diff_buf_idx(wp->w_buffer); if (idx == DB_COUNT) /* cannot happen */ { vim_free(line_org); return FALSE; } /* search for a change that includes "lnum" in the list of diffblocks. */ for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next) if (lnum <= dp->df_lnum[idx] + dp->df_count[idx]) break; if (dp == NULL || diff_check_sanity(curtab, dp) == FAIL) { vim_free(line_org); return FALSE; } off = lnum - dp->df_lnum[idx]; for (i = 0; i < DB_COUNT; ++i) if (curtab->tp_diffbuf[i] != NULL && i != idx) { /* Skip lines that are not in the other change (filler lines). */ if (off >= dp->df_count[i]) continue; added = FALSE; line_new = ml_get_buf(curtab->tp_diffbuf[i], dp->df_lnum[i] + off, FALSE); /* Search for start of difference */ si_org = si_new = 0; while (line_org[si_org] != NUL) { if ((diff_flags & DIFF_IWHITE) && vim_iswhite(line_org[si_org]) && vim_iswhite(line_new[si_new])) { si_org = (int)(skipwhite(line_org + si_org) - line_org); si_new = (int)(skipwhite(line_new + si_new) - line_new); } else { if (line_org[si_org] != line_new[si_new]) break; ++si_org; ++si_new; } } #ifdef FEAT_MBYTE if (has_mbyte) { /* Move back to first byte of character in both lines (may * have "nn^" in line_org and "n^ in line_new). */ si_org -= (*mb_head_off)(line_org, line_org + si_org); si_new -= (*mb_head_off)(line_new, line_new + si_new); } #endif if (*startp > si_org) *startp = si_org; /* Search for end of difference, if any. */ if (line_org[si_org] != NUL || line_new[si_new] != NUL) { ei_org = (int)STRLEN(line_org); ei_new = (int)STRLEN(line_new); while (ei_org >= *startp && ei_new >= si_new && ei_org >= 0 && ei_new >= 0) { if ((diff_flags & DIFF_IWHITE) && vim_iswhite(line_org[ei_org]) && vim_iswhite(line_new[ei_new])) { while (ei_org >= *startp && vim_iswhite(line_org[ei_org])) --ei_org; while (ei_new >= si_new && vim_iswhite(line_new[ei_new])) --ei_new; } else { if (line_org[ei_org] != line_new[ei_new]) break; --ei_org; --ei_new; } } if (*endp < ei_org) *endp = ei_org; } } vim_free(line_org); return added; } #if defined(FEAT_FOLDING) || defined(PROTO) /* * Return TRUE if line "lnum" is not close to a diff block, this line should * be in a fold. * Return FALSE if there are no diff blocks at all in this window. */ int diff_infold(wp, lnum) win_T *wp; linenr_T lnum; { int i; int idx = -1; int other = FALSE; diff_T *dp; /* Return if 'diff' isn't set. */ if (!wp->w_p_diff) return FALSE; for (i = 0; i < DB_COUNT; ++i) { if (curtab->tp_diffbuf[i] == wp->w_buffer) idx = i; else if (curtab->tp_diffbuf[i] != NULL) other = TRUE; } /* return here if there are no diffs in the window */ if (idx == -1 || !other) return FALSE; if (curtab->tp_diff_invalid) ex_diffupdate(NULL); /* update after a big change */ /* Return if there are no diff blocks. All lines will be folded. */ if (curtab->tp_first_diff == NULL) return TRUE; for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next) { /* If this change is below the line there can't be any further match. */ if (dp->df_lnum[idx] - diff_context > lnum) break; /* If this change ends before the line we have a match. */ if (dp->df_lnum[idx] + dp->df_count[idx] + diff_context > lnum) return FALSE; } return TRUE; } #endif /* * "dp" and "do" commands. */ void nv_diffgetput(put) int put; { exarg_T ea; ea.arg = (char_u *)""; if (put) ea.cmdidx = CMD_diffput; else ea.cmdidx = CMD_diffget; ea.addr_count = 0; ea.line1 = curwin->w_cursor.lnum; ea.line2 = curwin->w_cursor.lnum; ex_diffgetput(&ea); } /* * ":diffget" * ":diffput" */ void ex_diffgetput(eap) exarg_T *eap; { linenr_T lnum; int count; linenr_T off = 0; diff_T *dp; diff_T *dprev; diff_T *dfree; int idx_cur; int idx_other; int idx_from; int idx_to; int i; int added; char_u *p; aco_save_T aco; buf_T *buf; int start_skip, end_skip; int new_count; int buf_empty; int found_not_ma = FALSE; /* Find the current buffer in the list of diff buffers. */ idx_cur = diff_buf_idx(curbuf); if (idx_cur == DB_COUNT) { EMSG(_("E99: Current buffer is not in diff mode")); return; } if (*eap->arg == NUL) { /* No argument: Find the other buffer in the list of diff buffers. */ for (idx_other = 0; idx_other < DB_COUNT; ++idx_other) if (curtab->tp_diffbuf[idx_other] != curbuf && curtab->tp_diffbuf[idx_other] != NULL) { if (eap->cmdidx != CMD_diffput || curtab->tp_diffbuf[idx_other]->b_p_ma) break; found_not_ma = TRUE; } if (idx_other == DB_COUNT) { if (found_not_ma) EMSG(_("E793: No other buffer in diff mode is modifiable")); else EMSG(_("E100: No other buffer in diff mode")); return; } /* Check that there isn't a third buffer in the list */ for (i = idx_other + 1; i < DB_COUNT; ++i) if (curtab->tp_diffbuf[i] != curbuf && curtab->tp_diffbuf[i] != NULL && (eap->cmdidx != CMD_diffput || curtab->tp_diffbuf[i]->b_p_ma)) { EMSG(_("E101: More than two buffers in diff mode, don't know which one to use")); return; } } else { /* Buffer number or pattern given. Ignore trailing white space. */ p = eap->arg + STRLEN(eap->arg); while (p > eap->arg && vim_iswhite(p[-1])) --p; for (i = 0; vim_isdigit(eap->arg[i]) && eap->arg + i < p; ++i) ; if (eap->arg + i == p) /* digits only */ i = atol((char *)eap->arg); else { i = buflist_findpat(eap->arg, p, FALSE, TRUE); if (i < 0) return; /* error message already given */ } buf = buflist_findnr(i); if (buf == NULL) { EMSG2(_("E102: Can't find buffer \"%s\""), eap->arg); return; } if (buf == curbuf) return; /* nothing to do */ idx_other = diff_buf_idx(buf); if (idx_other == DB_COUNT) { EMSG2(_("E103: Buffer \"%s\" is not in diff mode"), eap->arg); return; } } diff_busy = TRUE; /* When no range given include the line above or below the cursor. */ if (eap->addr_count == 0) { /* Make it possible that ":diffget" on the last line gets line below * the cursor line when there is no difference above the cursor. */ if (eap->cmdidx == CMD_diffget && eap->line1 == curbuf->b_ml.ml_line_count && diff_check(curwin, eap->line1) == 0 && (eap->line1 == 1 || diff_check(curwin, eap->line1 - 1) == 0)) ++eap->line2; else if (eap->line1 > 0) --eap->line1; } if (eap->cmdidx == CMD_diffget) { idx_from = idx_other; idx_to = idx_cur; } else { idx_from = idx_cur; idx_to = idx_other; /* Need to make the other buffer the current buffer to be able to make * changes in it. */ /* set curwin/curbuf to buf and save a few things */ aucmd_prepbuf(&aco, curtab->tp_diffbuf[idx_other]); } /* May give the warning for a changed buffer here, which can trigger the * FileChangedRO autocommand, which may do nasty things and mess * everything up. */ if (!curbuf->b_changed) { change_warning(0); if (diff_buf_idx(curbuf) != idx_to) { EMSG(_("E787: Buffer changed unexpectedly")); return; } } dprev = NULL; for (dp = curtab->tp_first_diff; dp != NULL; ) { if (dp->df_lnum[idx_cur] > eap->line2 + off) break; /* past the range that was specified */ dfree = NULL; lnum = dp->df_lnum[idx_to]; count = dp->df_count[idx_to]; if (dp->df_lnum[idx_cur] + dp->df_count[idx_cur] > eap->line1 + off && u_save(lnum - 1, lnum + count) != FAIL) { /* Inside the specified range and saving for undo worked. */ start_skip = 0; end_skip = 0; if (eap->addr_count > 0) { /* A range was specified: check if lines need to be skipped. */ start_skip = eap->line1 + off - dp->df_lnum[idx_cur]; if (start_skip > 0) { /* range starts below start of current diff block */ if (start_skip > count) { lnum += count; count = 0; } else { count -= start_skip; lnum += start_skip; } } else start_skip = 0; end_skip = dp->df_lnum[idx_cur] + dp->df_count[idx_cur] - 1 - (eap->line2 + off); if (end_skip > 0) { /* range ends above end of current/from diff block */ if (idx_cur == idx_from) /* :diffput */ { i = dp->df_count[idx_cur] - start_skip - end_skip; if (count > i) count = i; } else /* :diffget */ { count -= end_skip; end_skip = dp->df_count[idx_from] - start_skip - count; if (end_skip < 0) end_skip = 0; } } else end_skip = 0; } buf_empty = FALSE; added = 0; for (i = 0; i < count; ++i) { /* remember deleting the last line of the buffer */ buf_empty = curbuf->b_ml.ml_line_count == 1; ml_delete(lnum, FALSE); --added; } for (i = 0; i < dp->df_count[idx_from] - start_skip - end_skip; ++i) { linenr_T nr; nr = dp->df_lnum[idx_from] + start_skip + i; if (nr > curtab->tp_diffbuf[idx_from]->b_ml.ml_line_count) break; p = vim_strsave(ml_get_buf(curtab->tp_diffbuf[idx_from], nr, FALSE)); if (p != NULL) { ml_append(lnum + i - 1, p, 0, FALSE); vim_free(p); ++added; if (buf_empty && curbuf->b_ml.ml_line_count == 2) { /* Added the first line into an empty buffer, need to * delete the dummy empty line. */ buf_empty = FALSE; ml_delete((linenr_T)2, FALSE); } } } new_count = dp->df_count[idx_to] + added; dp->df_count[idx_to] = new_count; if (start_skip == 0 && end_skip == 0) { /* Check if there are any other buffers and if the diff is * equal in them. */ for (i = 0; i < DB_COUNT; ++i) if (curtab->tp_diffbuf[i] != NULL && i != idx_from && i != idx_to && !diff_equal_entry(dp, idx_from, i)) break; if (i == DB_COUNT) { /* delete the diff entry, the buffers are now equal here */ dfree = dp; dp = dp->df_next; if (dprev == NULL) curtab->tp_first_diff = dp; else dprev->df_next = dp; } } /* Adjust marks. This will change the following entries! */ if (added != 0) { mark_adjust(lnum, lnum + count - 1, (long)MAXLNUM, (long)added); if (curwin->w_cursor.lnum >= lnum) { /* Adjust the cursor position if it's in/after the changed * lines. */ if (curwin->w_cursor.lnum >= lnum + count) curwin->w_cursor.lnum += added; else if (added < 0) curwin->w_cursor.lnum = lnum; } } changed_lines(lnum, 0, lnum + count, (long)added); if (dfree != NULL) { /* Diff is deleted, update folds in other windows. */ #ifdef FEAT_FOLDING diff_fold_update(dfree, idx_to); #endif vim_free(dfree); } else /* mark_adjust() may have changed the count in a wrong way */ dp->df_count[idx_to] = new_count; /* When changing the current buffer, keep track of line numbers */ if (idx_cur == idx_to) off += added; } /* If before the range or not deleted, go to next diff. */ if (dfree == NULL) { dprev = dp; dp = dp->df_next; } } /* restore curwin/curbuf and a few other things */ if (eap->cmdidx != CMD_diffget) { /* Syncing undo only works for the current buffer, but we change * another buffer. Sync undo if the command was typed. This isn't * 100% right when ":diffput" is used in a function or mapping. */ if (KeyTyped) u_sync(FALSE); aucmd_restbuf(&aco); } diff_busy = FALSE; /* Check that the cursor is on a valid character and update it's position. * When there were filler lines the topline has become invalid. */ check_cursor(); changed_line_abv_curs(); /* Also need to redraw the other buffers. */ diff_redraw(FALSE); } #ifdef FEAT_FOLDING /* * Update folds for all diff buffers for entry "dp". * Skip buffer with index "skip_idx". * When there are no diffs, all folds are removed. */ static void diff_fold_update(dp, skip_idx) diff_T *dp; int skip_idx; { int i; win_T *wp; for (wp = firstwin; wp != NULL; wp = wp->w_next) for (i = 0; i < DB_COUNT; ++i) if (curtab->tp_diffbuf[i] == wp->w_buffer && i != skip_idx) foldUpdate(wp, dp->df_lnum[i], dp->df_lnum[i] + dp->df_count[i]); } #endif /* * Return TRUE if buffer "buf" is in diff-mode. */ int diff_mode_buf(buf) buf_T *buf; { tabpage_T *tp; for (tp = first_tabpage; tp != NULL; tp = tp->tp_next) if (diff_buf_idx_tp(buf, tp) != DB_COUNT) return TRUE; return FALSE; } /* * Move "count" times in direction "dir" to the next diff block. * Return FAIL if there isn't such a diff block. */ int diff_move_to(dir, count) int dir; long count; { int idx; linenr_T lnum = curwin->w_cursor.lnum; diff_T *dp; idx = diff_buf_idx(curbuf); if (idx == DB_COUNT || curtab->tp_first_diff == NULL) return FAIL; if (curtab->tp_diff_invalid) ex_diffupdate(NULL); /* update after a big change */ if (curtab->tp_first_diff == NULL) /* no diffs today */ return FAIL; while (--count >= 0) { /* Check if already before first diff. */ if (dir == BACKWARD && lnum <= curtab->tp_first_diff->df_lnum[idx]) break; for (dp = curtab->tp_first_diff; ; dp = dp->df_next) { if (dp == NULL) break; if ((dir == FORWARD && lnum < dp->df_lnum[idx]) || (dir == BACKWARD && (dp->df_next == NULL || lnum <= dp->df_next->df_lnum[idx]))) { lnum = dp->df_lnum[idx]; break; } } } /* don't end up past the end of the file */ if (lnum > curbuf->b_ml.ml_line_count) lnum = curbuf->b_ml.ml_line_count; /* When the cursor didn't move at all we fail. */ if (lnum == curwin->w_cursor.lnum) return FAIL; setpcmark(); curwin->w_cursor.lnum = lnum; curwin->w_cursor.col = 0; return OK; } #if defined(FEAT_CURSORBIND) || defined(PROTO) linenr_T diff_get_corresponding_line(buf1, lnum1, buf2, lnum3) buf_T *buf1; linenr_T lnum1; buf_T *buf2; linenr_T lnum3; { int idx1; int idx2; diff_T *dp; int baseline = 0; linenr_T lnum2; idx1 = diff_buf_idx(buf1); idx2 = diff_buf_idx(buf2); if (idx1 == DB_COUNT || idx2 == DB_COUNT || curtab->tp_first_diff == NULL) return lnum1; if (curtab->tp_diff_invalid) ex_diffupdate(NULL); /* update after a big change */ if (curtab->tp_first_diff == NULL) /* no diffs today */ return lnum1; for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next) { if (dp->df_lnum[idx1] > lnum1) { lnum2 = lnum1 - baseline; /* don't end up past the end of the file */ if (lnum2 > buf2->b_ml.ml_line_count) lnum2 = buf2->b_ml.ml_line_count; return lnum2; } else if ((dp->df_lnum[idx1] + dp->df_count[idx1]) > lnum1) { /* Inside the diffblock */ baseline = lnum1 - dp->df_lnum[idx1]; if (baseline > dp->df_count[idx2]) baseline = dp->df_count[idx2]; return dp->df_lnum[idx2] + baseline; } else if ( (dp->df_lnum[idx1] == lnum1) && (dp->df_count[idx1] == 0) && (dp->df_lnum[idx2] <= lnum3) && ((dp->df_lnum[idx2] + dp->df_count[idx2]) > lnum3)) /* * Special case: if the cursor is just after a zero-count * block (i.e. all filler) and the target cursor is already * inside the corresponding block, leave the target cursor * unmoved. This makes repeated CTRL-W W operations work * as expected. */ return lnum3; baseline = (dp->df_lnum[idx1] + dp->df_count[idx1]) - (dp->df_lnum[idx2] + dp->df_count[idx2]); } /* If we get here then the cursor is after the last diff */ lnum2 = lnum1 - baseline; /* don't end up past the end of the file */ if (lnum2 > buf2->b_ml.ml_line_count) lnum2 = buf2->b_ml.ml_line_count; return lnum2; } #endif #if defined(FEAT_FOLDING) || defined(PROTO) /* * For line "lnum" in the current window find the equivalent lnum in window * "wp", compensating for inserted/deleted lines. */ linenr_T diff_lnum_win(lnum, wp) linenr_T lnum; win_T *wp; { diff_T *dp; int idx; int i; linenr_T n; idx = diff_buf_idx(curbuf); if (idx == DB_COUNT) /* safety check */ return (linenr_T)0; if (curtab->tp_diff_invalid) ex_diffupdate(NULL); /* update after a big change */ /* search for a change that includes "lnum" in the list of diffblocks. */ for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next) if (lnum <= dp->df_lnum[idx] + dp->df_count[idx]) break; /* When after the last change, compute relative to the last line number. */ if (dp == NULL) return wp->w_buffer->b_ml.ml_line_count - (curbuf->b_ml.ml_line_count - lnum); /* Find index for "wp". */ i = diff_buf_idx(wp->w_buffer); if (i == DB_COUNT) /* safety check */ return (linenr_T)0; n = lnum + (dp->df_lnum[i] - dp->df_lnum[idx]); if (n > dp->df_lnum[i] + dp->df_count[i]) n = dp->df_lnum[i] + dp->df_count[i]; return n; } #endif #endif /* FEAT_DIFF */
zyz2011-vim
src/diff.c
C
gpl2
65,038
/* vi:set ts=8 sw=4: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * Tcl extensions by Ingo Wilken <Ingo.Wilken@informatik.uni-oldenburg.de> * Last modification: Wed May 10 21:28:44 CEST 2000 * Requires Tcl 8.0 or higher. * * Variables: * ::vim::current(buffer) # Name of buffer command for current buffer. * ::vim::current(window) # Name of window command for current window. * ::vim::range(start) # Start of current range (line number). * ::vim::range(end) # End of current range (line number). * ::vim::lbase # Start of line/column numbers (1 or 0). * * Commands: * ::vim::command {cmd} # Execute ex command {cmd}. * ::vim::option {opt} [val] # Get/Set option {opt}. * ::vim::expr {expr} # Evaluate {expr} using vim's evaluator. * ::vim::beep # Guess. * * set buf [::vim::buffer {n}] # Create Tcl command for buffer N. * set bl [::vim::buffer list] # Get list of Tcl commands of all buffers. * ::vim::buffer exists {n} # True if buffer {n} exists. * * set wl [::vim::window list] # Get list of Tcl commands of all windows. * * set n [$win height] # Report window height. * $win height {n} # Set window height to {n}. * array set pos [$win cursor] # Get cursor position. * $win cursor {row} {col} # Set cursor position. * $win cursor pos # Set cursor position from array var "pos" * $win delcmd {cmd} # Register callback command for closed window. * $win option {opt} [val] # Get/Set vim option in context of $win. * $win command {cmd} # Execute ex command in context of $win. * $win expr {expr} # Evaluate vim expression in context of $win. * set buf [$win buffer] # Create Tcl command for window's buffer. * * $buf name # Reports file name in buffer. * $buf number # Reports buffer number. * set l [$buf get {n}] # Get buffer line {n} as a string. * set L [$buf get {n} {m}] # Get lines {n} through {m} as a list. * $buf count # Reports number of lines in buffer. * $buf last # Reports number of last line in buffer. * $buf delete {n} # Delete line {n}. * $buf delete {n} {m} # Delete lines {n} through {m}. * $buf set {n} {l} # Set line {n} to string {l}. * $buf set {n} {m} {L} # Set lines {n} through {m} from list {L}. * # Delete/inserts lines as appropriate. * $buf option {opt} [val] # Get/Set vim option in context of $buf. * $buf command {cmd} # Execute ex command in context of $buf * $buf expr {cmd} # Evaluate vim expression in context of $buf. * array set pos [$buf mark {m}] # Get position of mark. * $buf append {n} {str} # Append string {str} to buffer,after line {n}. * $buf insert {n} {str} # Insert string {str} in buffer as line {n}. * $buf delcmd {cmd} # Register callback command for deleted buffer. * set wl [$buf windows] # Get list of Tcl commands for all windows of * # this buffer. TODO: * ::vim::buffer new # create new buffer + Tcl command */ #include "vim.h" #undef EXTERN /* tcl.h defines it too */ #ifdef DYNAMIC_TCL # define USE_TCL_STUBS /* use tcl's stubs mechanism */ #endif #include <tcl.h> #include <string.h> typedef struct { Tcl_Interp *interp; int exitvalue; int range_start, range_end; int lbase; char *curbuf, *curwin; } tcl_info; static tcl_info tclinfo = { NULL, 0, 0, 0, 0, NULL, NULL }; #define VAR_RANGE1 "::vim::range(start)" #define VAR_RANGE2 "::vim::range(begin)" #define VAR_RANGE3 "::vim::range(end)" #define VAR_CURBUF "::vim::current(buffer)" #define VAR_CURWIN "::vim::current(window)" #define VAR_LBASE "::vim::lbase" #define VAR_CURLINE "line" #define VAR_CURLNUM "lnum" #define VARNAME_SIZE 64 #define row2tcl(x) ((x) - (tclinfo.lbase==0)) #define row2vim(x) ((x) + (tclinfo.lbase==0)) #define col2tcl(x) ((x) + (tclinfo.lbase!=0)) #define col2vim(x) ((x) - (tclinfo.lbase!=0)) #define VIMOUT ((ClientData)1) #define VIMERR ((ClientData)2) /* This appears to be new in Tcl 8.4. */ #ifndef CONST84 # define CONST84 #endif /* * List of Tcl interpreters who reference a vim window or buffer. * Each buffer and window has it's own list in the w_tcl_ref or b_tcl_ref * struct member. We need this because Tcl can create sub-interpreters with * the "interp" command, and each interpreter can reference all windows and * buffers. */ struct ref { struct ref *next; Tcl_Interp *interp; Tcl_Command cmd; /* Tcl command that represents this object */ Tcl_Obj *delcmd; /* Tcl command to call when object is being del. */ void *vimobj; /* Vim window or buffer (win_T* or buf_T*) */ }; static char * tclgetbuffer _ANSI_ARGS_((Tcl_Interp *interp, buf_T *buf)); static char * tclgetwindow _ANSI_ARGS_((Tcl_Interp *interp, win_T *win)); static int tclsetdelcmd _ANSI_ARGS_((Tcl_Interp *interp, struct ref *reflist, void *vimobj, Tcl_Obj *delcmd)); static int tclgetlinenum _ANSI_ARGS_ ((Tcl_Interp *interp, Tcl_Obj *obj, int *valueP, buf_T *buf)); static win_T *tclfindwin _ANSI_ARGS_ ((buf_T *buf)); static int tcldoexcommand _ANSI_ARGS_ ((Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[], int objn)); static int tclsetoption _ANSI_ARGS_ ((Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[], int objn)); static int tclvimexpr _ANSI_ARGS_ ((Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[], int objn)); static void tcldelthisinterp _ANSI_ARGS_ ((void)); static int vimerror _ANSI_ARGS_((Tcl_Interp *interp)); static void tclmsg _ANSI_ARGS_((char *text)); static void tclerrmsg _ANSI_ARGS_((char *text)); static void tclupdatevars _ANSI_ARGS_((void)); static struct ref refsdeleted; /* dummy object for deleted ref list */ /***************************************************************************** * TCL interface manager ****************************************************************************/ #if defined(DYNAMIC_TCL) || defined(PROTO) # ifndef DYNAMIC_TCL_DLL # define DYNAMIC_TCL_DLL "tcl83.dll" # endif # ifndef DYNAMIC_TCL_VER # define DYNAMIC_TCL_VER "8.3" # endif # ifndef DYNAMIC_TCL /* Just generating prototypes */ typedef int HANDLE; # endif /* * Declare HANDLE for tcl.dll and function pointers. */ static HANDLE hTclLib = NULL; Tcl_Interp* (*dll_Tcl_CreateInterp)(); /* * Table of name to function pointer of tcl. */ #define TCL_PROC FARPROC static struct { char* name; TCL_PROC* ptr; } tcl_funcname_table[] = { {"Tcl_CreateInterp", (TCL_PROC*)&dll_Tcl_CreateInterp}, {NULL, NULL}, }; /* * Make all runtime-links of tcl. * * 1. Get module handle using LoadLibraryEx. * 2. Get pointer to tcl function by GetProcAddress. * 3. Repeat 2, until get all functions will be used. * * Parameter 'libname' provides name of DLL. * Return OK or FAIL. */ static int tcl_runtime_link_init(char *libname, int verbose) { int i; if (hTclLib) return OK; if (!(hTclLib = LoadLibraryEx(libname, NULL, 0))) { if (verbose) EMSG2(_(e_loadlib), libname); return FAIL; } for (i = 0; tcl_funcname_table[i].ptr; ++i) { if (!(*tcl_funcname_table[i].ptr = GetProcAddress(hTclLib, tcl_funcname_table[i].name))) { FreeLibrary(hTclLib); hTclLib = NULL; if (verbose) EMSG2(_(e_loadfunc), tcl_funcname_table[i].name); return FAIL; } } return OK; } #endif /* defined(DYNAMIC_TCL) || defined(PROTO) */ #ifdef DYNAMIC_TCL static char *find_executable_arg = NULL; #endif void vim_tcl_init(arg) char *arg; { #ifndef DYNAMIC_TCL Tcl_FindExecutable(arg); #else find_executable_arg = arg; #endif } #if defined(DYNAMIC_TCL) || defined(PROTO) static int stubs_initialized = FALSE; /* * Return TRUE if the TCL interface can be used. */ int tcl_enabled(verbose) int verbose; { if (!stubs_initialized && find_executable_arg != NULL && tcl_runtime_link_init(DYNAMIC_TCL_DLL, verbose) == OK) { Tcl_Interp *interp; if (interp = dll_Tcl_CreateInterp()) { if (Tcl_InitStubs(interp, DYNAMIC_TCL_VER, 0)) { Tcl_FindExecutable(find_executable_arg); Tcl_DeleteInterp(interp); stubs_initialized = TRUE; } /* FIXME: When Tcl_InitStubs() was failed, how delete interp? */ } } return stubs_initialized; } #endif void tcl_end() { #ifdef DYNAMIC_TCL if (hTclLib) { FreeLibrary(hTclLib); hTclLib = NULL; } #endif } /**************************************************************************** Tcl commands ****************************************************************************/ /* * Replace standard "exit" command. * * Delete the Tcl interpreter; a new one will be created with the next * :tcl command). The exit code is saved (and retrieved in tclexit()). * Since Tcl's exit is never expected to return and this replacement * does, then (except for a trivial case) additional Tcl commands will * be run. Since the interpreter is now marked as deleted, an error * will be returned -- typically "attempt to call eval in deleted * interpreter". Hopefully, at this point, checks for TCL_ERROR take * place and control percolates back up to Vim -- but with this new error * string in the interpreter's result value. Therefore it would be * useless for this routine to return the exit code via Tcl_SetResult(). */ static int exitcmd(dummy, interp, objc, objv) ClientData dummy UNUSED; Tcl_Interp *interp; int objc; Tcl_Obj *CONST objv[]; { int value = 0; switch (objc) { case 2: if (Tcl_GetIntFromObj(interp, objv[1], &value) != TCL_OK) break; /* FALLTHROUGH */ case 1: tclinfo.exitvalue = value; Tcl_DeleteInterp(interp); break; default: Tcl_WrongNumArgs(interp, 1, objv, "?returnCode?"); } return TCL_ERROR; } /* * "::vim::beep" - what Vi[m] does best :-) */ static int beepcmd(dummy, interp, objc, objv) ClientData dummy UNUSED; Tcl_Interp *interp; int objc; Tcl_Obj *CONST objv[]; { if (objc != 1) { Tcl_WrongNumArgs(interp, 1, objv, NULL); return TCL_ERROR; } vim_beep(); return TCL_OK; } /* * "::vim::buffer list" - create a list of buffer commands. * "::vim::buffer {N}" - create buffer command for buffer N. * "::vim::buffer exists {N}" - test if buffer N exists. * "::vim::buffer new" - create a new buffer (not implemented) */ static int buffercmd(dummy, interp, objc, objv) ClientData dummy UNUSED; Tcl_Interp *interp; int objc; Tcl_Obj *CONST objv[]; { char *name; buf_T *buf; Tcl_Obj *resobj; int err, n, idx; enum {BCMD_EXISTS, BCMD_LIST}; static CONST84 char *bcmdoptions[] = { "exists", "list", (char *)0 }; if (objc < 2) { Tcl_WrongNumArgs(interp, 1, objv, "option"); return TCL_ERROR; } err = Tcl_GetIntFromObj(interp, objv[1], &n); if (err == TCL_OK) { if (objc != 2) { Tcl_WrongNumArgs(interp, 1, objv, "bufNumber"); return TCL_ERROR; } for (buf = firstbuf; buf != NULL; buf = buf->b_next) { if (buf->b_fnum == n) { name = tclgetbuffer(interp, buf); if (name == NULL) return TCL_ERROR; Tcl_SetResult(interp, name, TCL_VOLATILE); return TCL_OK; } } Tcl_SetResult(interp, _("invalid buffer number"), TCL_STATIC); return TCL_ERROR; } Tcl_ResetResult(interp); /* clear error from Tcl_GetIntFromObj */ err = Tcl_GetIndexFromObj(interp, objv[1], bcmdoptions, "option", 0, &idx); if (err != TCL_OK) return err; switch (idx) { case BCMD_LIST: if (objc != 2) { Tcl_WrongNumArgs(interp, 2, objv, ""); err = TCL_ERROR; break; } for (buf = firstbuf; buf != NULL; buf = buf->b_next) { name = tclgetbuffer(interp, buf); if (name == NULL) { err = TCL_ERROR; break; } Tcl_AppendElement(interp, name); } break; case BCMD_EXISTS: if (objc != 3) { Tcl_WrongNumArgs(interp, 2, objv, "bufNumber"); err = TCL_ERROR; break; } err = Tcl_GetIntFromObj(interp, objv[2], &n); if (err == TCL_OK) { buf = buflist_findnr(n); resobj = Tcl_NewIntObj(buf != NULL); Tcl_SetObjResult(interp, resobj); } break; default: Tcl_SetResult(interp, _("not implemented yet"), TCL_STATIC); err = TCL_ERROR; } return err; } /* * "::vim::window list" - create list of window commands. */ static int windowcmd(dummy, interp, objc, objv) ClientData dummy UNUSED; Tcl_Interp *interp; int objc; Tcl_Obj *CONST objv[]; { char *what, *string; win_T *win; if (objc != 2) { Tcl_WrongNumArgs(interp, 1, objv, "option"); return TCL_ERROR; } what = Tcl_GetStringFromObj(objv[1], NULL); if (strcmp(what, "list") == 0) { FOR_ALL_WINDOWS(win) { string = tclgetwindow(interp, win); if (string == NULL) return TCL_ERROR; Tcl_AppendElement(interp, string); } return TCL_OK; } Tcl_SetResult(interp, _("unknown option"), TCL_STATIC); return TCL_ERROR; } /* * flags for bufselfcmd and winselfcmd to indicate outstanding actions. */ #define FL_UPDATE_SCREEN (1<<0) #define FL_UPDATE_CURBUF (1<<1) #define FL_ADJUST_CURSOR (1<<2) /* * This function implements the buffer commands. */ static int bufselfcmd(ref, interp, objc, objv) ClientData ref; Tcl_Interp *interp; int objc; Tcl_Obj *CONST objv[]; { int opt, err, idx, flags; int val1, val2, n, i; buf_T *buf, *savebuf; win_T *win, *savewin; Tcl_Obj *resobj; pos_T *pos; char *line; enum { BUF_APPEND, BUF_COMMAND, BUF_COUNT, BUF_DELCMD, BUF_DELETE, BUF_EXPR, BUF_GET, BUF_INSERT, BUF_LAST, BUF_MARK, BUF_NAME, BUF_NUMBER, BUF_OPTION, BUF_SET, BUF_WINDOWS }; static CONST84 char *bufoptions[] = { "append", "command", "count", "delcmd", "delete", "expr", "get", "insert", "last", "mark", "name", "number", "option", "set", "windows", (char *)0 }; if (objc < 2) { Tcl_WrongNumArgs(interp, 1, objv, "option ?arg ...?"); return TCL_ERROR; } err = Tcl_GetIndexFromObj(interp, objv[1], bufoptions, "option", 0, &idx); if (err != TCL_OK) return err; buf = (buf_T *)((struct ref *)ref)->vimobj; savebuf = curbuf; curbuf = buf; savewin = curwin; curwin = tclfindwin(buf); flags = 0; opt = 0; switch (idx) { case BUF_COMMAND: err = tcldoexcommand(interp, objc, objv, 2); flags |= FL_UPDATE_SCREEN; break; case BUF_OPTION: err = tclsetoption(interp, objc, objv, 2); flags |= FL_UPDATE_SCREEN; break; case BUF_EXPR: err = tclvimexpr(interp, objc, objv, 2); break; case BUF_NAME: /* * Get filename of buffer. */ if (objc != 2) { Tcl_WrongNumArgs(interp, 2, objv, NULL); err = TCL_ERROR; break; } if (buf->b_ffname) Tcl_SetResult(interp, (char *)buf->b_ffname, TCL_VOLATILE); else Tcl_SetResult(interp, "", TCL_STATIC); break; case BUF_LAST: /* * Get line number of last line. */ opt = 1; /* fallthrough */ case BUF_COUNT: /* * Get number of lines in buffer. */ if (objc != 2) { Tcl_WrongNumArgs(interp, 2, objv, NULL); err = TCL_ERROR; break; } val1 = (int)buf->b_ml.ml_line_count; if (opt) val1 = row2tcl(val1); resobj = Tcl_NewIntObj(val1); Tcl_SetObjResult(interp, resobj); break; case BUF_NUMBER: /* * Get buffer's number. */ if (objc != 2) { Tcl_WrongNumArgs(interp, 2, objv, NULL); err = TCL_ERROR; break; } resobj = Tcl_NewIntObj((int)buf->b_fnum); Tcl_SetObjResult(interp, resobj); break; case BUF_GET: if (objc != 3 && objc != 4) { Tcl_WrongNumArgs(interp, 2, objv, "lineNumber ?lineNumber?"); err = TCL_ERROR; break; } err = tclgetlinenum(interp, objv[2], &val1, buf); if (err != TCL_OK) break; if (objc == 4) { err = tclgetlinenum(interp, objv[3], &val2, buf); if (err != TCL_OK) break; if (val1 > val2) { n = val1; val1 = val2; val2 = n; } Tcl_ResetResult(interp); for (n = val1; n <= val2 && err == TCL_OK; n++) { line = (char *)ml_get_buf(buf, (linenr_T)n, FALSE); if (line) Tcl_AppendElement(interp, line); else err = TCL_ERROR; } } else { /* objc == 3 */ line = (char *)ml_get_buf(buf, (linenr_T)val1, FALSE); Tcl_SetResult(interp, line, TCL_VOLATILE); } break; case BUF_SET: if (objc != 4 && objc != 5) { Tcl_WrongNumArgs(interp, 3, objv, "lineNumber ?lineNumber? stringOrList"); err = TCL_ERROR; break; } err = tclgetlinenum(interp, objv[2], &val1, buf); if (err != TCL_OK) return TCL_ERROR; if (objc == 4) { /* * Replace one line with a string. * $buf set {n} {string} */ line = Tcl_GetStringFromObj(objv[3], NULL); if (u_savesub((linenr_T)val1) != OK) { Tcl_SetResult(interp, _("cannot save undo information"), TCL_STATIC); err = TCL_ERROR; } else if (ml_replace((linenr_T)val1, (char_u *)line, TRUE) != OK) { Tcl_SetResult(interp, _("cannot replace line"), TCL_STATIC); err = TCL_ERROR; } else { changed_bytes((linenr_T)val1, 0); flags |= FL_UPDATE_CURBUF; } break; } else { /* * Replace several lines with the elements of a Tcl list. * $buf set {n} {m} {list} * If the list contains more than {m}-{n}+1 elements, they * are * inserted after line {m}. If the list contains fewer * elements, * the lines from {n}+length({list}) through {m} * are deleted. */ int lc; Tcl_Obj **lv; err = tclgetlinenum(interp, objv[3], &val2, buf); if (err != TCL_OK) break; err = Tcl_ListObjGetElements(interp, objv[4], &lc, &lv); if (err != TCL_OK) break; if (val1 > val2) { n = val1; val1 = val2; val2 = n; } n = val1; if (u_save((linenr_T)(val1 - 1), (linenr_T)(val2 + 1)) != OK) { Tcl_SetResult(interp, _("cannot save undo information"), TCL_STATIC); err = TCL_ERROR; break; } flags |= FL_UPDATE_CURBUF; for (i = 0; i < lc && n <= val2; i++) { line = Tcl_GetStringFromObj(lv[i], NULL); if (ml_replace((linenr_T)n, (char_u *)line, TRUE) != OK) goto setListError; ++n; } if (i < lc) { /* append lines */ do { line = Tcl_GetStringFromObj(lv[i], NULL); if (ml_append((linenr_T)(n - 1), (char_u *)line, 0, FALSE) != OK) goto setListError; ++n; ++i; } while (i < lc); } else if (n <= val2) { /* did not replace all lines, delete */ i = n; do { if (ml_delete((linenr_T)i, FALSE) != OK) goto setListError; ++n; } while (n <= val2); } lc -= val2 - val1 + 1; /* number of lines to be replaced */ mark_adjust((linenr_T)val1, (linenr_T)val2, (long)MAXLNUM, (long)lc); changed_lines((linenr_T)val1, 0, (linenr_T)val2 + 1, (long)lc); break; setListError: u_undo(1); /* ??? */ Tcl_SetResult(interp, _("cannot set line(s)"), TCL_STATIC); err = TCL_ERROR; } break; case BUF_DELETE: if (objc != 3 && objc != 4) { Tcl_WrongNumArgs(interp, 3, objv, "lineNumber ?lineNumber?"); err = TCL_ERROR; break; } err = tclgetlinenum(interp, objv[2], &val1, buf); if (err != TCL_OK) break; val2 = val1; if (objc == 4) { err = tclgetlinenum(interp, objv[3], &val2, buf); if (err != TCL_OK) return err; if (val1 > val2) { i = val1; val1 = val2; val2 = i; } } n = val2 - val1 + 1; if (u_savedel((linenr_T)val1, (long)n) != OK) { Tcl_SetResult(interp, _("cannot save undo information"), TCL_STATIC); err = TCL_ERROR; break; } for (i = 0; i < n; i++) { ml_delete((linenr_T)val1, FALSE); err = vimerror(interp); if (err != TCL_OK) break; } if (i > 0) deleted_lines_mark((linenr_T)val1, (long)i); flags |= FL_ADJUST_CURSOR|FL_UPDATE_SCREEN; break; case BUF_MARK: if (objc != 3) { Tcl_WrongNumArgs(interp, 2, objv, "markName"); err = TCL_ERROR; break; } line = Tcl_GetStringFromObj(objv[2], NULL); pos = NULL; if (line[0] != '\0' && line[1] == '\0') { pos = getmark(line[0], FALSE); } if (pos == NULL) { Tcl_SetResult(interp, _("invalid mark name"), TCL_STATIC); err = TCL_ERROR; break; } err = vimerror(interp); if (err != TCL_OK) break; if (pos->lnum <= 0) { Tcl_SetResult(interp, _("mark not set"), TCL_STATIC); err = TCL_ERROR; } else { char rbuf[64]; sprintf(rbuf, _("row %d column %d"), (int)row2tcl(pos->lnum), (int)col2tcl(pos->col)); Tcl_SetResult(interp, rbuf, TCL_VOLATILE); } break; case BUF_INSERT: opt = 1; /* fallthrough */ case BUF_APPEND: if (objc != 4) { Tcl_WrongNumArgs(interp, 2, objv, "lineNum text"); err = TCL_ERROR; break; } err = tclgetlinenum(interp, objv[2], &val1, buf); if (err != TCL_OK) break; if (opt) --val1; if (u_save((linenr_T)val1, (linenr_T)(val1+1)) != OK) { Tcl_SetResult(interp, _("cannot save undo information"), TCL_STATIC); err = TCL_ERROR; break; } line = Tcl_GetStringFromObj(objv[3], NULL); if (ml_append((linenr_T)val1, (char_u *)line, 0, FALSE) != OK) { Tcl_SetResult(interp, _("cannot insert/append line"), TCL_STATIC); err = TCL_ERROR; break; } appended_lines_mark((linenr_T)val1, 1L); flags |= FL_UPDATE_SCREEN; break; case BUF_WINDOWS: /* * Return list of window commands. */ if (objc != 2) { Tcl_WrongNumArgs(interp, 2, objv, NULL); err = TCL_ERROR; break; } Tcl_ResetResult(interp); FOR_ALL_WINDOWS(win) { if (win->w_buffer == buf) { line = tclgetwindow(interp, win); if (line != NULL) Tcl_AppendElement(interp, line); else { err = TCL_ERROR; break; } } } break; case BUF_DELCMD: /* * Register deletion callback. * TODO: Should be able to register multiple callbacks */ if (objc != 3) { Tcl_WrongNumArgs(interp, 2, objv, "command"); err = TCL_ERROR; break; } err = tclsetdelcmd(interp, buf->b_tcl_ref, (void *)buf, objv[2]); break; default: Tcl_SetResult(interp, _("not implemented yet"), TCL_STATIC); err = TCL_ERROR; } if (flags & FL_UPDATE_CURBUF) redraw_curbuf_later(NOT_VALID); curbuf = savebuf; curwin = savewin; if (flags & FL_ADJUST_CURSOR) check_cursor(); if (flags & (FL_UPDATE_SCREEN | FL_UPDATE_CURBUF)) update_screen(NOT_VALID); return err; } /* * This function implements the window commands. */ static int winselfcmd(ref, interp, objc, objv) ClientData ref; Tcl_Interp *interp; int objc; Tcl_Obj *CONST objv[]; { int err, idx, flags; int val1, val2; Tcl_Obj *resobj; win_T *savewin, *win; buf_T *savebuf; char *str; enum { WIN_BUFFER, WIN_COMMAND, WIN_CURSOR, WIN_DELCMD, WIN_EXPR, WIN_HEIGHT, WIN_OPTION }; static CONST84 char *winoptions[] = { "buffer", "command", "cursor", "delcmd", "expr", "height", "option", (char *)0 }; if (objc < 2) { Tcl_WrongNumArgs(interp, 1, objv, "option ?arg ...?"); return TCL_ERROR; } err = Tcl_GetIndexFromObj(interp, objv[1], winoptions, "option", 0, &idx); if (err != TCL_OK) return TCL_ERROR; win = (win_T *)((struct ref *)ref)->vimobj; savewin = curwin; curwin = win; savebuf = curbuf; curbuf = win->w_buffer; flags = 0; switch (idx) { case WIN_OPTION: err = tclsetoption(interp, objc, objv, 2); flags |= FL_UPDATE_SCREEN; break; case WIN_COMMAND: err = tcldoexcommand(interp, objc, objv, 2); flags |= FL_UPDATE_SCREEN; break; case WIN_EXPR: err = tclvimexpr(interp, objc, objv, 2); break; case WIN_HEIGHT: if (objc == 3) { err = Tcl_GetIntFromObj(interp, objv[2], &val1); if (err != TCL_OK) break; #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif win_setheight(val1); err = vimerror(interp); if (err != TCL_OK) break; } else if (objc != 2) { Tcl_WrongNumArgs(interp, 2, objv, "?value?"); err = TCL_ERROR; break; } resobj = Tcl_NewIntObj((int)(win->w_height)); Tcl_SetObjResult(interp, resobj); break; case WIN_BUFFER: if (objc != 2) { Tcl_WrongNumArgs(interp, 2, objv, NULL); err = TCL_ERROR; break; } str = tclgetbuffer(interp, win->w_buffer); if (str) Tcl_SetResult(interp, str, TCL_VOLATILE); else err = TCL_ERROR; break; case WIN_DELCMD: if (objc != 3) { Tcl_WrongNumArgs(interp, 2, objv, "command"); err = TCL_ERROR; break; } err = tclsetdelcmd(interp, win->w_tcl_ref, (void *)win, objv[2]); break; case WIN_CURSOR: if (objc > 4) { Tcl_WrongNumArgs(interp, 2, objv, "?arg1 ?arg2??"); err = TCL_ERROR; break; } if (objc == 2) { char buf[64]; sprintf(buf, _("row %d column %d"), (int)row2tcl(win->w_cursor.lnum), (int)col2tcl(win->w_cursor.col)); Tcl_SetResult(interp, buf, TCL_VOLATILE); break; } else if (objc == 3) { Tcl_Obj *part, *var; part = Tcl_NewStringObj("row", -1); var = Tcl_ObjGetVar2(interp, objv[2], part, TCL_LEAVE_ERR_MSG); if (var == NULL) { err = TCL_ERROR; break; } err = tclgetlinenum(interp, var, &val1, win->w_buffer); if (err != TCL_OK) break; part = Tcl_NewStringObj("column", -1); var = Tcl_ObjGetVar2(interp, objv[2], part, TCL_LEAVE_ERR_MSG); if (var == NULL) { err = TCL_ERROR; break; } err = Tcl_GetIntFromObj(interp, var, &val2); if (err != TCL_OK) break; } else { /* objc == 4 */ err = tclgetlinenum(interp, objv[2], &val1, win->w_buffer); if (err != TCL_OK) break; err = Tcl_GetIntFromObj(interp, objv[3], &val2); if (err != TCL_OK) break; } /* TODO: should check column */ win->w_cursor.lnum = val1; win->w_cursor.col = col2vim(val2); flags |= FL_UPDATE_SCREEN; break; default: Tcl_SetResult(interp, _("not implemented yet"), TCL_STATIC); break; } curwin = savewin; curbuf = savebuf; if (flags & FL_UPDATE_SCREEN) update_screen(NOT_VALID); return err; } static int commandcmd(dummy, interp, objc, objv) ClientData dummy UNUSED; Tcl_Interp *interp; int objc; Tcl_Obj *CONST objv[]; { int err; err = tcldoexcommand(interp, objc, objv, 1); update_screen(VALID); return err; } static int optioncmd(dummy, interp, objc, objv) ClientData dummy UNUSED; Tcl_Interp *interp; int objc; Tcl_Obj *CONST objv[]; { int err; err = tclsetoption(interp, objc, objv, 1); update_screen(VALID); return err; } static int exprcmd(dummy, interp, objc, objv) ClientData dummy UNUSED; Tcl_Interp *interp; int objc; Tcl_Obj *CONST objv[]; { return tclvimexpr(interp, objc, objv, 1); } /**************************************************************************** Support functions for Tcl commands ****************************************************************************/ /* * Get a line number from 'obj' and convert it to vim's range. */ static int tclgetlinenum(interp, obj, valueP, buf) Tcl_Interp *interp; Tcl_Obj *obj; int *valueP; buf_T *buf; { int err, i; enum { LN_BEGIN, LN_BOTTOM, LN_END, LN_FIRST, LN_LAST, LN_START, LN_TOP }; static CONST84 char *keyw[] = { "begin", "bottom", "end", "first", "last", "start", "top", (char *)0 }; err = Tcl_GetIndexFromObj(interp, obj, keyw, "", 0, &i); if (err == TCL_OK) { switch (i) { case LN_BEGIN: case LN_FIRST: case LN_START: case LN_TOP: *valueP = 1; break; case LN_BOTTOM: case LN_END: case LN_LAST: *valueP = buf->b_ml.ml_line_count; break; } return TCL_OK; } Tcl_ResetResult(interp); err = Tcl_GetIntFromObj(interp, obj, &i); if (err != TCL_OK) return err; i = row2vim(i); if (i < 1 || i > buf->b_ml.ml_line_count) { Tcl_SetResult(interp, _("line number out of range"), TCL_STATIC); return TCL_ERROR; } *valueP = i; return TCL_OK; } /* * Find the first window in the window list that displays the buffer. */ static win_T * tclfindwin(buf) buf_T *buf; { win_T *win; FOR_ALL_WINDOWS(win) { if (win->w_buffer == buf) return win; } return curwin; /* keep current window context */ } /* * Do-it-all function for "::vim::command", "$buf command" and "$win command". */ static int tcldoexcommand(interp, objc, objv, objn) Tcl_Interp *interp; int objc; Tcl_Obj *CONST objv[]; int objn; { tcl_info saveinfo; int err, flag, nobjs; char *arg; nobjs = objc - objn; if (nobjs < 1 || nobjs > 2) { Tcl_WrongNumArgs(interp, objn, objv, "?-quiet? exCommand"); return TCL_ERROR; } flag = 0; if (nobjs == 2) { arg = Tcl_GetStringFromObj(objv[objn], NULL); if (strcmp(arg, "-quiet") == 0) flag = 1; else { Tcl_ResetResult(interp); Tcl_AppendResult(interp, _("unknown flag: "), arg, (char *)0); return TCL_ERROR; } ++objn; } memcpy(&saveinfo, &tclinfo, sizeof(tcl_info)); tclinfo.interp = NULL; tclinfo.curwin = NULL; tclinfo.curbuf = NULL; arg = Tcl_GetStringFromObj(objv[objn], NULL); if (flag) ++emsg_off; do_cmdline_cmd((char_u *)arg); if (flag) --emsg_off; err = vimerror(interp); /* If the ex command created a new Tcl interpreter, remove it */ if (tclinfo.interp) tcldelthisinterp(); memcpy(&tclinfo, &saveinfo, sizeof(tcl_info)); tclupdatevars(); return err; } /* * Do-it-all function for "::vim::option", "$buf option" and "$win option". */ static int tclsetoption(interp, objc, objv, objn) Tcl_Interp *interp; int objc; Tcl_Obj *CONST objv[]; int objn; { int err, nobjs, idx; char_u *option; int isnum; long lval; char_u *sval; Tcl_Obj *resobj; enum { OPT_OFF, OPT_ON, OPT_TOGGLE }; static CONST84 char *optkw[] = { "off", "on", "toggle", (char *)0 }; nobjs = objc - objn; if (nobjs != 1 && nobjs != 2) { Tcl_WrongNumArgs(interp, objn, objv, "vimOption ?value?"); return TCL_ERROR; } option = (char_u *)Tcl_GetStringFromObj(objv[objn], NULL); ++objn; isnum = get_option_value(option, &lval, &sval, 0); err = TCL_OK; switch (isnum) { case 0: Tcl_SetResult(interp, (char *)sval, TCL_VOLATILE); vim_free(sval); break; case 1: resobj = Tcl_NewLongObj(lval); Tcl_SetObjResult(interp, resobj); break; default: Tcl_SetResult(interp, _("unknown vimOption"), TCL_STATIC); return TCL_ERROR; } if (nobjs == 2) { if (isnum) { sval = NULL; /* avoid compiler warning */ err = Tcl_GetIndexFromObj(interp, objv[objn], optkw, "", 0, &idx); if (err != TCL_OK) { Tcl_ResetResult(interp); err = Tcl_GetLongFromObj(interp, objv[objn], &lval); } else switch (idx) { case OPT_ON: lval = 1; break; case OPT_OFF: lval = 0; break; case OPT_TOGGLE: lval = !lval; break; } } else sval = (char_u *)Tcl_GetStringFromObj(objv[objn], NULL); if (err == TCL_OK) { set_option_value(option, lval, sval, OPT_LOCAL); err = vimerror(interp); } } return err; } /* * Do-it-all function for "::vim::expr", "$buf expr" and "$win expr". */ static int tclvimexpr(interp, objc, objv, objn) Tcl_Interp *interp; int objc; Tcl_Obj *CONST objv[]; int objn; { #ifdef FEAT_EVAL char *expr, *str; #endif int err; if (objc - objn != 1) { Tcl_WrongNumArgs(interp, objn, objv, "vimExpr"); return TCL_ERROR; } #ifdef FEAT_EVAL expr = Tcl_GetStringFromObj(objv[objn], NULL); str = (char *)eval_to_string((char_u *)expr, NULL, TRUE); if (str == NULL) Tcl_SetResult(interp, _("invalid expression"), TCL_STATIC); else Tcl_SetResult(interp, str, TCL_VOLATILE); err = vimerror(interp); #else Tcl_SetResult(interp, _("expressions disabled at compile time"), TCL_STATIC); err = TCL_ERROR; #endif return err; } /* * Check for internal vim errors. */ static int vimerror(interp) Tcl_Interp *interp; { if (got_int) { Tcl_SetResult(interp, _("keyboard interrupt"), TCL_STATIC); return TCL_ERROR; } else if (did_emsg) { Tcl_SetResult(interp, _("vim error"), TCL_STATIC); return TCL_ERROR; } return TCL_OK; } /* * Functions that handle the reference lists: * delref() - callback for Tcl's DeleteCommand * tclgetref() - find/create Tcl command for a win_T* or buf_T* object * tclgetwindow() - window frontend for tclgetref() * tclgetbuffer() - buffer frontend for tclgetref() * tclsetdelcmd() - add Tcl callback command to a vim object */ static void delref(cref) ClientData cref; { struct ref *ref = (struct ref *)cref; if (ref->delcmd) { Tcl_DecrRefCount(ref->delcmd); ref->delcmd = NULL; } ref->interp = NULL; } static char * tclgetref(interp, refstartP, prefix, vimobj, proc) Tcl_Interp *interp; void **refstartP; /* ptr to w_tcl_ref/b_tcl-ref member of win_T/buf_T struct */ char *prefix; /* "win" or "buf" */ void *vimobj; /* win_T* or buf_T* */ Tcl_ObjCmdProc *proc; /* winselfcmd or bufselfcmd */ { struct ref *ref, *unused = NULL; static char name[VARNAME_SIZE]; Tcl_Command cmd; ref = (struct ref *)(*refstartP); if (ref == &refsdeleted) { Tcl_SetResult(interp, _("cannot create buffer/window command: object is being deleted"), TCL_STATIC); return NULL; } while (ref != NULL) { if (ref->interp == interp) break; if (ref->interp == NULL) unused = ref; ref = ref->next; } if (ref) vim_snprintf(name, sizeof(name), "::vim::%s", Tcl_GetCommandName(interp, ref->cmd)); else { if (unused) ref = unused; else { ref = (struct ref *)Tcl_Alloc(sizeof(struct ref)); ref->interp = NULL; ref->next = (struct ref *)(*refstartP); (*refstartP) = (void *)ref; } /* This might break on some exotic systems... */ vim_snprintf(name, sizeof(name), "::vim::%s_%lx", prefix, (unsigned long)vimobj); cmd = Tcl_CreateObjCommand(interp, name, proc, (ClientData)ref, (Tcl_CmdDeleteProc *)delref); if (!cmd) return NULL; ref->interp = interp; ref->cmd = cmd; ref->delcmd = NULL; ref->vimobj = vimobj; } return name; } static char * tclgetwindow(interp, win) Tcl_Interp *interp; win_T *win; { return tclgetref(interp, &(win->w_tcl_ref), "win", (void *)win, winselfcmd); } static char * tclgetbuffer(interp, buf) Tcl_Interp *interp; buf_T *buf; { return tclgetref(interp, &(buf->b_tcl_ref), "buf", (void *)buf, bufselfcmd); } static int tclsetdelcmd(interp, reflist, vimobj, delcmd) Tcl_Interp *interp; struct ref *reflist; void *vimobj; Tcl_Obj *delcmd; { if (reflist == &refsdeleted) { Tcl_SetResult(interp, _("cannot register callback command: buffer/window is already being deleted"), TCL_STATIC); return TCL_ERROR; } while (reflist != NULL) { if (reflist->interp == interp && reflist->vimobj == vimobj) { if (reflist->delcmd) { Tcl_DecrRefCount(reflist->delcmd); } Tcl_IncrRefCount(delcmd); reflist->delcmd = delcmd; return TCL_OK; } reflist = reflist->next; } /* This should never happen. Famous last word? */ EMSG(_("E280: TCL FATAL ERROR: reflist corrupt!? Please report this to vim-dev@vim.org")); Tcl_SetResult(interp, _("cannot register callback command: buffer/window reference not found"), TCL_STATIC); return TCL_ERROR; } /******************************************* I/O Channel ********************************************/ static int channel_close(instance, interp) ClientData instance; Tcl_Interp *interp UNUSED; { int err = 0; /* currently does nothing */ if (instance != VIMOUT && instance != VIMERR) { Tcl_SetErrno(EBADF); err = EBADF; } return err; } static int channel_input(instance, buf, bufsiz, errptr) ClientData instance UNUSED; char *buf UNUSED; int bufsiz UNUSED; int *errptr; { /* input is currently not supported */ Tcl_SetErrno(EINVAL); if (errptr) *errptr = EINVAL; return -1; } static int channel_output(instance, buf, bufsiz, errptr) ClientData instance; char *buf; int bufsiz; int *errptr; { char_u *str; int result; /* The buffer is not guaranteed to be 0-terminated, and we don't if * there is enough room to add a '\0'. So we have to create a copy * of the buffer... */ str = vim_strnsave((char_u *)buf, bufsiz); if (!str) { Tcl_SetErrno(ENOMEM); if (errptr) *errptr = ENOMEM; return -1; } result = bufsiz; if (instance == VIMOUT) tclmsg((char *)str); else if (instance == VIMERR) tclerrmsg((char *)str); else { Tcl_SetErrno(EBADF); if (errptr) *errptr = EBADF; result = -1; } vim_free(str); return result; } static void channel_watch(instance, mask) ClientData instance UNUSED; int mask UNUSED; { Tcl_SetErrno(EINVAL); } static int channel_gethandle(instance, direction, handleptr) ClientData instance UNUSED; int direction UNUSED; ClientData *handleptr UNUSED; { Tcl_SetErrno(EINVAL); return EINVAL; } static Tcl_ChannelType channel_type = { "vimmessage", /* typeName */ TCL_CHANNEL_VERSION_2, /* version */ channel_close, /* closeProc */ channel_input, /* inputProc */ channel_output, /* outputProc */ NULL, /* seekProc */ NULL, /* setOptionProc */ NULL, /* getOptionProc */ channel_watch, /* watchProc */ channel_gethandle, /* getHandleProc */ NULL, /* close2Proc */ NULL, /* blockModeProc */ #ifdef TCL_CHANNEL_VERSION_2 NULL, /* flushProc */ NULL, /* handlerProc */ #endif /* The following should not be necessary since TCL_CHANNEL_VERSION_2 was * set above */ #ifdef TCL_CHANNEL_VERSION_3 NULL, /* wideSeekProc */ #endif #ifdef TCL_CHANNEL_VERSION_4 NULL, /* threadActionProc */ #endif #ifdef TCL_CHANNEL_VERSION_5 NULL /* truncateProc */ #endif }; /********************************** Interface to vim **********************************/ static void tclupdatevars() { char varname[VARNAME_SIZE]; /* must be writeable */ char *name; strcpy(varname, VAR_RANGE1); Tcl_UpdateLinkedVar(tclinfo.interp, varname); strcpy(varname, VAR_RANGE2); Tcl_UpdateLinkedVar(tclinfo.interp, varname); strcpy(varname, VAR_RANGE3); Tcl_UpdateLinkedVar(tclinfo.interp, varname); strcpy(varname, VAR_LBASE); Tcl_UpdateLinkedVar(tclinfo.interp, varname); name = tclgetbuffer(tclinfo.interp, curbuf); strcpy(tclinfo.curbuf, name); strcpy(varname, VAR_CURBUF); Tcl_UpdateLinkedVar(tclinfo.interp, varname); name = tclgetwindow(tclinfo.interp, curwin); strcpy(tclinfo.curwin, name); strcpy(varname, VAR_CURWIN); Tcl_UpdateLinkedVar(tclinfo.interp, varname); } static int tclinit(eap) exarg_T *eap; { char varname[VARNAME_SIZE]; /* Tcl_LinkVar requires writeable varname */ char *name; #ifdef DYNAMIC_TCL if (!tcl_enabled(TRUE)) { EMSG(_("E571: Sorry, this command is disabled: the Tcl library could not be loaded.")); return FAIL; } #endif if (!tclinfo.interp) { Tcl_Interp *interp; static Tcl_Channel ch1, ch2; /* Create replacement channels for stdout and stderr; this has to be * done each time an interpreter is created since the channels are closed * when the interpreter is deleted */ ch1 = Tcl_CreateChannel(&channel_type, "vimout", VIMOUT, TCL_WRITABLE); ch2 = Tcl_CreateChannel(&channel_type, "vimerr", VIMERR, TCL_WRITABLE); Tcl_SetStdChannel(ch1, TCL_STDOUT); Tcl_SetStdChannel(ch2, TCL_STDERR); interp = Tcl_CreateInterp(); Tcl_Preserve(interp); if (Tcl_Init(interp) == TCL_ERROR) { Tcl_Release(interp); Tcl_DeleteInterp(interp); return FAIL; } #if 0 /* VIM sure is interactive */ Tcl_SetVar(interp, "tcl_interactive", "1", TCL_GLOBAL_ONLY); #endif Tcl_SetChannelOption(interp, ch1, "-buffering", "line"); #ifdef WIN3264 Tcl_SetChannelOption(interp, ch1, "-translation", "lf"); #endif Tcl_SetChannelOption(interp, ch2, "-buffering", "line"); #ifdef WIN3264 Tcl_SetChannelOption(interp, ch2, "-translation", "lf"); #endif /* replace standard Tcl exit command */ Tcl_DeleteCommand(interp, "exit"); Tcl_CreateObjCommand(interp, "exit", exitcmd, (ClientData)NULL, (Tcl_CmdDeleteProc *)NULL); /* new commands, in ::vim namespace */ Tcl_CreateObjCommand(interp, "::vim::buffer", buffercmd, (ClientData)NULL, (Tcl_CmdDeleteProc *)NULL); Tcl_CreateObjCommand(interp, "::vim::window", windowcmd, (ClientData)NULL, (Tcl_CmdDeleteProc *)NULL); Tcl_CreateObjCommand(interp, "::vim::command", commandcmd, (ClientData)NULL, (Tcl_CmdDeleteProc *)NULL); Tcl_CreateObjCommand(interp, "::vim::beep", beepcmd, (ClientData)NULL, (Tcl_CmdDeleteProc *)NULL); Tcl_CreateObjCommand(interp, "::vim::option", optioncmd, (ClientData)NULL, (Tcl_CmdDeleteProc *)NULL); Tcl_CreateObjCommand(interp, "::vim::expr", exprcmd, (ClientData)NULL, (Tcl_CmdDeleteProc *)NULL); /* "lbase" variable */ tclinfo.lbase = 1; strcpy(varname, VAR_LBASE); Tcl_LinkVar(interp, varname, (char *)&tclinfo.lbase, TCL_LINK_INT); /* "range" variable */ tclinfo.range_start = eap->line1; strcpy(varname, VAR_RANGE1); Tcl_LinkVar(interp, varname, (char *)&tclinfo.range_start, TCL_LINK_INT|TCL_LINK_READ_ONLY); strcpy(varname, VAR_RANGE2); Tcl_LinkVar(interp, varname, (char *)&tclinfo.range_start, TCL_LINK_INT|TCL_LINK_READ_ONLY); tclinfo.range_end = eap->line2; strcpy(varname, VAR_RANGE3); Tcl_LinkVar(interp, varname, (char *)&tclinfo.range_end, TCL_LINK_INT|TCL_LINK_READ_ONLY); /* "current" variable */ tclinfo.curbuf = Tcl_Alloc(VARNAME_SIZE); tclinfo.curwin = Tcl_Alloc(VARNAME_SIZE); name = tclgetbuffer(interp, curbuf); strcpy(tclinfo.curbuf, name); strcpy(varname, VAR_CURBUF); Tcl_LinkVar(interp, varname, (char *)&tclinfo.curbuf, TCL_LINK_STRING|TCL_LINK_READ_ONLY); name = tclgetwindow(interp, curwin); strcpy(tclinfo.curwin, name); strcpy(varname, VAR_CURWIN); Tcl_LinkVar(interp, varname, (char *)&tclinfo.curwin, TCL_LINK_STRING|TCL_LINK_READ_ONLY); tclinfo.interp = interp; } else { /* Interpreter already exists, just update variables */ tclinfo.range_start = row2tcl(eap->line1); tclinfo.range_end = row2tcl(eap->line2); tclupdatevars(); } tclinfo.exitvalue = 0; return OK; } static void tclerrmsg(text) char *text; { char *next; while ((next=strchr(text, '\n'))) { *next++ = '\0'; EMSG(text); text = next; } if (*text) EMSG(text); } static void tclmsg(text) char *text; { char *next; while ((next=strchr(text, '\n'))) { *next++ = '\0'; MSG(text); text = next; } if (*text) MSG(text); } static void tcldelthisinterp() { if (!Tcl_InterpDeleted(tclinfo.interp)) Tcl_DeleteInterp(tclinfo.interp); Tcl_Release(tclinfo.interp); /* The interpreter is now gets deleted. All registered commands (esp. * window and buffer commands) are deleted, triggering their deletion * callback, which deletes all refs pointing to this interpreter. * We could garbage-collect the unused ref structs in all windows and * buffers, but unless the user creates hundreds of sub-interpreters * all referring to lots of windows and buffers, this is hardly worth * the effort. Unused refs are recycled by other interpreters, and * all refs are free'd when the window/buffer gets closed by vim. */ tclinfo.interp = NULL; Tcl_Free(tclinfo.curbuf); Tcl_Free(tclinfo.curwin); tclinfo.curbuf = tclinfo.curwin = NULL; } static int tclexit(error) int error; { int newerr = OK; if (Tcl_InterpDeleted(tclinfo.interp) /* True if we intercepted Tcl's exit command */ #if (TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION >= 5) || TCL_MAJOR_VERSION > 8 || Tcl_LimitExceeded(tclinfo.interp) /* True if the interpreter cannot continue */ #endif ) { char buf[50]; sprintf(buf, _("E572: exit code %d"), tclinfo.exitvalue); tclerrmsg(buf); if (tclinfo.exitvalue == 0) { did_emsg = 0; newerr = OK; } else newerr = FAIL; tcldelthisinterp(); } else { char *result; result = (char *)Tcl_GetStringResult(tclinfo.interp); if (error == TCL_OK) { tclmsg(result); newerr = OK; } else { tclerrmsg(result); newerr = FAIL; } } return newerr; } /* * ":tcl" */ void ex_tcl(eap) exarg_T *eap; { char_u *script; int err; script = script_get(eap, eap->arg); if (!eap->skip) { err = tclinit(eap); if (err == OK) { Tcl_AllowExceptions(tclinfo.interp); if (script == NULL) err = Tcl_Eval(tclinfo.interp, (char *)eap->arg); else err = Tcl_Eval(tclinfo.interp, (char *)script); err = tclexit(err); } } vim_free(script); } /* * ":tclfile" */ void ex_tclfile(eap) exarg_T *eap; { char *file = (char *)eap->arg; int err; err = tclinit(eap); if (err == OK) { Tcl_AllowExceptions(tclinfo.interp); err = Tcl_EvalFile(tclinfo.interp, file); err = tclexit(err); } } /* * ":tcldo" */ void ex_tcldo(eap) exarg_T *eap; { char *script, *line; int err, rs, re, lnum; char var_lnum[VARNAME_SIZE]; /* must be writeable memory */ char var_line[VARNAME_SIZE]; linenr_T first_line = 0; linenr_T last_line = 0; rs = eap->line1; re = eap->line2; script = (char *)eap->arg; strcpy(var_lnum, VAR_CURLNUM); strcpy(var_line, VAR_CURLINE); err = tclinit(eap); if (err != OK) return; lnum = row2tcl(rs); Tcl_LinkVar(tclinfo.interp, var_lnum, (char *)&lnum, TCL_LINK_INT|TCL_LINK_READ_ONLY); err = TCL_OK; if (u_save((linenr_T)(rs-1), (linenr_T)(re+1)) != OK) { Tcl_SetResult(tclinfo.interp, _("cannot save undo information"), TCL_STATIC); err = TCL_ERROR; } while (err == TCL_OK && rs <= re) { line = (char *)ml_get_buf(curbuf, (linenr_T)rs, FALSE); if (!line) { Tcl_SetResult(tclinfo.interp, _("cannot get line"), TCL_STATIC); err = TCL_ERROR; break; } Tcl_SetVar(tclinfo.interp, var_line, line, 0); Tcl_AllowExceptions(tclinfo.interp); err = Tcl_Eval(tclinfo.interp, script); if (err != TCL_OK || Tcl_InterpDeleted(tclinfo.interp) #if (TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION >= 5) || TCL_MAJOR_VERSION > 8 || Tcl_LimitExceeded(tclinfo.interp) #endif ) break; line = (char *)Tcl_GetVar(tclinfo.interp, var_line, 0); if (line) { if (ml_replace((linenr_T)rs, (char_u *)line, TRUE) != OK) { Tcl_SetResult(tclinfo.interp, _("cannot replace line"), TCL_STATIC); err = TCL_ERROR; break; } if (first_line == 0) first_line = rs; last_line = rs; } ++rs; ++lnum; Tcl_UpdateLinkedVar(tclinfo.interp, var_lnum); } if (first_line) changed_lines(first_line, 0, last_line + 1, (long)0); Tcl_UnsetVar(tclinfo.interp, var_line, 0); Tcl_UnlinkVar(tclinfo.interp, var_lnum); if (err == TCL_OK) Tcl_ResetResult(tclinfo.interp); (void)tclexit(err); } static void tcldelallrefs(ref) struct ref *ref; { struct ref *next; int err; char *result; while (ref != NULL) { next = ref->next; if (ref->interp) { if (ref->delcmd) { err = Tcl_GlobalEvalObj(ref->interp, ref->delcmd); if (err != TCL_OK) { result = (char *)Tcl_GetStringResult(ref->interp); if (result) tclerrmsg(result); } Tcl_DecrRefCount(ref->delcmd); ref->delcmd = NULL; } Tcl_DeleteCommandFromToken(ref->interp, ref->cmd); } Tcl_Free((char *)ref); ref = next; } } void tcl_buffer_free(buf) buf_T *buf; { struct ref *reflist; #ifdef DYNAMIC_TCL if (!stubs_initialized) /* Not using Tcl, nothing to do. */ return; #endif reflist = (struct ref *)(buf->b_tcl_ref); if (reflist != &refsdeleted) { buf->b_tcl_ref = (void *)&refsdeleted; tcldelallrefs(reflist); buf->b_tcl_ref = NULL; } } #if defined(FEAT_WINDOWS) || defined(PROTO) void tcl_window_free(win) win_T *win; { struct ref *reflist; #ifdef DYNAMIC_TCL if (!stubs_initialized) /* Not using Tcl, nothing to do. */ return; #endif reflist = (struct ref*)(win->w_tcl_ref); if (reflist != &refsdeleted) { win->w_tcl_ref = (void *)&refsdeleted; tcldelallrefs(reflist); win->w_tcl_ref = NULL; } } #endif /* The End */
zyz2011-vim
src/if_tcl.c
C
gpl2
49,479
rem To be used on MS-Windows when using the Visual C++ Toolkit 2003 rem See INSTALLpc.txt for information. set PATH=%SystemRoot%\Microsoft.NET\Framework\v1.1.4322;%PATH% call "%VCToolkitInstallDir%vcvars32.bat" set MSVCVer=7.1 rem The platform SDK can be installed elsewhere, adjust the path. call "%ProgramFiles%\Microsoft Platform SDK\SetEnv.Cmd" rem call "e:\Microsoft Platform SDK\SetEnv.Cmd" set LIB=%ProgramFiles%\Microsoft Visual Studio .NET 2003\Vc7\lib;%LIB%
zyz2011-vim
src/msvcsetup.bat
Batchfile
gpl2
471
# List of distributed Vim files. # Used by Makefile and upload.aap. # source files for all source archives SRC_ALL = \ src/README.txt \ src/arabic.c \ src/arabic.h \ src/ascii.h \ src/blowfish.c \ src/buffer.c \ src/charset.c \ src/diff.c \ src/digraph.c \ src/edit.c \ src/eval.c \ src/ex_cmds.c \ src/ex_cmds.h \ src/ex_cmds2.c \ src/ex_docmd.c \ src/ex_eval.c \ src/ex_getln.c \ src/farsi.c \ src/farsi.h \ src/feature.h \ src/fileio.c \ src/fold.c \ src/getchar.c \ src/globals.h \ src/gui.c \ src/gui.h \ src/gui_beval.c \ src/gui_beval.h \ src/hardcopy.c \ src/hashtab.c \ src/keymap.h \ src/macros.h \ src/main.c \ src/mark.c \ src/mbyte.c \ src/memfile.c \ src/memfile_test.c \ src/memline.c \ src/menu.c \ src/message.c \ src/misc1.c \ src/misc2.c \ src/move.c \ src/mysign \ src/nbdebug.c \ src/nbdebug.h \ src/netbeans.c \ src/normal.c \ src/ops.c \ src/option.c \ src/option.h \ src/popupmnu.c \ src/quickfix.c \ src/regexp.c \ src/regexp.h \ src/screen.c \ src/search.c \ src/sha256.c \ src/structs.h \ src/spell.c \ src/syntax.c \ src/tag.c \ src/term.c \ src/term.h \ src/termlib.c \ src/ui.c \ src/undo.c \ src/version.c \ src/version.h \ src/vim.h \ src/window.c \ src/xxd/xxd.c \ src/main.aap \ src/testdir/main.aap \ src/testdir/*.in \ src/testdir/test[0-9]*.ok \ src/testdir/test49.vim \ src/testdir/test60.vim \ src/testdir/test83-tags? \ src/proto.h \ src/proto/blowfish.pro \ src/proto/buffer.pro \ src/proto/charset.pro \ src/proto/diff.pro \ src/proto/digraph.pro \ src/proto/edit.pro \ src/proto/eval.pro \ src/proto/ex_cmds.pro \ src/proto/ex_cmds2.pro \ src/proto/ex_docmd.pro \ src/proto/ex_eval.pro \ src/proto/ex_getln.pro \ src/proto/fileio.pro \ src/proto/fold.pro \ src/proto/getchar.pro \ src/proto/gui.pro \ src/proto/gui_beval.pro \ src/proto/hardcopy.pro \ src/proto/hashtab.pro \ src/proto/main.pro \ src/proto/mark.pro \ src/proto/mbyte.pro \ src/proto/memfile.pro \ src/proto/memline.pro \ src/proto/menu.pro \ src/proto/message.pro \ src/proto/misc1.pro \ src/proto/misc2.pro \ src/proto/move.pro \ src/proto/netbeans.pro \ src/proto/normal.pro \ src/proto/ops.pro \ src/proto/option.pro \ src/proto/popupmnu.pro \ src/proto/quickfix.pro \ src/proto/regexp.pro \ src/proto/screen.pro \ src/proto/search.pro \ src/proto/sha256.pro \ src/proto/spell.pro \ src/proto/syntax.pro \ src/proto/tag.pro \ src/proto/term.pro \ src/proto/termlib.pro \ src/proto/ui.pro \ src/proto/undo.pro \ src/proto/version.pro \ src/proto/window.pro \ # source files for Unix only SRC_UNIX = \ Makefile \ Filelist \ README_src.txt \ configure \ pixmaps/*.xpm \ pixmaps/gen-inline-pixbufs.sh \ pixmaps/stock_icons.h \ src/INSTALL \ src/INSTALLx.txt \ src/Makefile \ src/auto/configure \ src/config.aap.in \ src/config.h.in \ src/config.mk.dist \ src/config.mk.in \ src/configure \ src/configure.in \ src/gui_at_fs.c \ src/gui_at_sb.c \ src/gui_at_sb.h \ src/gui_athena.c \ src/gui_gtk.c \ src/gui_gtk_f.c \ src/gui_gtk_f.h \ src/gui_gtk_x11.c \ src/gui_motif.c \ src/gui_xmdlg.c \ src/gui_xmebw.c \ src/gui_xmebw.h \ src/gui_xmebwp.h \ src/gui_x11.c \ src/gui_x11_pm.h \ src/hangulin.c \ src/if_xcmdsrv.c \ src/integration.c \ src/integration.h \ src/link.sh \ src/installman.sh \ src/installml.sh \ src/mkinstalldirs \ src/os_unix.c \ src/os_unix.h \ src/os_unixx.h \ src/osdef.sh \ src/osdef1.h.in \ src/osdef2.h.in \ src/pathdef.sh \ src/proto/gui_athena.pro \ src/proto/gui_gtk.pro \ src/proto/gui_gtk_x11.pro \ src/proto/gui_motif.pro \ src/proto/gui_xmdlg.pro \ src/proto/gui_x11.pro \ src/proto/hangulin.pro \ src/proto/if_xcmdsrv.pro \ src/proto/os_unix.pro \ src/proto/pty.pro \ src/proto/workshop.pro \ src/pty.c \ src/testdir/Makefile \ src/testdir/unix.vim \ src/toolcheck \ src/vim_icon.xbm \ src/vim_mask.xbm \ src/vimtutor \ src/gvimtutor \ src/which.sh \ src/workshop.c \ src/workshop.h \ src/wsdebug.c \ src/wsdebug.h \ src/xxd/Makefile \ # source files for both DOS and Unix SRC_DOS_UNIX = \ src/if_cscope.c \ src/if_cscope.h \ src/if_lua.c \ src/if_mzsch.c \ src/if_mzsch.h \ src/if_perl.xs \ src/if_perlsfio.c \ src/if_python.c \ src/if_python3.c \ src/if_py_both.h \ src/if_ruby.c \ src/if_sniff.h \ src/if_tcl.c \ src/proto/if_cscope.pro \ src/proto/if_lua.pro \ src/proto/if_mzsch.pro \ src/proto/if_perl.pro \ src/proto/if_perlsfio.pro \ src/proto/if_python.pro \ src/proto/if_python3.pro \ src/proto/if_ruby.pro \ src/proto/if_tcl.pro \ src/typemap \ # source files for DOS (also in the extra archive) SRC_DOS = \ src/GvimExt/*.mak \ src/GvimExt/GvimExt.reg \ src/GvimExt/Makefile \ src/GvimExt/README.txt \ src/GvimExt/gvimext.cpp \ src/GvimExt/gvimext.def \ src/GvimExt/gvimext.h \ src/GvimExt/gvimext.inf \ src/GvimExt/gvimext.rc \ src/GvimExt/gvimext_ming.def \ src/GvimExt/gvimext_ming.rc \ src/GvimExt/resource.h \ src/GvimExt/uninst.bat \ README_srcdos.txt \ src/INSTALLpc.txt \ src/Make_bc3.mak \ src/Make_bc5.mak \ src/Make_cyg.mak \ src/Make_djg.mak \ src/Make_ivc.mak \ src/Make_dvc.mak \ src/Make_ming.mak \ src/Make_mvc.mak \ src/Make_w16.mak \ src/bigvim.bat \ src/msvcsetup.bat \ src/msvc2008.bat \ src/msvc2010.bat \ src/dimm.idl \ src/dlldata.c \ src/dosinst.c \ src/dosinst.h \ src/glbl_ime.cpp \ src/glbl_ime.h \ src/gui_w16.c \ src/gui_w32.c \ src/gui_w48.c \ src/guiw16rc.h \ src/gui_w32_rc.h \ src/if_ole.cpp \ src/if_ole.h \ src/if_ole.idl \ src/iid_ole.c \ src/os_dos.h \ src/os_msdos.c \ src/os_msdos.h \ src/os_w32dll.c \ src/os_w32exe.c \ src/os_win16.c \ src/os_win32.c \ src/os_mswin.c \ src/os_win16.h \ src/os_win32.h \ src/proto/gui_w16.pro \ src/proto/gui_w32.pro \ src/proto/if_ole.pro \ src/proto/os_msdos.pro \ src/proto/os_win16.pro \ src/proto/os_win32.pro \ src/proto/os_mswin.pro \ src/testdir/Make_dos.mak \ src/testdir/Make_ming.mak \ src/testdir/dos.vim \ src/uninstal.c \ src/vim.def \ src/vim.rc \ src/vimio.h \ src/gvim.exe.mnf \ src/vim16.def \ src/vim16.rc \ src/vimrun.c \ src/vimtbar.h \ src/xpm_w32.c \ src/xpm_w32.h \ src/xxd/Make_bc3.mak \ src/xxd/Make_bc5.mak \ src/xxd/Make_cyg.mak \ src/xxd/Make_djg.mak \ src/xxd/Make_ming.mak \ src/xxd/Make_mvc.mak \ nsis/gvim.nsi \ nsis/README.txt \ uninstal.txt \ src/VisVim/Commands.cpp \ src/VisVim/Commands.h \ src/VisVim/DSAddIn.cpp \ src/VisVim/DSAddIn.h \ src/VisVim/OleAut.cpp \ src/VisVim/OleAut.h \ src/VisVim/README_VisVim.txt \ src/VisVim/Reg.cpp \ src/VisVim/Register.bat \ src/VisVim/Resource.h \ src/VisVim/StdAfx.cpp \ src/VisVim/StdAfx.h \ src/VisVim/UnRegist.bat \ src/VisVim/VisVim.cpp \ src/VisVim/VisVim.def \ src/VisVim/VisVim.mak \ src/VisVim/VisVim.h \ src/VisVim/VisVim.odl \ src/VisVim/VisVim.rc \ src/VisVim/VsReadMe.txt \ # source files for DOS without CR/LF translation (also in the extra archive) SRC_DOS_BIN = \ src/VisVim/Res/*.bmp \ src/tearoff.bmp \ src/tools.bmp \ src/tools16.bmp \ src/vim*.ico \ src/vim.tlb \ src/vimtbar.lib \ src/vimtbar.dll \ nsis/icons/*.bmp \ nsis/icons/*.ico \ # source files for Amiga, DOS, etc. (also in the extra archive) SRC_AMI_DOS = \ # source files for Amiga (also in the extra archive) SRC_AMI = \ README_amisrc.txt \ README_amisrc.txt.info \ src.info \ src/INSTALLami.txt \ src/Make_dice.mak \ src/Make_manx.mak \ src/Make_morph.mak \ src/Make_sas.mak \ src/os_amiga.c \ src/os_amiga.h \ src/proto/os_amiga.pro \ src/testdir/Make_amiga.mak \ src/testdir/amiga.vim \ src/xxd/Make_amiga.mak \ # source files for the Mac (also in the extra archive) SRC_MAC = \ src/INSTALLmac.txt \ src/dehqx.py \ src/gui_mac.c \ src/os_mac_rsrc/*.icns \ src/os_mac.h \ src/os_mac.rsr.hqx \ src/os_mac_conv.c \ src/os_macosx.m \ src/proto/gui_mac.pro \ src/proto/os_mac_conv.pro \ # source files for VMS (in the extra archive) SRC_VMS = \ src/INSTALLvms.txt \ src/Make_vms.mms \ src/gui_gtk_vms.h \ src/os_vms.c \ src/os_vms_conf.h \ src/os_vms_mms.c \ src/proto/os_vms.pro \ src/testdir/Make_vms.mms \ src/testdir/vms.vim \ src/xxd/Make_vms.mms \ vimtutor.com \ # source files for OS/2 (in the extra archive) SRC_OS2 = \ src/Make_os2.mak \ src/os_os2_cfg.h \ src/testdir/Make_os2.mak \ src/testdir/todos.vim \ src/testdir/os2.vim \ src/xxd/Make_os2.mak \ # source files for QNX (in the extra archive) SRC_QNX = \ src/os_qnx.c \ src/os_qnx.h \ src/gui_photon.c \ src/proto/gui_photon.pro \ src/proto/os_qnx.pro \ # source files for the extra archive (all sources that are not for Unix) SRC_EXTRA = \ $(SRC_AMI) \ $(SRC_AMI_DOS) \ $(SRC_DOS) \ $(SRC_DOS_BIN) \ $(SRC_MAC) \ $(SRC_OS2) \ $(SRC_QNX) \ $(SRC_VMS) \ README_os390.txt \ src/Make_mint.mak \ src/if_sniff.c \ src/infplist.xml \ src/link.390 \ src/os_beos.c \ src/os_beos.h \ src/os_beos.rsrc \ src/os_mint.h \ src/os_vms_fix.com \ src/toolbar.phi \ # runtime files for all distributions RT_ALL = \ README.txt \ runtime/bugreport.vim \ runtime/doc/*.awk \ runtime/doc/*.pl \ runtime/doc/*.txt \ runtime/doc/Makefile \ runtime/doc/doctags.c \ runtime/doc/vim.1 \ runtime/doc/evim.1 \ runtime/doc/vimdiff.1 \ runtime/doc/vimtutor.1 \ runtime/doc/xxd.1 \ runtime/ftoff.vim \ runtime/gvimrc_example.vim \ runtime/macros/README.txt \ runtime/macros/dvorak \ runtime/macros/editexisting.vim \ runtime/macros/hanoi/click.me \ runtime/macros/hanoi/hanoi.vim \ runtime/macros/hanoi/poster \ runtime/macros/justify.vim \ runtime/macros/less.sh \ runtime/macros/less.vim \ runtime/macros/life/click.me \ runtime/macros/life/life.vim \ runtime/macros/matchit.vim \ runtime/macros/matchit.txt \ runtime/macros/maze/README.txt \ runtime/macros/maze/[mM]akefile \ runtime/macros/maze/main.aap \ runtime/macros/maze/maze.c \ runtime/macros/maze/maze_5.78 \ runtime/macros/maze/maze_mac \ runtime/macros/maze/mazeansi.c \ runtime/macros/maze/mazeclean.c \ runtime/macros/maze/poster \ runtime/macros/shellmenu.vim \ runtime/macros/swapmous.vim \ runtime/macros/urm/README.txt \ runtime/macros/urm/examples \ runtime/macros/urm/urm \ runtime/macros/urm/urm.vim \ runtime/mswin.vim \ runtime/evim.vim \ runtime/optwin.vim \ runtime/ftplugin.vim \ runtime/ftplugof.vim \ runtime/indent.vim \ runtime/indoff.vim \ runtime/termcap \ runtime/tools/README.txt \ runtime/tools/[a-z]*[a-z0-9] \ runtime/tutor/README.txt \ runtime/tutor/tutor \ runtime/tutor/tutor.vim \ runtime/vimrc_example.vim \ # runtime files for all distributions without CR-NL translation RT_ALL_BIN = \ runtime/doc/tags \ runtime/print/*.ps \ # runtime script files RT_SCRIPTS = \ runtime/filetype.vim \ runtime/scripts.vim \ runtime/menu.vim \ runtime/macmap.vim \ runtime/delmenu.vim \ runtime/synmenu.vim \ runtime/makemenu.vim \ runtime/autoload/*.vim \ runtime/autoload/README.txt \ runtime/autoload/xml/*.vim \ runtime/colors/*.vim \ runtime/colors/README.txt \ runtime/compiler/*.vim \ runtime/compiler/README.txt \ runtime/indent/*.vim \ runtime/indent/README.txt \ runtime/ftplugin/*.vim \ runtime/ftplugin/logtalk.dict \ runtime/ftplugin/README.txt \ runtime/plugin/*.vim \ runtime/plugin/README.txt \ runtime/syntax/*.vim \ runtime/syntax/README.txt \ # Unix runtime RT_UNIX = \ README_unix.txt \ runtime/hi16-action-make.png \ runtime/hi22-action-make.png \ runtime/vim16x16.png \ runtime/vim16x16.xpm \ runtime/vim32x32.png \ runtime/vim32x32.xpm \ runtime/vim48x48.png \ runtime/vim48x48.xpm \ # Unix and DOS runtime without CR-LF translation RT_UNIX_DOS_BIN = \ runtime/vim16x16.gif \ runtime/vim32x32.gif \ runtime/vim48x48.gif \ # runtime not for unix or extra RT_NO_UNIX = \ # runtime for Amiga (also in the extra archive) RT_AMI_DOS = \ runtime/doc/vim.man \ runtime/doc/vimdiff.man \ runtime/doc/vimtutor.man \ runtime/doc/xxd.man \ # DOS runtime (also in the extra archive) RT_DOS = \ README_dos.txt \ runtime/rgb.txt \ vimtutor.bat \ # DOS runtime without CR-LF translation (also in the extra archive) RT_DOS_BIN = \ runtime/vimlogo.cdr \ runtime/vimlogo.eps \ runtime/vimlogo.gif \ runtime/vimlogo.pdf \ # Amiga runtime (also in the extra archive) RT_AMI = \ README.txt.info \ README_ami.txt \ README_ami.txt.info \ libs/arp.library \ runtime/doc.info \ runtime/doc/*.info \ runtime/icons/README.txt \ runtime/icons/*.info \ runtime/icons.info \ runtime/macros.info \ runtime/macros/*.info \ runtime/macros/hanoi/*.info \ runtime/macros/life/*.info \ runtime/macros/maze/*.info \ runtime/macros/urm/*.info \ runtime/tools.info \ runtime/tutor.info \ runtime/tutor/*.info \ # runtime files in extra archive RT_EXTRA = \ $(RT_AMI) \ $(RT_AMI_DOS) \ $(RT_DOS) \ $(RT_DOS_BIN) \ README_mac.txt \ # included in all Amiga archives ROOT_AMI = \ Contents \ Contents.info \ runtime.info \ vimdir.info \ # root files for the extra archive ROOT_EXTRA = \ $(ROOT_AMI) \ # files for Amiga small binary (also in extra archive) BIN_AMI = \ README_amibin.txt \ README_amibin.txt.info \ Vim.info \ Xxd.info \ # files for DOS binary (also in extra archive) BIN_DOS = \ README_bindos.txt \ uninstal.txt \ # files for Win32 OLE binary (also in extra archive) BIN_OLE = \ README_ole.txt \ # files for Win32s binary (also in extra archive) BIN_W32S = \ README_w32s.txt \ # files for VMS binary (also in extra archive) BIN_VMS = \ README_vms.txt \ # files for OS/2 binary (also in extra archive) BIN_OS2 = \ README_os2.txt \ # binary files for extra archive BIN_EXTRA = \ $(BIN_AMI) \ $(BIN_DOS) \ $(BIN_OLE) \ $(BIN_W32S) \ $(BIN_VMS) \ $(BIN_OS2) \ # all files for extra archive EXTRA = \ $(BIN_EXTRA) \ $(ROOT_EXTRA) \ $(RT_EXTRA) \ $(SRC_EXTRA) \ README_extra.txt \ src/VisVim/VisVim.dll \ farsi/README.txt \ farsi/fonts/*/far-* \ runtime/vimlogo.xpm \ src/swis.s \ src/tee/Makefile \ src/tee/tee.c \ csdpmi4b.zip \ # generic language files LANG_GEN = \ runtime/doc/*-fr.1 \ runtime/doc/*-fr.UTF-8.1 \ runtime/doc/*-it.1 \ runtime/doc/*-it.UTF-8.1 \ runtime/doc/*-pl.1 \ runtime/doc/*-pl.UTF-8.1 \ runtime/doc/*-ru.1 \ runtime/doc/*-ru.UTF-8.1 \ runtime/lang/README.txt \ runtime/lang/menu_*.vim \ runtime/keymap/README.txt \ runtime/keymap/*.vim \ runtime/tutor/README.*.txt \ runtime/tutor/Makefile \ runtime/tutor/tutor.utf-8 \ runtime/tutor/tutor.?? \ runtime/tutor/tutor.??.* \ runtime/tutor/tutor.bar \ runtime/tutor/tutor.bar.* \ runtime/spell/README.txt \ runtime/spell/??/*.diff \ runtime/spell/??/main.aap \ runtime/spell/tet/*.diff \ runtime/spell/tet/main.aap \ runtime/spell/check/main.aap \ runtime/spell/check/*.aff \ runtime/spell/check/*.dic \ runtime/spell/yi/README.txt \ runtime/spell/main.aap \ runtime/spell/*.vim \ # generic language files, binary LANG_GEN_BIN = \ runtime/spell/README_en.txt \ runtime/spell/en.ascii.spl \ runtime/spell/en.latin1.spl \ runtime/spell/en.utf-8.spl \ runtime/spell/en.ascii.sug \ runtime/spell/en.latin1.sug \ runtime/spell/en.utf-8.sug \ # all files for lang archive LANG_SRC = \ src/po/README.txt \ src/po/README_mingw.txt \ src/po/README_mvc.txt \ src/po/check.vim \ src/po/cleanup.vim \ src/po/Makefile \ src/po/Make_cyg.mak \ src/po/Make_ming.mak \ src/po/Make_mvc.mak \ src/po/sjiscorr.c \ src/po/*.po \ # the language files for the Win32 lang archive LANG_DOS = \ src/po/*.mo \ # vim: set ft=make:
zyz2011-vim
Filelist
Makefile
gpl2
16,118
" An example for a vimrc file. " " Maintainer: Bram Moolenaar <Bram@vim.org> " Last change: 2011 Apr 15 " " To use it, copy it to " for Unix and OS/2: ~/.vimrc " for Amiga: s:.vimrc " for MS-DOS and Win32: $VIM\_vimrc " for OpenVMS: sys$login:.vimrc " When started as "evim", evim.vim will already have done these settings. if v:progname =~? "evim" finish endif " Use Vim settings, rather than Vi settings (much better!). " This must be first, because it changes other options as a side effect. set nocompatible " allow backspacing over everything in insert mode set backspace=indent,eol,start if has("vms") set nobackup " do not keep a backup file, use versions instead else set backup " keep a backup file endif set history=50 " keep 50 lines of command line history set ruler " show the cursor position all the time set showcmd " display incomplete commands set incsearch " do incremental searching " For Win32 GUI: remove 't' flag from 'guioptions': no tearoff menu entries " let &guioptions = substitute(&guioptions, "t", "", "g") " Don't use Ex mode, use Q for formatting map Q gq " CTRL-U in insert mode deletes a lot. Use CTRL-G u to first break undo, " so that you can undo CTRL-U after inserting a line break. inoremap <C-U> <C-G>u<C-U> " In many terminal emulators the mouse works just fine, thus enable it. if has('mouse') set mouse=a endif " Switch syntax highlighting on, when the terminal has colors " Also switch on highlighting the last used search pattern. if &t_Co > 2 || has("gui_running") syntax on set hlsearch endif " Only do this part when compiled with support for autocommands. if has("autocmd") " Enable file type detection. " Use the default filetype settings, so that mail gets 'tw' set to 72, " 'cindent' is on in C files, etc. " Also load indent files, to automatically do language-dependent indenting. filetype plugin indent on " Put these in an autocmd group, so that we can delete them easily. augroup vimrcEx au! " For all text files set 'textwidth' to 78 characters. autocmd FileType text setlocal textwidth=78 " When editing a file, always jump to the last known cursor position. " Don't do it when the position is invalid or when inside an event handler " (happens when dropping a file on gvim). " Also don't do it when the mark is in the first line, that is the default " position when opening a file. autocmd BufReadPost * \ if line("'\"") > 1 && line("'\"") <= line("$") | \ exe "normal! g`\"" | \ endif augroup END else set autoindent " always set autoindenting on endif " has("autocmd") " Convenient command to see the difference between the current buffer and the " file it was loaded from, thus the changes you made. " Only define it when not defined already. if !exists(":DiffOrig") command DiffOrig vert new | set bt=nofile | r ++edit # | 0d_ | diffthis \ | wincmd p | diffthis endif
zyz2011-vim
runtime/vimrc_example.vim
Vim Script
gpl2
2,945
" Vim support file to switch off loading plugins for file types " " Maintainer: Bram Moolenaar <Bram@vim.org> " Last Change: 2011 Oct 20 if exists("did_load_ftplugin") unlet did_load_ftplugin endif " Remove all autocommands in the filetypeplugin group, if any exist. if exists("#filetypeplugin") silent! au! filetypeplugin * endif
zyz2011-vim
runtime/ftplugof.vim
Vim Script
gpl2
337
" Vim support file to switch on loading indent files for file types " " Maintainer: Bram Moolenaar <Bram@vim.org> " Last Change: 2008 Feb 22 if exists("did_indent_on") finish endif let did_indent_on = 1 augroup filetypeindent au FileType * call s:LoadIndent() func! s:LoadIndent() if exists("b:undo_indent") exe b:undo_indent unlet! b:undo_indent b:did_indent endif let s = expand("<amatch>") if s != "" if exists("b:did_indent") unlet b:did_indent endif " When there is a dot it is used to separate filetype names. Thus for " "aaa.bbb" load "indent/aaa.vim" and then "indent/bbb.vim". for name in split(s, '\.') exe 'runtime! indent/' . name . '.vim' endfor endif endfunc augroup END
zyz2011-vim
runtime/indent.vim
Vim Script
gpl2
767
" Vim support file to detect file types in scripts " " Maintainer: Bram Moolenaar <Bram@vim.org> " Last change: 2010 Sep 22 " This file is called by an autocommand for every file that has just been " loaded into a buffer. It checks if the type of file can be recognized by " the file contents. The autocommand is in $VIMRUNTIME/filetype.vim. " Only do the rest when the FileType autocommand has not been triggered yet. if did_filetype() finish endif " Load the user defined scripts file first " Only do this when the FileType autocommand has not been triggered yet if exists("myscriptsfile") && filereadable(expand(myscriptsfile)) execute "source " . myscriptsfile if did_filetype() finish endif endif " Line continuation is used here, remove 'C' from 'cpoptions' let s:cpo_save = &cpo set cpo&vim let s:line1 = getline(1) if s:line1 =~ "^#!" " A script that starts with "#!". " Check for a line like "#!/usr/bin/env VAR=val bash". Turn it into " "#!/usr/bin/bash" to make matching easier. if s:line1 =~ '^#!\s*\S*\<env\s' let s:line1 = substitute(s:line1, '\S\+=\S\+', '', 'g') let s:line1 = substitute(s:line1, '\<env\s\+', '', '') endif " Get the program name. " Only accept spaces in PC style paths: "#!c:/program files/perl [args]". " If the word env is used, use the first word after the space: " "#!/usr/bin/env perl [path/args]" " If there is no path use the first word: "#!perl [path/args]". " Otherwise get the last word after a slash: "#!/usr/bin/perl [path/args]". if s:line1 =~ '^#!\s*\a:[/\\]' let s:name = substitute(s:line1, '^#!.*[/\\]\(\i\+\).*', '\1', '') elseif s:line1 =~ '^#!.*\<env\>' let s:name = substitute(s:line1, '^#!.*\<env\>\s\+\(\i\+\).*', '\1', '') elseif s:line1 =~ '^#!\s*[^/\\ ]*\>\([^/\\]\|$\)' let s:name = substitute(s:line1, '^#!\s*\([^/\\ ]*\>\).*', '\1', '') else let s:name = substitute(s:line1, '^#!\s*\S*[/\\]\(\i\+\).*', '\1', '') endif " tcl scripts may have #!/bin/sh in the first line and "exec wish" in the " third line. Suggested by Steven Atkinson. if getline(3) =~ '^exec wish' let s:name = 'wish' endif " Bourne-like shell scripts: bash bash2 ksh ksh93 sh if s:name =~ '^\(bash\d*\|\|ksh\d*\|sh\)\>' call SetFileTypeSH(s:line1) " defined in filetype.vim " csh scripts elseif s:name =~ '^csh\>' if exists("g:filetype_csh") call SetFileTypeShell(g:filetype_csh) else call SetFileTypeShell("csh") endif " tcsh scripts elseif s:name =~ '^tcsh\>' call SetFileTypeShell("tcsh") " Z shell scripts elseif s:name =~ '^zsh\>' set ft=zsh " TCL scripts elseif s:name =~ '^\(tclsh\|wish\|expectk\|itclsh\|itkwish\)\>' set ft=tcl " Expect scripts elseif s:name =~ '^expect\>' set ft=expect " Gnuplot scripts elseif s:name =~ '^gnuplot\>' set ft=gnuplot " Makefiles elseif s:name =~ 'make\>' set ft=make " Lua elseif s:name =~ 'lua' set ft=lua " Perl 6 elseif s:name =~ 'perl6' set ft=perl6 " Perl elseif s:name =~ 'perl' set ft=perl " PHP elseif s:name =~ 'php' set ft=php " Python elseif s:name =~ 'python' set ft=python " Groovy elseif s:name =~ '^groovy\>' set ft=groovy " Ruby elseif s:name =~ 'ruby' set ft=ruby " BC calculator elseif s:name =~ '^bc\>' set ft=bc " sed elseif s:name =~ 'sed\>' set ft=sed " OCaml-scripts elseif s:name =~ 'ocaml' set ft=ocaml " Awk scripts elseif s:name =~ 'awk\>' set ft=awk " Website MetaLanguage elseif s:name =~ 'wml' set ft=wml " Scheme scripts elseif s:name =~ 'scheme' set ft=scheme " CFEngine scripts elseif s:name =~ 'cfengine' set ft=cfengine endif unlet s:name else " File does not start with "#!". let s:line2 = getline(2) let s:line3 = getline(3) let s:line4 = getline(4) let s:line5 = getline(5) " Bourne-like shell scripts: sh ksh bash bash2 if s:line1 =~ '^:$' call SetFileTypeSH(s:line1) " defined in filetype.vim " Z shell scripts elseif s:line1 =~ '^#compdef\>' || s:line1 =~ '^#autoload\>' || \ "\n".s:line1."\n".s:line2."\n".s:line3."\n".s:line4."\n".s:line5 =~ '\n\s*emulate\s\+\%(-[LR]\s\+\)\=[ckz]\=sh\>' set ft=zsh " ELM Mail files elseif s:line1 =~ '^From \([a-zA-Z][a-zA-Z_0-9\.=-]*\(@[^ ]*\)\=\|-\) .* \(19\|20\)\d\d$' set ft=mail " Mason elseif s:line1 =~ '^<[%&].*>' set ft=mason " Vim scripts (must have '" vim' as the first line to trigger this) elseif s:line1 =~ '^" *[vV]im$' set ft=vim " MOO elseif s:line1 =~ '^\*\* LambdaMOO Database, Format Version \%([1-3]\>\)\@!\d\+ \*\*$' set ft=moo " Diff file: " - "diff" in first line (context diff) " - "Only in " in first line " - "--- " in first line and "+++ " in second line (unified diff). " - "*** " in first line and "--- " in second line (context diff). " - "# It was generated by makepatch " in the second line (makepatch diff). " - "Index: <filename>" in the first line (CVS file) " - "=== ", line of "=", "---", "+++ " (SVK diff) " - "=== ", "--- ", "+++ " (bzr diff, common case) " - "=== (removed|added|renamed|modified)" (bzr diff, alternative) elseif s:line1 =~ '^\(diff\>\|Only in \|\d\+\(,\d\+\)\=[cda]\d\+\>\|# It was generated by makepatch \|Index:\s\+\f\+\r\=$\|===== \f\+ \d\+\.\d\+ vs edited\|==== //\f\+#\d\+\)' \ || (s:line1 =~ '^--- ' && s:line2 =~ '^+++ ') \ || (s:line1 =~ '^\* looking for ' && s:line2 =~ '^\* comparing to ') \ || (s:line1 =~ '^\*\*\* ' && s:line2 =~ '^--- ') \ || (s:line1 =~ '^=== ' && ((s:line2 =~ '^=\{66\}' && s:line3 =~ '^--- ' && s:line4 =~ '^+++') || (s:line2 =~ '^--- ' && s:line3 =~ '^+++ '))) \ || (s:line1 =~ '^=== \(removed\|added\|renamed\|modified\)') set ft=diff " PostScript Files (must have %!PS as the first line, like a2ps output) elseif s:line1 =~ '^%![ \t]*PS' set ft=postscr " M4 scripts: Guess there is a line that starts with "dnl". elseif s:line1 =~ '^\s*dnl\>' \ || s:line2 =~ '^\s*dnl\>' \ || s:line3 =~ '^\s*dnl\>' \ || s:line4 =~ '^\s*dnl\>' \ || s:line5 =~ '^\s*dnl\>' set ft=m4 " AmigaDos scripts elseif $TERM == "amiga" \ && (s:line1 =~ "^;" || s:line1 =~ '^\.[bB][rR][aA]') set ft=amiga " SiCAD scripts (must have procn or procd as the first line to trigger this) elseif s:line1 =~? '^ *proc[nd] *$' set ft=sicad " Purify log files start with "**** Purify" elseif s:line1 =~ '^\*\*\*\* Purify' set ft=purifylog " XML elseif s:line1 =~ '<?\s*xml.*?>' set ft=xml " XHTML (e.g.: PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN") elseif s:line1 =~ '\<DTD\s\+XHTML\s' set ft=xhtml " HTML (e.g.: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN") elseif s:line1 =~? '\<DOCTYPE\s\+html\>' set ft=html " PDF elseif s:line1 =~ '^%PDF-' set ft=pdf " XXD output elseif s:line1 =~ '^\x\{7}: \x\{2} \=\x\{2} \=\x\{2} \=\x\{2} ' set ft=xxd " RCS/CVS log output elseif s:line1 =~ '^RCS file:' || s:line2 =~ '^RCS file:' set ft=rcslog " CVS commit elseif s:line2 =~ '^CVS:' || getline("$") =~ '^CVS: ' set ft=cvs " Prescribe elseif s:line1 =~ '^!R!' set ft=prescribe " Send-pr elseif s:line1 =~ '^SEND-PR:' set ft=sendpr " SNNS files elseif s:line1 =~ '^SNNS network definition file' set ft=snnsnet elseif s:line1 =~ '^SNNS pattern definition file' set ft=snnspat elseif s:line1 =~ '^SNNS result file' set ft=snnsres " Virata elseif s:line1 =~ '^%.\{-}[Vv]irata' \ || s:line2 =~ '^%.\{-}[Vv]irata' \ || s:line3 =~ '^%.\{-}[Vv]irata' \ || s:line4 =~ '^%.\{-}[Vv]irata' \ || s:line5 =~ '^%.\{-}[Vv]irata' set ft=virata " Strace elseif s:line1 =~ '^\(\[pid \d\+\] \)\=[0-9:.]* *execve(' || s:line1 =~ '^__libc_start_main' set ft=strace " VSE JCL elseif s:line1 =~ '^\* $$ JOB\>' || s:line1 =~ '^// *JOB\>' set ft=vsejcl " TAK and SINDA elseif s:line4 =~ 'K & K Associates' || s:line2 =~ 'TAK 2000' set ft=takout elseif s:line3 =~ 'S Y S T E M S I M P R O V E D ' set ft=sindaout elseif getline(6) =~ 'Run Date: ' set ft=takcmp elseif getline(9) =~ 'Node File 1' set ft=sindacmp " DNS zone files elseif s:line1.s:line2.s:line3.s:line4 =~ '^; <<>> DiG [0-9.]\+ <<>>\|BIND.*named\|$ORIGIN\|$TTL\|IN\s\+SOA' set ft=bindzone " BAAN elseif s:line1 =~ '|\*\{1,80}' && s:line2 =~ 'VRC ' \ || s:line2 =~ '|\*\{1,80}' && s:line3 =~ 'VRC ' set ft=baan " Valgrind elseif s:line1 =~ '^==\d\+== valgrind' || s:line3 =~ '^==\d\+== Using valgrind' set ft=valgrind " Renderman Interface Bytestream elseif s:line1 =~ '^##RenderMan' set ft=rib " Scheme scripts elseif s:line1 =~ 'exec\s\+\S*scheme' || s:line2 =~ 'exec\s\+\S*scheme' set ft=scheme " Git output elseif s:line1 =~ '^\(commit\|tree\|object\) \x\{40\}\>\|^tag \S\+$' set ft=git " CVS diff else let s:lnum = 1 while getline(s:lnum) =~ "^? " && s:lnum < line("$") let s:lnum += 1 endwhile if getline(s:lnum) =~ '^Index:\s\+\f\+$' set ft=diff " locale input files: Formal Definitions of Cultural Conventions " filename must be like en_US, fr_FR@euro or en_US.UTF-8 elseif expand("%") =~ '\a\a_\a\a\($\|[.@]\)\|i18n$\|POSIX$\|translit_' let s:lnum = 1 while s:lnum < 100 && s:lnum < line("$") if getline(s:lnum) =~ '^LC_\(IDENTIFICATION\|CTYPE\|COLLATE\|MONETARY\|NUMERIC\|TIME\|MESSAGES\|PAPER\|TELEPHONE\|MEASUREMENT\|NAME\|ADDRESS\)$' setf fdcc break endif let s:lnum += 1 endwhile endif unlet s:lnum endif unlet s:line2 s:line3 s:line4 s:line5 endif " Restore 'cpoptions' let &cpo = s:cpo_save unlet s:cpo_save s:line1
zyz2011-vim
runtime/scripts.vim
Vim Script
gpl2
9,880
" Set options and add mapping such that Vim behaves a lot like MS-Windows " " Maintainer: Bram Moolenaar <Bram@vim.org> " Last change: 2006 Apr 02 " bail out if this isn't wanted (mrsvim.vim uses this). if exists("g:skip_loading_mswin") && g:skip_loading_mswin finish endif " set the 'cpoptions' to its Vim default if 1 " only do this when compiled with expression evaluation let s:save_cpo = &cpoptions endif set cpo&vim " set 'selection', 'selectmode', 'mousemodel' and 'keymodel' for MS-Windows behave mswin " backspace and cursor keys wrap to previous/next line set backspace=indent,eol,start whichwrap+=<,>,[,] " backspace in Visual mode deletes selection vnoremap <BS> d " CTRL-X and SHIFT-Del are Cut vnoremap <C-X> "+x vnoremap <S-Del> "+x " CTRL-C and CTRL-Insert are Copy vnoremap <C-C> "+y vnoremap <C-Insert> "+y " CTRL-V and SHIFT-Insert are Paste map <C-V> "+gP map <S-Insert> "+gP cmap <C-V> <C-R>+ cmap <S-Insert> <C-R>+ " Pasting blockwise and linewise selections is not possible in Insert and " Visual mode without the +virtualedit feature. They are pasted as if they " were characterwise instead. " Uses the paste.vim autoload script. exe 'inoremap <script> <C-V>' paste#paste_cmd['i'] exe 'vnoremap <script> <C-V>' paste#paste_cmd['v'] imap <S-Insert> <C-V> vmap <S-Insert> <C-V> " Use CTRL-Q to do what CTRL-V used to do noremap <C-Q> <C-V> " Use CTRL-S for saving, also in Insert mode noremap <C-S> :update<CR> vnoremap <C-S> <C-C>:update<CR> inoremap <C-S> <C-O>:update<CR> " For CTRL-V to work autoselect must be off. " On Unix we have two selections, autoselect can be used. if !has("unix") set guioptions-=a endif " CTRL-Z is Undo; not in cmdline though noremap <C-Z> u inoremap <C-Z> <C-O>u " CTRL-Y is Redo (although not repeat); not in cmdline though noremap <C-Y> <C-R> inoremap <C-Y> <C-O><C-R> " Alt-Space is System menu if has("gui") noremap <M-Space> :simalt ~<CR> inoremap <M-Space> <C-O>:simalt ~<CR> cnoremap <M-Space> <C-C>:simalt ~<CR> endif " CTRL-A is Select all noremap <C-A> gggH<C-O>G inoremap <C-A> <C-O>gg<C-O>gH<C-O>G cnoremap <C-A> <C-C>gggH<C-O>G onoremap <C-A> <C-C>gggH<C-O>G snoremap <C-A> <C-C>gggH<C-O>G xnoremap <C-A> <C-C>ggVG " CTRL-Tab is Next window noremap <C-Tab> <C-W>w inoremap <C-Tab> <C-O><C-W>w cnoremap <C-Tab> <C-C><C-W>w onoremap <C-Tab> <C-C><C-W>w " CTRL-F4 is Close window noremap <C-F4> <C-W>c inoremap <C-F4> <C-O><C-W>c cnoremap <C-F4> <C-C><C-W>c onoremap <C-F4> <C-C><C-W>c " restore 'cpoptions' set cpo& if 1 let &cpoptions = s:save_cpo unlet s:save_cpo endif
zyz2011-vim
runtime/mswin.vim
Vim Script
gpl2
2,587